code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
//
// partial2js
// Copyright (c) 2014 Dennis Sänger
// Licensed under the MIT
// http://opensource.org/licenses/MIT
//
"use strict";
var glob = require('glob-all');
var fs = require('fs');
var path = require('path');
var stream = require('stream');
var htmlmin = require('html-minifier').minify;
var escape = require('js-string-escape');
var eol = require('os').EOL;
function Partial2Js( opts ) {
opts = opts || {};
var self = this;
this.debug = !!opts.debug;
this.patterns = [];
this.files = [];
this.contents = {};
this.uniqueFn = function( file ) {
return file;
};
var log = (function log() {
if ( this.debug ) {
console.log.apply( console, arguments );
}
}).bind( this );
var find = (function() {
this.files = glob.sync( this.patterns.slice( 0 )) || [];
}).bind( this );
function cleanPatterns( patterns ) {
return patterns.map(function( entry ) {
return entry.replace(/\/\*+/g, '');
});
}
function compare( patterns, a, b ) {
return matchInPattern( patterns, a ) - matchInPattern( patterns, b );
}
var sort = (function() {
var clean = cleanPatterns( this.patterns );
this.files.sort(function( a, b ) {
return compare( clean, a, b );
});
}).bind( this );
//
// this function is not every functional ;)
// Should use findIndex() [ES6] as soon as possible
//
function matchInPattern( patterns, entry ) {
var res = patterns.length + 100;
patterns.every(function( pattern, index ) {
if ( entry.indexOf( pattern ) > -1 ) {
res = index;
return false;
}
return true;
});
return res;
}
var unique = (function() {
if ( typeof this.uniqueFn === 'function' && this.files && this.files.length ) {
var obj = {};
this.files.forEach(function( file ) {
var key = self.uniqueFn( file );
if ( !obj[key] ) {
obj[key] = file;
}
});
this.files = obj;
}
}).bind( this );
var asString = (function( moduleName ) {
var buffer = '';
buffer += '(function(window,document){' + eol;
buffer += '"use strict";' + eol;
buffer += 'angular.module("'+moduleName+'",[]).run(["$templateCache",function($templateCache){' + eol;
for ( var k in this.contents ) {
buffer += ' $templateCache.put("'+k+'","'+this.contents[k]+'");' + eol;
}
buffer += '}]);' + eol;
buffer += '})(window,document);';
return buffer;
}).bind( this );
var read = (function() {
var id, path, stat;
this.contents = {};
for( var k in this.files ) {
id = k;
path = this.files[k];
stat = fs.statSync( path );
if ( stat.isFile()) {
log('read file:', path, '=>', id );
this.contents[id] = fs.readFileSync( path );
}
}
return this.contents;
}).bind( this );
var asStream = function( string ) {
var s = new stream.Readable();
s._read = function noop() {};
s.push( string );
s.push(null);
return s;
};
var minify = (function() {
var opts = {
collapseWhitespace: true,
preserveLineBreaks: false,
removeComments: true,
removeRedundantAttributes: true,
removeEmptyAttributes: false,
keepClosingSlash: true,
maxLineLength: 0,
customAttrCollapse: /.+/,
html5: true
};
for ( var k in this.contents ) {
this.contents[k] = escape(htmlmin( String(this.contents[k]), opts ));
}
}).bind( this );
this.add = function( pattern ) {
this.patterns.push( pattern );
return this;
};
this.not = function( pattern ) {
this.patterns.push( '!'+pattern );
return this;
};
this.folder = function( folder ) {
if ( folder && String( folder ) === folder ) {
folder = path.resolve( folder ) + '/**/*';
this.patterns.push( folder );
}
return this;
};
this.unique = function( fn ) {
this.uniqueFn = fn;
return this;
};
this.stringify = function( moduleName ) {
find();
sort();
unique();
read();
minify();
return asString( moduleName );
};
this.stream = function( moduleName ) {
return asStream( this.stringify( moduleName ) );
};
}
module.exports = function( opts ) {
return new Partial2Js( opts );
};
| ds82/partial2js | index.js | JavaScript | mit | 4,307 |
---
layout: post
title: Creating a gem with bundler
date: 2013-11-26 10:48:31
disqus: n
---
A trick I am learning since 2 years ago : splitting up even more of the main code base into smaller parts. The ideas behind this are numerous : from speeding up tests to keeping things simple.
Defining sub parts of the product as gems allows to enforce stricter rules on the APIs changes, keep each test suite small and independent and stick to principles and rules dear to OO programmers and OO designers.
And in the same manner rather than using Rspec and tons of gems to test drive the development of each gem I rely on something that’s already coming with Ruby : Minitest.
## A great companion for the journey
After a quick search I found a great Minitest quick reference from Matt Sears (http://mattsears.com/articles/2011/12/10/minitest-quick-reference). It has been very helpful to jump on the minitest train with my Rspec habits. I only had to look for something else when I started to mock objects and messages.
## Starting a gem
Bundler has the great taste to come with a way to create a gem skeleton : ```bundle gem```.
And if you ask bundle a bit of details about that ```gem``` command :
```
bundle help gem
Usage:
bundle gem GEM
Options:
-b, [--bin=Generate a binary for your library.]
-t, [--test=Generate a test directory for your library: 'rspec' is the default, but 'minitest' is also supported.]
-e, [--edit=/path/to/your/editor] # Open generated gemspec in the specified editor (defaults to $EDITOR or $BUNDLER_EDITOR)
[--no-color=Disable colorization in output]
-V, [--verbose=Enable verbose output mode]
Creates a skeleton for creating a rubygem
```
Let’s run it :
```
$ bundle gem foo -t minitest
create foo/Gemfile
create foo/Rakefile
create foo/LICENSE.txt
create foo/README.md
create foo/.gitignore
create foo/foo.gemspec
create foo/lib/foo.rb
create foo/lib/foo/version.rb
create foo/test/minitest_helper.rb
create foo/test/test_foo.rb
create foo/.travis.yml
Initializating git repo in /Users/ange/Code/gems/test/foo
```
The command creates a *foo* directory and create everything you need to start working on a new gem :
* a *Gemfile* (yet it’s mostly empty)
* a *Rakefile*
* a *LICENSE* (MIT license, by default it considers you are going open source)
* a basic *README* with minimal sections
* a *.gitignore* file already filed with usual files and paths
* a *foo.gemspec* file that contains the description of your gem, the gem development and running dependencies and your contact informations
* then there is the initial, almost empty, files for your gem placed and named following the classic practices of the Ruby community, including *minitest* base setup.
* as a bonus there is a minimal *.travis.yml* config file so you can push your code to a public repository on github and get the tests runnings right away !
## Gemspec
Contrary to a Ruby application (such as a Sinatra or Rails app) you don’t define your gem dependencies in a Gemfile. You define them in the gem spec file :
```
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'foo/version'
Gem::Specification.new do |spec|
spec.name = "foo"
spec.version = Foo::VERSION
spec.authors = ["Thomas Riboulet"]
spec.email = ["[email protected]”]
spec.description = %q{TODO: Write a gem description}
spec.summary = %q{TODO: Write a gem summary}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "minitest"
spec.add_dependency “faraday”
end
```
This gemspec is the one generated by bundler. We can see that it includes the gem name, the version (using the Foo::VERSION constant inherited from the ```require ‘foo/version’``` line. It also includes my name, email, the description and summary of the gem, a homepage and license.
Bundler will use git tricks to list the files, and some ruby tricks to list executables and test files.
The dependencies come last with first the development dependencies and then the dependencies. The first ones will be needed to develop, the later just to use the gem.
## Minitest
Now I do like to have a default test setup ready but this one lacks colours and readability to my taste.
I did not know about the -t flag until I did some research for this post. I was happy to see it in but I do prefer my setup and way :
```
# test helper
require 'minitest/autorun'
require 'minitest/pride'
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'foo'
```
Pride will add a bit of colours to the output. (Look around there is also a way to have a nyan cat running across the screen).
The Rake file is ok but here is an alternative one :
```
# Rakefile
require "bundler/gem_tasks"
desc "Run all tests"
task :test do
Dir.glob('./test/**/test_*.rb').each { |file| require file }
end
task :default => :test
```
It’s a bit simpler to read and there is less libs required. It’s using a very simple mechanism to run all tests : *Dir.glob* call on the test directory plus a *require* for each test file.
## Test file template
As you can see from the previous Rakefile and the initial run of bundler the naming rule for minitest test files is to *prefix* the name of the tested class with *test_*.
I am not going to give a crash course on Minitest : all you have to know is described in the **excellent** article from Matt Sears.
What I can show you is a basic template.
```
require_relative ‘../../minitest_helper'
describe Foo do
describe "setup" do
it “should respond to setup” do
subject.must_respond_to(:setup)
end
end
end
```
The first line might look odd to some : I usually keep the Rails’ habit to sort my tests the same way the tested classes are. It keeps thing a bit nittier all around.
```
Foo/
lib/
foo.rb
foo/
sub_foo.rb
test/
minitest_helper.rb
lib/
test_foo.rb
foo/
test_sub_foo.rb
```
That’s why the require relative is a playing with paths.
## Other gems I use with Minitest
### VCR
For those who don’t know VCR it’s a nifty tool that allows you to record http transactions with external services and replay them. It allows you to speed up test and also to avoid calling 100 times a minute a remote service. Bonus point : you can work offline if you have a set of recordings.
VCR uses *cassettes* to record and replay. Cassettes are YAML files that you can edit yourself if you ever want to. There is a simple setup to do in your test helper :
```
VCR.configure do |c|
c.default_cassette_options = { :record => :new_episodes }
c.cassette_library_dir = 'test/vcr/cassettes'
c.hook_into :faraday
end
```
You can setup default cassette options such as the preference to record (never, every time, once, …), where to store the cassettes and what library to use to pass the http calls and replay them.
For the options the simple way is to request *new_episodes*. That will record new requests and store them to be replayed when they are requested again. It’s what you would usually want.
For the cassette dir, again I like my directories organised so I put all the vcr stuff inside the test directory.
For the library I usually go for Faraday. It’s the http lib I use most of the time now : it’s simple, allows for some clean code and fast tricks while doing the job properly. It’s also pretty simple to configure.
Back to the test template : the before and after blocks setup and cleanup the VCR run. ```VCR.insert_cassette __name__``` will create a cassette named after the current test file and tell VCR to write to it.
```VCR.eject_cassette``` does what you might imagine : close the file to avoid further writes.
```
before do
VCR.insert_cassette __name__
end
after do
VCR.eject_cassette
end
```
The problem with VCR is that once it’s setup all your http calls will go through it and it’s a bit tedious to setup paths around it to avoid that.
> An alternative to using record and replay tools such as VCR is to use tools such as Artifice (https://github.com/wycats/artifice).
> Artifice allows you to mock remote service replies by plugging http calls to mini Rack apps.
> It’s a bit more difficult to setup and maintain than VCR but it’s way faster and if you have a proper documentation of the remote API or recordings of how it’s behaving it can be a nicer solution.
### Faker
Faker is another really handy tool : it allows you to generate realistic data for you model attributes. Names, email addresses, phone numbers, domain names, … It’s a handy companion for people writing tests everyday.
### Fake-redis
I often use redis for all sort of things in my applications and gems. Fake redis is a memory only, super fast implementation of Redis. It will save you time and make tests faster.
### Mocha
If Minitest is not enough Mocha can bring a bit more bang to it, it’s also easy to use and will ease your path to mocks.
## Packaging up the gem
Once it’s ready you can build the gem using ```gem build```. Then you can push to Rubygems, if it’s to be open source that it is.
Create an account on Rubygems.org if it’s not the case yet and check the documentation over there. Once it’s done you can ```gem push foo-0.0.1.gem``` to get your gem out there.
## Using your gems privately
There is commercial private gem servers as a service such as Gemfury (http://www.gemfury.com) but you can use private git repositories to store your private gems too.
## The point
I hope that this article has shown you how easy it has become to create a gem with tests. I am quite sad I did not know about these steps few years ago, it would have made it easier for me to keep my projects tighter and cleaner.
### Thanks
Big thanks to @joelazemar for his advices when I was searching around and learning about gem making.
Big thanks to Matt Sears for his great article about Minitest.
Big thanks to Claudio Ortolina for his brilliant piece (http://net.tutsplus.com/tutorials/ruby/gem-creation-with-bundler/) that served as inspiration for this article. If you need more details go check it out. The present article is intended to be a quick read to give you the minimal things you need to get going but Claudio’s has lot of details.
And a huge thank you to the Bundler team for the tool and commands it brings.
| mcansky/mcansky.github.io | _posts/2013-11-26-Creating-a-gem-with-minitest.md | Markdown | mit | 10,874 |
<?php
/* Cachekey: cache/stash_default/doctrine/doctrinenamespacecachekey[dc2_b1b70927f4ac11a36c774dc0f41356a4_]/ */
/* Type: array */
$loaded = true;
$expiration = 1425255999;
$data = array();
/* Child Type: integer */
$data['return'] = 1;
/* Child Type: integer */
$data['createdOn'] = 1424843731;
| imyuvii/concrete | application/files/cache/0fea6a13c52b4d47/25368f24b045ca84/38a865804f8fdcb6/57cd99682e939275/2ddb27c5cdf0b672/745d4c64665be841/6a8ae9bbe8c71756/ee7cd192ca4a73e0.php | PHP | mit | 307 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blocks & Guidelines</title>
<link rel="stylesheet" type="text/css" href="./css/ui.css">
<script src='https://code.jquery.com/jquery-2.1.3.min.js' type='application/javascript'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/ace/1.1.8/ace.js' type='application/javascript'></script>
<script src='./js/blocks.and.guidelines.js' type='application/javascript'></script>
<script src='./js/rapheal-min.js' type='application/javascript'></script>
<script src='./js/util.js' type='application/javascript'></script>
<script src='./js/ui.js' type='application/javascript'></script>
</head>
<body id='body'>
<!-- <div id='canvas'></div> -->
<div id='rendering-context'></div>
<div id='documents'>
<div class='addlevel'>+</div>
<h3>Diagrams</h3>
<span class='button' id='Import'><input type="file" id="input"></span><p></p>
<span class='button' id='Export'><a href='' target="_blank">Export</a></span>
<span class='button' id='Delete'>Delete</span>
<div id='scroller'>
<ul id="saves"></ul>
</div>
</div>
</body>
</html>
| OSU-Infovis/BlocksAndGuides | ui.html | HTML | mit | 1,378 |
<?php
class AsuransiForm extends CFormModel
{
public $stringNIM;
public $arrayNIM;
public function rules()
{
return array(
array('stringNIM', 'required'),
);
}
public function attributeLabels()
{
return array(
'stringNIM' => Yii::t('app','NIM'),
);
}
protected function beforeValidate()
{
preg_match_all('([0-9]+)',$this->stringNIM,$nims);
$this->arrayNIM = $nims[0];
return parent::beforeValidate();
}
public function preview()
{
$criteria = new CDbCriteria;
$criteria->addInCondition('nim',$this->arrayNIM);
return new CActiveDataProvider('Mahasiswa', array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>50
),
));
}
public function lunasi()
{
$criteria = new CDbCriteria;
$criteria->addInCondition('nim',$this->arrayNIM);
foreach(Mahasiswa::model()->findAll($criteria) as $mahasiswa) {
$mahasiswa->lunasiAsuransi();
}
}
}
| ata/kkn | protected/models/AsuransiForm.php | PHP | mit | 910 |
# The MIT License (MIT)
Copyright (c) 2017 Eric Scuccimarra <[email protected]>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.
| escuccim/LaraBlog | LICENSE.md | Markdown | mit | 1,136 |
function main()
while true do
print('Hello')
end
end
live.patch('main', main)
live.start(main)
| zentner-kyle/lua-live | example/hello1.lua | Lua | mit | 105 |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#nullable disable
namespace StyleCop.Analyzers.OrderingRules
{
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using StyleCop.Analyzers.Helpers;
using StyleCop.Analyzers.Settings.ObjectModel;
/// <summary>
/// A constant field is placed beneath a non-constant field.
/// </summary>
/// <remarks>
/// <para>A violation of this rule occurs when a constant field is placed beneath a non-constant field. Constants
/// should be placed above fields to indicate that the two are fundamentally different types of elements with
/// different considerations for the compiler, different naming requirements, etc.</para>
/// </remarks>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class SA1203ConstantsMustAppearBeforeFields : DiagnosticAnalyzer
{
/// <summary>
/// The ID for diagnostics produced by the <see cref="SA1203ConstantsMustAppearBeforeFields"/> analyzer.
/// </summary>
public const string DiagnosticId = "SA1203";
private const string HelpLink = "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1203.md";
private static readonly LocalizableString Title = new LocalizableResourceString(nameof(OrderingResources.SA1203Title), OrderingResources.ResourceManager, typeof(OrderingResources));
private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(OrderingResources.SA1203MessageFormat), OrderingResources.ResourceManager, typeof(OrderingResources));
private static readonly LocalizableString Description = new LocalizableResourceString(nameof(OrderingResources.SA1203Description), OrderingResources.ResourceManager, typeof(OrderingResources));
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, AnalyzerCategory.OrderingRules, DiagnosticSeverity.Warning, AnalyzerConstants.EnabledByDefault, Description, HelpLink);
private static readonly ImmutableArray<SyntaxKind> TypeDeclarationKinds =
ImmutableArray.Create(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration);
private static readonly Action<SyntaxNodeAnalysisContext, StyleCopSettings> TypeDeclarationAction = HandleTypeDeclaration;
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(TypeDeclarationAction, TypeDeclarationKinds);
}
private static void HandleTypeDeclaration(SyntaxNodeAnalysisContext context, StyleCopSettings settings)
{
var elementOrder = settings.OrderingRules.ElementOrder;
int constantIndex = elementOrder.IndexOf(OrderingTrait.Constant);
if (constantIndex < 0)
{
return;
}
var typeDeclaration = (TypeDeclarationSyntax)context.Node;
var members = typeDeclaration.Members;
var previousFieldConstant = true;
var previousFieldStatic = false;
var previousFieldReadonly = false;
var previousAccessLevel = AccessLevel.NotSpecified;
foreach (var member in members)
{
if (!(member is FieldDeclarationSyntax field))
{
continue;
}
AccessLevel currentAccessLevel = MemberOrderHelper.GetAccessLevelForOrdering(field, field.Modifiers);
bool currentFieldConstant = field.Modifiers.Any(SyntaxKind.ConstKeyword);
bool currentFieldReadonly = currentFieldConstant || field.Modifiers.Any(SyntaxKind.ReadOnlyKeyword);
bool currentFieldStatic = currentFieldConstant || field.Modifiers.Any(SyntaxKind.StaticKeyword);
bool compareConst = true;
for (int j = 0; compareConst && j < constantIndex; j++)
{
switch (elementOrder[j])
{
case OrderingTrait.Accessibility:
if (currentAccessLevel != previousAccessLevel)
{
compareConst = false;
}
continue;
case OrderingTrait.Readonly:
if (currentFieldReadonly != previousFieldReadonly)
{
compareConst = false;
}
continue;
case OrderingTrait.Static:
if (currentFieldStatic != previousFieldStatic)
{
compareConst = false;
}
continue;
case OrderingTrait.Kind:
// Only fields may be marked const, and all fields have the same kind.
continue;
case OrderingTrait.Constant:
default:
continue;
}
}
if (compareConst)
{
if (!previousFieldConstant && currentFieldConstant)
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, NamedTypeHelpers.GetNameOrIdentifierLocation(member)));
}
}
previousFieldConstant = currentFieldConstant;
previousFieldReadonly = currentFieldReadonly;
previousFieldStatic = currentFieldStatic;
previousAccessLevel = currentAccessLevel;
}
}
}
}
| DotNetAnalyzers/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers/OrderingRules/SA1203ConstantsMustAppearBeforeFields.cs | C# | mit | 6,370 |
//
// Created by Kévin POLOSSAT on 14/01/2018.
//
#ifndef LW_TCP_SERVER_SOCKET_H
#define LW_TCP_SERVER_SOCKET_H
#include <memory>
#include <type_traits>
#include "Socket.h"
#include "Reactor.h"
#include "Buffer.h"
#include "Operation.h"
#include "SSLSocket.h"
namespace lw_network {
template<typename Sock = Socket>
class ReactiveSocketBase : public Sock {
static_assert(std::is_base_of<Socket, Sock>::value, "Socket base should be a derived class of Socket");
public:
explicit ReactiveSocketBase(Reactor &reactor) : Sock(), reactor_(reactor) { register_(); }
ReactiveSocketBase(Reactor &reactor, Sock socket): Sock(socket), reactor_(reactor) { register_(); }
~ReactiveSocketBase() = default;
ReactiveSocketBase(ReactiveSocketBase const &other) = default;
ReactiveSocketBase(ReactiveSocketBase &&other) = default;
ReactiveSocketBase &operator=(ReactiveSocketBase const &other) {
Sock::operator=(other);
return *this;
}
ReactiveSocketBase &operator=(ReactiveSocketBase &&other) {
Sock::operator=(other);
return *this;
}
void close() {
reactor_.unregisterHandler(this->getImpl(), lw_network::Reactor::read);
reactor_.unregisterHandler(this->getImpl(), lw_network::Reactor::write);
error_code ec = no_error;
Sock::close(ec);
}
void async_read_some(Buffer b, std::function<void(std::size_t nbyte, error_code ec)> completionHandler);
void async_read(Buffer b, std::function<void(std::size_t nbyte, error_code ec)> completionHandler);
void async_write_some(Buffer b, std::function<void(std::size_t nbyte, error_code ec)> completionHandler);
void async_write(Buffer b, std::function<void(std::size_t nbyte, error_code ec)> completionHandler);
private:
Reactor &reactor_;
private:
void register_() {
reactor_.registerHandler(this->getImpl(), lw_network::Reactor::read);
reactor_.registerHandler(this->getImpl(), lw_network::Reactor::write);
}
};
using ReactiveSocket = ReactiveSocketBase<>;
using SSLReactiveSocket = ReactiveSocketBase<SSLSocket>;
// TODO FACTORIZE
template<typename T>
class ReadOperation : public Operation {
public:
ReadOperation(
ReactiveSocketBase<T> &s,
Buffer b,
std::function<void(std::size_t nbyte, error_code ec)> completionHandler):
s_(s), ec_(no_error), nbyte_(0), b_(std::move(b)), completionHandler_(std::move(completionHandler)) {}
bool handle() {
nbyte_ = s_.recv(b_, 0, ec_);
return b_.exhausted();
}
void complete() {
completionHandler_(nbyte_, ec_);
}
private:
ReactiveSocketBase<T> &s_;
error_code ec_;
std::size_t nbyte_;
Buffer b_;
std::function<void(std::size_t nbyte, error_code ec)> completionHandler_;
};
template<typename T>
class WriteOperation : public Operation {
public:
WriteOperation(
lw_network::ReactiveSocketBase<T> &s,
lw_network::Buffer b,
std::function<void(size_t, lw_network::error_code)> completionHandler):
s_(s), ec_(no_error), nbyte_(0), b_(std::move(b)), completionHandler_(std::move(completionHandler)) {}
bool handle() {
nbyte_ = s_.send(b_, 0, ec_);
return b_.exhausted();
}
void complete() {
completionHandler_(nbyte_, ec_);
}
private:
ReactiveSocketBase<T> &s_;
error_code ec_;
std::size_t nbyte_;
Buffer b_;
std::function<void(std::size_t nbyte, error_code ec)> completionHandler_;
};
template<typename T>
class ReadSomeOperation : public Operation {
public:
ReadSomeOperation(
lw_network::ReactiveSocketBase<T> &s,
lw_network::Buffer b,
std::function<void(size_t, lw_network::error_code)> completionHandler):
s_(s), ec_(no_error), nbyte_(0), b_(std::move(b)), completionHandler_(std::move(completionHandler)) {
}
bool handle() {
nbyte_ = s_.recv(b_, 0, ec_);
return true;
}
void complete() {
completionHandler_(nbyte_, ec_);
}
private:
ReactiveSocketBase<T> &s_;
error_code ec_;
std::size_t nbyte_;
Buffer b_;
std::function<void(std::size_t nbyte, error_code ec)> completionHandler_;
};
template<typename T>
class WriteSomeOperation : public Operation {
public:
WriteSomeOperation(
lw_network::ReactiveSocketBase<T> &s,
lw_network::Buffer b,
std::function<void(size_t, lw_network::error_code)> completionHandler):
s_(s), ec_(no_error), nbyte_(0), b_(std::move(b)), completionHandler_(std::move(completionHandler)) {}
bool handle() {
nbyte_ = s_.send(b_, 0, ec_);
return true;
}
void complete() {
completionHandler_(nbyte_, ec_);
}
private:
ReactiveSocketBase<T> &s_;
error_code ec_;
std::size_t nbyte_;
Buffer b_;
std::function<void(std::size_t nbyte, error_code ec)> completionHandler_;
};
}
#include "ReactiveSocketBase.icc"
#endif //LW_TCP_SERVER_SOCKET_H
| polosskevin/zia | src/modules/server/lw_network/ReactiveSocketBase.h | C | mit | 5,070 |
var testLogin = function(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
alert("username="+username+" , password="+password);
}
window.onload = function (){
}
| Xcoder1011/OC_StudyDemo | OC与JS互调/WebView-JS/WebView-JS/加载本地的js,html,css/js/test.js | JavaScript | mit | 248 |
from __future__ import absolute_import, division, print_function, unicode_literals
# Statsd client. Loosely based on the version by Steve Ivy <[email protected]>
import logging
import random
import socket
import time
from contextlib import contextmanager
log = logging.getLogger(__name__)
class StatsD(object):
def __init__(self, host='localhost', port=8125, enabled=True, prefix=''):
self.addr = None
self.enabled = enabled
if enabled:
self.set_address(host, port)
self.prefix = prefix
self.udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def set_address(self, host, port=8125):
try:
self.addr = (socket.gethostbyname(host), port)
except socket.gaierror:
self.addr = None
self.enabled = False
@contextmanager
def timed(self, stat, sample_rate=1):
log.debug('Entering timed context for %r' % (stat,))
start = time.time()
yield
duration = int((time.time() - start) * 1000)
log.debug('Exiting timed context for %r' % (stat,))
self.timing(stat, duration, sample_rate)
def timing(self, stats, time, sample_rate=1):
"""
Log timing information
"""
unit = 'ms'
log.debug('%r took %s %s' % (stats, time, unit))
self.update_stats(stats, "%s|%s" % (time, unit), sample_rate)
def increment(self, stats, sample_rate=1):
"""
Increments one or more stats counters
"""
self.update_stats(stats, 1, sample_rate)
def decrement(self, stats, sample_rate=1):
"""
Decrements one or more stats counters
"""
self.update_stats(stats, -1, sample_rate)
def update_stats(self, stats, delta=1, sampleRate=1):
"""
Updates one or more stats counters by arbitrary amounts
"""
if not self.enabled or self.addr is None:
return
if type(stats) is not list:
stats = [stats]
data = {}
for stat in stats:
data["%s%s" % (self.prefix, stat)] = "%s|c" % delta
self.send(data, sampleRate)
def send(self, data, sample_rate):
sampled_data = {}
if sample_rate < 1:
if random.random() <= sample_rate:
for stat, value in data.items():
sampled_data[stat] = "%s|@%s" % (value, sample_rate)
else:
sampled_data = data
try:
for stat, value in sampled_data.items():
self.udp_sock.sendto("%s:%s" % (stat, value), self.addr)
except Exception as e:
log.exception('Failed to send data to the server: %r', e)
if __name__ == '__main__':
sd = StatsD()
for i in range(1, 100):
sd.increment('test')
| smarkets/smk_python_sdk | smarkets/statsd.py | Python | mit | 2,824 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Profiler.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
// Provides operations for profiling the code.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Diagnostics
{
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Kephas.Logging;
using Kephas.Operations;
using Kephas.Threading.Tasks;
/// <summary>
/// Provides operations for profiling the code.
/// </summary>
public static class Profiler
{
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithWarningStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithWarningStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithInfoStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithInfoStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithDebugStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithDebugStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithTraceStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithTraceStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at the indicated log level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="logLevel">The log level.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithStopwatch(
this Action action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
action();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at the indicated
/// log level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">Optional. The logger.</param>
/// <param name="logLevel">Optional. The log level.</param>
/// <param name="memberName">Optional. Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult<T>();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
result.Value = action();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithWarningStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithWarningStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithInfoStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithInfoStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithDebugStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithDebugStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithTraceStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithTraceStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync<T>(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at the indicated log level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="logLevel">The log level.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static async Task<IOperationResult> WithStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
await action().PreserveThreadContext();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed
/// time at the indicated log level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">Optional. The logger.</param>
/// <param name="logLevel">Optional. The log level.</param>
/// <param name="memberName">Optional. Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static async Task<IOperationResult<T>> WithStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult<T>();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
result.Value = await action().PreserveThreadContext();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
}
} | quartz-software/kephas | src/Kephas.Core/Diagnostics/Profiler.cs | C# | mit | 19,835 |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Examples
{
class Program
{
[STAThread]
static void Main(string[] args)
{
SolidEdgeFramework.Application application = null;
SolidEdgePart.PartDocument partDocument = null;
SolidEdgePart.Models models = null;
SolidEdgePart.Model model = null;
SolidEdgePart.RevolvedCutouts revolvedCutouts = null;
SolidEdgePart.RevolvedCutout revolvedCutout = null;
try
{
// See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register();
// Attempt to connect to a running instance of Solid Edge.
application = (SolidEdgeFramework.Application)Marshal.GetActiveObject("SolidEdge.Application");
partDocument = application.ActiveDocument as SolidEdgePart.PartDocument;
if (partDocument != null)
{
models = partDocument.Models;
model = models.Item(1);
revolvedCutouts = model.RevolvedCutouts;
for (int i = 1; i <= revolvedCutouts.Count; i++)
{
revolvedCutout = revolvedCutouts.Item(i);
var topCap = (SolidEdgeGeometry.Face)revolvedCutout.TopCap;
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleMessageFilter.Unregister();
}
}
}
} | SolidEdgeCommunity/docs | docfx_project/snippets/SolidEdgePart.RevolvedCutout.TopCap.cs | C# | mit | 1,741 |
class MySessionsController < ApplicationController
prepend_before_filter :stop_tracking, :only => [:destroy]
def stop_tracking
current_user.update_attributes(:current_sign_in_ip => nil)
end
end
| jaylane/nycdispensary | app/controllers/my_sessions_controller.rb | Ruby | mit | 206 |
using System.ComponentModel;
namespace LinqAn.Google.Metrics
{
/// <summary>
/// The total number of completions for the requested goal number.
/// </summary>
[Description("The total number of completions for the requested goal number.")]
public class Goal19Completions: Metric<int>
{
/// <summary>
/// Instantiates a <seealso cref="Goal19Completions" />.
/// </summary>
public Goal19Completions(): base("Goal 19 Completions",true,"ga:goal19Completions")
{
}
}
}
| kenshinthebattosai/LinqAn.Google | src/LinqAn.Google/Metrics/Goal19Completions.cs | C# | mit | 490 |
using Silk.NET.Input;
using Silk.NET.Maths;
using Silk.NET.Windowing;
namespace WemkuhewhallYekaherehohurnije
{
class Program
{
private static IWindow _window;
private static void Main(string[] args)
{
//Create a window.
var options = WindowOptions.Default;
options = new WindowOptions
(
true,
new Vector2D<int>(50, 50),
new Vector2D<int>(1280, 720),
0.0,
0.0,
new GraphicsAPI
(
ContextAPI.OpenGL,
ContextProfile.Core,
ContextFlags.ForwardCompatible,
new APIVersion(3, 3)
),
"",
WindowState.Normal,
WindowBorder.Resizable,
false,
false,
VideoMode.Default
);
options.Size = new Vector2D<int>(800, 600);
options.Title = "LearnOpenGL with Silk.NET";
_window = Window.Create(options);
//Assign events.
_window.Load += OnLoad;
_window.Update += OnUpdate;
_window.Render += OnRender;
//Run the window.
_window.Run();
}
private static void OnLoad()
{
//Set-up input context.
IInputContext input = _window.CreateInput();
for (int i = 0; i < input.Keyboards.Count; i++)
{
input.Keyboards[i].KeyDown += KeyDown;
}
}
private static void OnRender(double obj)
{
//Here all rendering should be done.
}
private static void OnUpdate(double obj)
{
//Here all updates to the program should be done.
}
private static void KeyDown(IKeyboard arg1, Key arg2, int arg3)
{
//Check to close the window on escape.
if (arg2 == Key.Escape)
{
_window.Close();
}
}
}
} | lindexi/lindexi_gd | WemkuhewhallYekaherehohurnije/WemkuhewhallYekaherehohurnije/Program.cs | C# | mit | 2,129 |
FILE(REMOVE_RECURSE
"CMakeFiles/polynomialutils_4.dir/polynomialutils.cpp.o"
"polynomialutils_4.pdb"
"polynomialutils_4"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
INCLUDE(CMakeFiles/polynomialutils_4.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
| cmeon/Simplex | lib/unsupported/test/CMakeFiles/polynomialutils_4.dir/cmake_clean.cmake | CMake | mit | 297 |
---
title: Overdose Fatality Review Teams Literature Review
_template: publication
area:
- Criminal Justice System
pubtype:
- Research Report
pubstatatus: 'true'
summary: States and localities across the United States have implemented overdose fatality review teams to address the impact of the opioid crisis on their communities. Overdose fatality review teams are designed to increase cross-system collaboration among various public safety, public health, and social service agencies; identify missed opportunities and system gaps; and develop recommendations for intervention efforts in hopes of preventing future overdose deaths. However, limitations in peer-reviewed research on the effectiveness of overdose fatality review teams limit the understanding of their usefulness. This article provides a review of literature on overdose fatality review teams, including goals, recommendations, and information sharing protocols, as well as considerations from other fatality review teams.
articleLink: /articles/overdose-fatality-review-teams-literature-review
puburl: /assets/articles/Overdose Fatality Review Team Literature Review Final-210219T19112457.pdf
---
States and localities across the United States have implemented overdose fatality review teams to address the impact of the opioid crisis on their communities. Overdose fatality review teams are designed to increase cross-system collaboration among various public safety, public health, and social service agencies; identify missed opportunities and system gaps; and develop recommendations for intervention efforts in hopes of preventing future overdose deaths. However, limitations in peer-reviewed research on the effectiveness of overdose fatality review teams limit the understanding of their usefulness. This article provides a review of literature on overdose fatality review teams, including goals, recommendations, and information sharing protocols, as well as considerations from other fatality review teams. | ICJIA/icjia-public-website | _content/55-publications/2021-03-15-overdose-fatality-review-teams-literature-review.html | HTML | mit | 1,987 |
<?php
namespace Libreame\BackendBundle\Helpers;
use Libreame\BackendBundle\Controller\AccesoController;
use Libreame\BackendBundle\Repository\ManejoDataRepository;
use Libreame\BackendBundle\Entity\LbIdiomas;
use Libreame\BackendBundle\Entity\LbUsuarios;
use Libreame\BackendBundle\Entity\LbEjemplares;
use Libreame\BackendBundle\Entity\LbSesiones;
use Libreame\BackendBundle\Entity\LbEditoriales;
use Libreame\BackendBundle\Entity\LbAutores;
/**
* Description of Feeds
*
* @author mramirez
*/
class GestionEjemplares {
/*
* feeds
* Retorna la lista de todos los ejemplares nuevos cargados en la plataforma.
* Solo a partir del ID que envía el cliente (Android), en adelante.
* Por ahora solo tendrá Ejemplares, luego se evaluará si tambien se cargan TRATOS Cerrados / Ofertas realizadas
*/
public function buscarEjemplares(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
$usuario = new LbUsuarios();
$sesion = new LbSesiones();
$ejemplares = new LbEjemplares();
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//echo "<script>alert(' buscaEjemplares :: FindAll ')</script>";
//Busca el usuario
$usuario = ManejoDataRepository::getUsuarioByEmail($psolicitud->getEmail());
//$membresia= ManejoDataRepository::getMembresiasUsuario($usuario);
//echo "<script>alert('MEM ".count($membresia)." regs ')</script>";
$grupo= ManejoDataRepository::getObjetoGruposUsuario($usuario);
$arrGru = array();
foreach ($grupo as $gru){
$arrGru[] = $gru->getIngrupo();
}
$ejemplares = ManejoDataRepository::getBuscarEjemplares($usuario, $arrGru, $psolicitud->getTextoBuscar());
//echo "Recuperó ejemplares...gestionejemplares:buscarEjemplares \n";
$respuesta->setRespuesta(AccesoController::inExitoso);
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
} else {
$respuesta->setRespuesta($respSesionVali);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
}
public function recuperarFeedEjemplares(Solicitud $psolicitud)
{
/*
http://ex4read.co/services/web/img/p/1/1/11.jpg
*/
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
$usuario = new LbUsuarios();
$sesion = new LbSesiones();
//$ejemplares = new LbEjemplares();
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' recuperarFeedEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//echo "<script>alert(' recuperarFeedEjemplares :: FindAll ')</script>";
//Busca el usuario
$usuario = ManejoDataRepository::getUsuarioByEmail($psolicitud->getEmail());
//$membresia= ManejoDataRepository::getMembresiasUsuario($usuario);
//echo "<script>alert('MEM ".count($membresia)." regs ')</script>";
$grupo= ManejoDataRepository::getObjetoGruposUsuario($usuario);
$arrGru = array();
foreach ($grupo as $gru){
$arrGru[] = $gru->getIngrupo();
}
$ejemplares = ManejoDataRepository::getEjemplaresDisponibles($arrGru, $psolicitud->getUltEjemplar());
//echo "Imagen ".$ejemplares;
$respuesta->setRespuesta(AccesoController::inExitoso);
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
} else {
$respuesta->setRespuesta($respSesionVali);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
}
public function publicarEjemplar(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' Publicar :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//Genera la oferta para el ejemplar si la accion es 1}
//echo "Decide accion para ejemplar : ".$psolicitud->getAccionComm();
if ($psolicitud->getAccionComm() == AccesoController::inAccPublica) {
//echo "\n La acion es publicar";
$respPub = ManejoDataRepository::generarPublicacionEjemplar($psolicitud);
$respuesta->setRespuesta($respPub);
} elseif ($psolicitud->getAccionComm() == AccesoController::inAccDespubl) {
} elseif ($psolicitud->getAccionComm() == AccesoController::inAccModific) {
} elseif ($psolicitud->getAccionComm() == AccesoController::inAccElimina) {}
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
} else {
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
}
public function visualizarBiblioteca(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
$usuario = new LbUsuarios();
$sesion = new LbSesiones();
$ejemplares = new LbEjemplares();
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//echo "<script>alert(' buscaEjemplares :: FindAll ')</script>";
//Busca el usuario
$usuario = ManejoDataRepository::getUsuarioByEmail($psolicitud->getEmail());
//$membresia= ManejoDataRepository::getMembresiasUsuario($usuario);
//echo "<script>alert('MEM ".count($membresia)." regs ')</script>";
$grupo= ManejoDataRepository::getObjetoGruposUsuario($usuario);
$arrGru = array();
foreach ($grupo as $gru){
$arrGru[] = $gru->getIngrupo();
}
$ejemplares = ManejoDataRepository::getVisualizarBiblioteca($usuario, $arrGru, $psolicitud->getFiltro());
//echo "Recuperó ejemplares...gestionejemplares:buscarEjemplares \n";
$respuesta->setRespuesta(AccesoController::inExitoso);
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
} else {
$respuesta->setRespuesta($respSesionVali);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$ejemplares = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ejemplares);
}
}
public function recuperarOferta(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
$usuario = new LbUsuarios();
$sesion = new LbSesiones();
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//echo "<script>alert(' recuperarFeedEjemplares :: FindAll ')</script>";
//Busca el usuario
$usuario = ManejoDataRepository::getUsuarioByEmail($psolicitud->getEmail());
//$membresia= ManejoDataRepository::getMembresiasUsuario($usuario);
//echo "<script>alert('MEM ".count($membresia)." regs ')</script>";
$oferta = ManejoDataRepository::getOfertaById($psolicitud->getIdOferta());
//echo "<script>alert('Oferta ".$psolicitud->getIdOferta()." ')</script>";
if ($oferta != NULL){
if ($oferta->getInofeactiva() == AccesoController::inExitoso){
$respuesta->setRespuesta(AccesoController::inExitoso);
} else {
$respuesta->setRespuesta(AccesoController::inMenNoAc);
}
} else {
$respuesta->setRespuesta(AccesoController::inMenNoEx);
}
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
return $objLogica::generaRespuesta($respuesta, $psolicitud, $oferta);
} else {
$respuesta->setRespuesta($respSesionVali);
$oferta = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $oferta);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$oferta = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $oferta);
}
}
public function listarIdiomas(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$respuesta->setRespuesta(AccesoController::inExitoso);
//echo "Respuesta Idiomas: ".$respuesta->getRespuesta()." \n";
$idiomas = ManejoDataRepository::getListaIdiomas();
$idioma = new LbIdiomas();
$arIdiomas = array();
//$contador = 0;
foreach ($idiomas as $idioma) {
$arIdiomas[] = array("ididioma"=>$idioma->getInididioma(), "nomidioma"=>utf8_encode($idioma->getTxidinombre()));
//echo "Idioma=".$idioma->getInididioma()." - ".$idioma->getTxidinombre()." \n";
//$contador++;
}
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arIdiomas);
} else {
$respuesta->setRespuesta($respSesionVali);
$arIdiomas = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arIdiomas);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$arIdiomas = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arIdiomas);
}
}
public function megustaEjemplar(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$resp = ManejoDataRepository::setMegustaEjemplar($psolicitud->getIdEjemplar(), $psolicitud->getMegusta(), $psolicitud->getEmail());
$respuesta->setRespuesta($resp);
$respuesta->setCantComenta(ManejoDataRepository::getCantComment($psolicitud->getIdEjemplar()));
$respuesta->setCantMegusta(ManejoDataRepository::getCantMegusta($psolicitud->getIdEjemplar()));
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
} else {
//echo 'sesion invalida';
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
}
public function VerUsrgustaEjemplar(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$UsrMegusta = ManejoDataRepository::getUsrMegustaEjemplar($psolicitud);
$respuesta->setRespuesta(AccesoController::inExitoso);
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, $UsrMegusta);
} else {
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $UsrMegusta);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $UsrMegusta);
}
}
public function comentarEjemplar(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$resp = ManejoDataRepository::setComentarioEjemplar($psolicitud);
$respuesta->setRespuesta($resp);
$respuesta->setCantComenta(ManejoDataRepository::getCantComment($psolicitud->getIdEjemplar()));
$respuesta->setCantMegusta(ManejoDataRepository::getCantMegusta($psolicitud->getIdEjemplar()));
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
} else {
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, NULL);
}
}
public function VerComentariosEjemplar(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$ComenEjemplar = ManejoDataRepository::getComentariosEjemplar($psolicitud);
$respuesta->setRespuesta(AccesoController::inExitoso);
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ComenEjemplar);
} else {
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ComenEjemplar);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $ComenEjemplar);
}
}
public function enviarMensajeChat(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
//Guarda la acion del usuario en una variable
$ultAccion = $psolicitud->getTratoAcep();
//Guarda el chat
$resp = ManejoDataRepository::setMensajeChat($psolicitud);
//echo "respuesta ".$resp;
if (is_null($resp)) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
} else {
$usrDueno = AccesoController::inDatoCer; //Default: no es el dueño
$respuesta->setRespuesta(AccesoController::inDatoUno);
$arrConversacion = array();
$objConv = new LbNegociacion();
$objConv = ManejoDataRepository::getChatNegociacionById($resp);
//echo "respuesta ".$resp;
//
if (!empty($objConv)) {
$usuarioEnv = ManejoDataRepository::getUsuarioByEmail($psolicitud->getEmail());
$usuarioDes = ManejoDataRepository::getUsuarioById($psolicitud->getIdusuariodes());
foreach ($objConv as $neg){
$idconversa = $neg->getTxnegidconversacion();
if($neg->getInnegusuescribe() == $neg->getInnegusuduenho()){
$usrrecibe = $neg->getInnegususolicita();
$usrDueno = AccesoController::inDatoUno;
} else {
$usrrecibe = $neg->getInnegusuduenho();
$usrDueno = AccesoController::inDatoCer;
}
$arrConversacion[] = array('fecha' => $neg->getFenegfechamens()->format(("Y-m-d H:i:s")),
'usrescribe' => $neg->getInnegusuescribe()->getInusuario(),
'nommostusrescribe' => utf8_encode($neg->getInnegusuescribe()->getTxusunommostrar()),
'idusrdestino' => $usrrecibe->getInusuario(),
'nommostusrdest' => utf8_encode($usrrecibe->getTxusunommostrar()),
'txmensaje' => utf8_encode($neg->getTxnegmensaje()),
'idconversa' => utf8_encode($neg->getTxnegidconversacion()),
'tratoacep' => $neg->getInnegtratoacep());
}
$respuesta->setIndAcept(ManejoDataRepository::getUsAceptTrato($usuarioEnv, $idconversa));
$respuesta->setIndOtroAcept(ManejoDataRepository::getUsAceptTrato($usuarioDes, $idconversa));
$respuesta->setBotonesMostrar(ManejoDataRepository::getBotonesMostrar($idconversa,$usrDueno,$ultAccion));
}
}
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arrConversacion);
} else {
$respuesta->setRespuesta($respSesionVali);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arrConversacion);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arrConversacion);
}
}
public function listarEditoriales(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$respuesta->setRespuesta(AccesoController::inExitoso);
//echo "Respuesta Idiomas: ".$respuesta->getRespuesta()." \n";
$editoriales = ManejoDataRepository::getListaEditoriales();
$editorial = new LbEditoriales();
$arEditoriales = array();
//$contador = 0;
foreach ($editoriales as $editorial) {
$arEditoriales[] = array("ideditor"=>$editorial->getInideditorial(), "nomeditor"=>utf8_encode($editorial->getTxedinombre()));
//echo "Idioma=".$idioma->getInididioma()." - ".$idioma->getTxidinombre()." \n";
//$contador++;
}
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arEditoriales);
} else {
$respuesta->setRespuesta($respSesionVali);
$arEditoriales = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arEditoriales);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$arEditoriales = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arEditoriales);
}
}
public function listarAutores(Solicitud $psolicitud)
{
/*setlocale (LC_TIME, "es_CO");
$fecha = new \DateTime;*/
$respuesta = new Respuesta();
$objLogica = $this->get('logica_service');
try {
//Valida que la sesión corresponda y se encuentre activa
$respSesionVali= ManejoDataRepository::validaSesionUsuario($psolicitud);
//echo "<script>alert(' buscarEjemplares :: Validez de sesion ".$respSesionVali." ')</script>";
if ($respSesionVali==AccesoController::inULogged)
{
//SE INACTIVA PORQUE PUEDE GENERAR UNA GRAN CANTIDAD DE REGISTROS EN UNA SOLA SESION
//Busca y recupera el objeto de la sesion::
//$sesion = ManejoDataRepository::recuperaSesionUsuario($usuario,$psolicitud);
//echo "<script>alert('La sesion es ".$sesion->getTxsesnumero()." ')</script>";
//Guarda la actividad de la sesion::
//ManejoDataRepository::generaActSesion($sesion,AccesoController::inDatoUno,"Recupera Feed de Ejemplares".$psolicitud->getEmail()." recuperados con éxito ",$psolicitud->getAccion(),$fecha,$fecha);
//echo "<script>alert('Generó actividad de sesion ')</script>";
$respuesta->setRespuesta(AccesoController::inExitoso);
//echo "Respuesta Idiomas: ".$respuesta->getRespuesta()." \n";
$autores = ManejoDataRepository::getListaAutores();
$autor = new LbAutores();
$arAutores = array();
//$contador = 0;
foreach ($autores as $autor) {
$arAutores[] = array("idautor"=>$autor->getInidautor(), "nomautor"=>utf8_encode($autor->getTxautnombre()));
//echo "Idioma=".$idioma->getInididioma()." - ".$idioma->getTxidinombre()." \n";
//$contador++;
}
//echo "esto es lo que hay en respuesta";
//print_r($respuesta);
//echo $contador." - lugares hallados";
//$arIdiomas = array("Español","Inglés","Frances","Alemán","Ruso","Portugues",
// "Catalán","Árabe","Bosnio","Croata","Serbio","Italiano","Griego","Turco","Húngaro","Hindi");
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arAutores);
} else {
$respuesta->setRespuesta($respSesionVali);
$arAutores = array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arAutores);
}
} catch (Exception $ex) {
$respuesta->setRespuesta(AccesoController::inPlatCai);
$arAutores= array();
return $objLogica::generaRespuesta($respuesta, $psolicitud, $arAutores);
}
}
}
| BaisicaSAS/LibreameBE | src/Libreame/BackendBundle/Helpers/GestionEjemplares.php | PHP | mit | 38,081 |
/**
* marked - a markdown parser
* Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*/
;(function() {
/**
* Block-Level Grammar
*/
var block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')
(/bull/g, block.bullet)
();
block.list = replace(block.list)
(/bull/g, block.bullet)
('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
('def', '\\n+(?=' + block.def.source + ')')
();
block.blockquote = replace(block.blockquote)
('def', block.def)
();
block._tag = '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
block.html = replace(block.html)
('comment', /<!--[\s\S]*?-->/)
('closed', /<(tag)[\s\S]+?<\/\1>/)
('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
(/tag/g, block._tag)
();
block.paragraph = replace(block.paragraph)
('hr', block.hr)
('heading', block.heading)
('lheading', block.lheading)
('blockquote', block.blockquote)
('tag', '<' + block._tag)
('def', block.def)
();
/**
* Normal Block Grammar
*/
block.normal = merge({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge({}, block.normal, {
fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
paragraph: /^/,
heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
});
block.gfm.paragraph = replace(block.paragraph)
('(?!', '(?!'
+ block.gfm.fences.source.replace('\\1', '\\2') + '|'
+ block.list.source.replace('\\1', '\\3') + '|')
();
/**
* GFM + Tables Block Grammar
*/
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});
/**
* Block Lexer
*/
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables;
} else {
this.rules = block.gfm;
}
}
}
/**
* Expose Block Rules
*/
Lexer.rules = block;
/**
* Static Lex Method
*/
Lexer.lex = function(src, options) {
var lexer = new Lexer(options);
return lexer.lex(src);
};
/**
* Preprocessing
*/
Lexer.prototype.lex = function(src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
.replace(/\u00a0/g, ' ')
.replace(/\u2424/g, '\n');
return this.token(src, true);
};
/**
* Lexing
*/
Lexer.prototype.token = function(src, top, bq) {
var src = src.replace(/^ +$/gm, '')
, next
, loose
, cap
, bull
, b
, item
, space
, i
, l;
while (src) {
// newline
if (cap = this.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this.tokens.push({
type: 'space'
});
}
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, '');
this.tokens.push({
type: 'code',
text: !this.options.pedantic
? cap.replace(/\n+$/, '')
: cap
});
continue;
}
// fences (gfm)
if (cap = this.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'code',
lang: cap[2],
text: cap[3] || ''
});
continue;
}
// heading
if (cap = this.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[1].length,
text: cap[2]
});
continue;
}
// table no leading pipe (gfm)
if (top && (cap = this.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// lheading
if (cap = this.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[2] === '=' ? 1 : 2,
text: cap[1]
});
continue;
}
// hr
if (cap = this.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'hr'
});
continue;
}
// blockquote
if (cap = this.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'blockquote_start'
});
cap = cap[0].replace(/^ *> ?/gm, '');
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this.token(cap, top, true);
this.tokens.push({
type: 'blockquote_end'
});
continue;
}
// list
if (cap = this.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this.tokens.push({
type: 'list_start',
ordered: bull.length > 1
});
// Get each top-level item.
cap = cap[0].match(this.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
// Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, '');
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) {
space -= item.length;
item = !this.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '');
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (this.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join('\n') + src;
i = l - 1;
}
}
// Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item.charAt(item.length - 1) === '\n';
if (!loose) loose = next;
}
this.tokens.push({
type: loose
? 'loose_item_start'
: 'list_item_start'
});
// Recurse.
this.token(item, false, bq);
this.tokens.push({
type: 'list_item_end'
});
}
this.tokens.push({
type: 'list_end'
});
continue;
}
// html
if (cap = this.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: this.options.sanitize
? 'paragraph'
: 'html',
pre: !this.options.sanitizer
&& (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
text: cap[0]
});
continue;
}
// def
if ((!bq && top) && (cap = this.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.links[cap[1].toLowerCase()] = {
href: cap[2],
title: cap[3]
};
continue;
}
// table (gfm)
if (top && (cap = this.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i]
.replace(/^ *\| *| *\| *$/g, '')
.split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// top-level paragraph
if (top && (cap = this.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'paragraph',
text: cap[1].charAt(cap[1].length - 1) === '\n'
? cap[1].slice(0, -1)
: cap[1]
});
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this.tokens.push({
type: 'text',
text: cap[0]
});
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return this.tokens;
};
/**
* Inline-Level Grammar
*/
var inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)([\s\S]*?[^`])\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
};
inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)
('inside', inline._inside)
('href', inline._href)
();
inline.reflink = replace(inline.reflink)
('inside', inline._inside)
();
/**
* Normal Inline Grammar
*/
inline.normal = merge({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)
(']|', '~]|')
('|', '|https?://|')
()
});
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(inline.gfm.text)('{2,}', '*')()
});
/**
* Inline Lexer & Compiler
*/
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
this.renderer = this.options.renderer || new Renderer;
this.renderer.options = this.options;
if (!this.links) {
throw new
Error('Tokens array requires a `links` property.');
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks;
} else {
this.rules = inline.gfm;
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic;
}
}
/**
* Expose Inline Rules
*/
InlineLexer.rules = inline;
/**
* Static Lexing/Compiling Method
*/
InlineLexer.output = function(src, links, options) {
var inline = new InlineLexer(links, options);
return inline.output(src);
};
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function(src) {
var out = ''
, link
, text
, href
, cap;
while (src) {
// escape
if (cap = this.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out += cap[1];
continue;
}
// autolink
if (cap = this.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === '@') {
text = cap[1].charAt(6) === ':'
? this.mangle(cap[1].substring(7))
: this.mangle(cap[1]);
href = this.mangle('mailto:') + text;
} else {
text = escape(cap[1]);
href = text;
}
out += this.renderer.link(href, null, text);
continue;
}
// url (gfm)
if (!this.inLink && (cap = this.rules.url.exec(src))) {
src = src.substring(cap[0].length);
text = escape(cap[1]);
href = text;
out += this.renderer.link(href, null, text);
continue;
}
// tag
if (cap = this.rules.tag.exec(src)) {
if (!this.inLink && /^<a /i.test(cap[0])) {
this.inLink = true;
} else if (this.inLink && /^<\/a>/i.test(cap[0])) {
this.inLink = false;
}
src = src.substring(cap[0].length);
out += this.options.sanitize
? this.options.sanitizer
? this.options.sanitizer(cap[0])
: escape(cap[0])
: cap[0]
continue;
}
// link
if (cap = this.rules.link.exec(src)) {
src = src.substring(cap[0].length);
this.inLink = true;
out += this.outputLink(cap, {
href: cap[2],
title: cap[3]
});
this.inLink = false;
continue;
}
// reflink, nolink
if ((cap = this.rules.reflink.exec(src))
|| (cap = this.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = this.links[link.toLowerCase()];
if (!link || !link.href) {
out += cap[0].charAt(0);
src = cap[0].substring(1) + src;
continue;
}
this.inLink = true;
out += this.outputLink(cap, link);
this.inLink = false;
continue;
}
// strong
if (cap = this.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.strong(this.output(cap[2] || cap[1]));
continue;
}
// em
if (cap = this.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.em(this.output(cap[2] || cap[1]));
continue;
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.codespan(escape(cap[2].trim(), true));
continue;
}
// br
if (cap = this.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.br();
continue;
}
// del (gfm)
if (cap = this.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.del(this.output(cap[1]));
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.text(escape(this.smartypants(cap[0])));
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return out;
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function(cap, link) {
var href = escape(link.href)
, title = link.title ? escape(link.title) : null;
return cap[0].charAt(0) !== '!'
? this.renderer.link(href, title, this.output(cap[1]))
: this.renderer.image(href, title, escape(cap[1]));
};
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function(text) {
if (!this.options.smartypants) return text;
return text
// em-dashes
.replace(/---/g, '\u2014')
// en-dashes
.replace(/--/g, '\u2013')
// opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
// closing singles & apostrophes
.replace(/'/g, '\u2019')
// opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
// closing doubles
.replace(/"/g, '\u201d')
// ellipses
.replace(/\.{3}/g, '\u2026');
};
/**
* Mangle Links
*/
InlineLexer.prototype.mangle = function(text) {
if (!this.options.mangle) return text;
var out = ''
, l = text.length
, i = 0
, ch;
for (; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > 0.5) {
ch = 'x' + ch.toString(16);
}
out += '&#' + ch + ';';
}
return out;
};
/**
* Renderer
*/
function Renderer(options) {
this.options = options || {};
}
Renderer.prototype.code = function(code, lang, escaped) {
if (this.options.highlight) {
var out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}
if (!lang) {
return '<pre><code>'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>';
}
return '<pre><code class="'
+ this.options.langPrefix
+ escape(lang, true)
+ '">'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>\n';
};
Renderer.prototype.blockquote = function(quote) {
return '<blockquote>\n' + quote + '</blockquote>\n';
};
Renderer.prototype.html = function(html) {
return html;
};
Renderer.prototype.heading = function(text, level, raw) {
return '<h'
+ level
+ ' id="'
+ this.options.headerPrefix
+ raw.toLowerCase().replace(/[^\w]+/g, '-')
+ '">'
+ text
+ '</h'
+ level
+ '>\n';
};
Renderer.prototype.hr = function() {
return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};
Renderer.prototype.list = function(body, ordered) {
var type = ordered ? 'ol' : 'ul';
return '<' + type + '>\n' + body + '</' + type + '>\n';
};
Renderer.prototype.listitem = function(text) {
return '<li>' + text + '</li>\n';
};
Renderer.prototype.paragraph = function(text) {
return '<p>' + text + '</p>\n';
};
Renderer.prototype.table = function(header, body) {
return '<table>\n'
+ '<thead>\n'
+ header
+ '</thead>\n'
+ '<tbody>\n'
+ body
+ '</tbody>\n'
+ '</table>\n';
};
Renderer.prototype.tablerow = function(content) {
return '<tr>\n' + content + '</tr>\n';
};
Renderer.prototype.tablecell = function(content, flags) {
var type = flags.header ? 'th' : 'td';
var tag = flags.align
? '<' + type + ' style="text-align:' + flags.align + '">'
: '<' + type + '>';
return tag + content + '</' + type + '>\n';
};
// span level renderer
Renderer.prototype.strong = function(text) {
return '<strong>' + text + '</strong>';
};
Renderer.prototype.em = function(text) {
return '<em>' + text + '</em>';
};
Renderer.prototype.codespan = function(text) {
return '<code>' + text + '</code>';
};
Renderer.prototype.br = function() {
return this.options.xhtml ? '<br/>' : '<br>';
};
Renderer.prototype.del = function(text) {
return '<del>' + text + '</del>';
};
Renderer.prototype.link = function(href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase();
} catch (e) {
return '';
}
if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
return '';
}
}
if (this.options.baseUrl && !originIndependentUrl.test(href)) {
href = resolveUrl(this.options.baseUrl, href);
}
var out = '<a href="' + href + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + text + '</a>';
return out;
};
Renderer.prototype.image = function(href, title, text) {
if (this.options.baseUrl && !originIndependentUrl.test(href)) {
href = resolveUrl(this.options.baseUrl, href);
}
var out = '<img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"';
}
out += this.options.xhtml ? '/>' : '>';
return out;
};
Renderer.prototype.text = function(text) {
return text;
};
/**
* Parsing & Compiling
*/
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
this.options.renderer = this.options.renderer || new Renderer;
this.renderer = this.options.renderer;
this.renderer.options = this.options;
}
/**
* Static Parse Method
*/
Parser.parse = function(src, options, renderer) {
var parser = new Parser(options, renderer);
return parser.parse(src);
};
/**
* Parse Loop
*/
Parser.prototype.parse = function(src) {
this.inline = new InlineLexer(src.links, this.options, this.renderer);
this.tokens = src.reverse();
var out = '';
while (this.next()) {
out += this.tok();
}
return out;
};
/**
* Next Token
*/
Parser.prototype.next = function() {
return this.token = this.tokens.pop();
};
/**
* Preview Next Token
*/
Parser.prototype.peek = function() {
return this.tokens[this.tokens.length - 1] || 0;
};
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function() {
var body = this.token.text;
while (this.peek().type === 'text') {
body += '\n' + this.next().text;
}
return this.inline.output(body);
};
/**
* Parse Current Token
*/
Parser.prototype.tok = function() {
switch (this.token.type) {
case 'space': {
return '';
}
case 'hr': {
return this.renderer.hr();
}
case 'heading': {
return this.renderer.heading(
this.inline.output(this.token.text),
this.token.depth,
this.token.text);
}
case 'code': {
return this.renderer.code(this.token.text,
this.token.lang,
this.token.escaped);
}
case 'table': {
var header = ''
, body = ''
, i
, row
, cell
, flags
, j;
// header
cell = '';
for (i = 0; i < this.token.header.length; i++) {
flags = { header: true, align: this.token.align[i] };
cell += this.renderer.tablecell(
this.inline.output(this.token.header[i]),
{ header: true, align: this.token.align[i] }
);
}
header += this.renderer.tablerow(cell);
for (i = 0; i < this.token.cells.length; i++) {
row = this.token.cells[i];
cell = '';
for (j = 0; j < row.length; j++) {
cell += this.renderer.tablecell(
this.inline.output(row[j]),
{ header: false, align: this.token.align[j] }
);
}
body += this.renderer.tablerow(cell);
}
return this.renderer.table(header, body);
}
case 'blockquote_start': {
var body = '';
while (this.next().type !== 'blockquote_end') {
body += this.tok();
}
return this.renderer.blockquote(body);
}
case 'list_start': {
var body = ''
, ordered = this.token.ordered;
while (this.next().type !== 'list_end') {
body += this.tok();
}
return this.renderer.list(body, ordered);
}
case 'list_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.token.type === 'text'
? this.parseText()
: this.tok();
}
return this.renderer.listitem(body);
}
case 'loose_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.tok();
}
return this.renderer.listitem(body);
}
case 'html': {
var html = !this.token.pre && !this.options.pedantic
? this.inline.output(this.token.text)
: this.token.text;
return this.renderer.html(html);
}
case 'paragraph': {
return this.renderer.paragraph(this.inline.output(this.token.text));
}
case 'text': {
return this.renderer.paragraph(this.parseText());
}
}
};
/**
* Helpers
*/
function escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function unescape(html) {
// explicitly match decimal, hex, and named HTML entities
return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
n = n.toLowerCase();
if (n === 'colon') return ':';
if (n.charAt(0) === '#') {
return n.charAt(1) === 'x'
? String.fromCharCode(parseInt(n.substring(2), 16))
: String.fromCharCode(+n.substring(1));
}
return '';
});
}
function replace(regex, opt) {
regex = regex.source;
opt = opt || '';
return function self(name, val) {
if (!name) return new RegExp(regex, opt);
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, '$1');
regex = regex.replace(name, val);
return self;
};
}
function resolveUrl(base, href) {
if (!baseUrls[' ' + base]) {
// we can ignore everything in base after the last slash of its path component,
// but we might need to add _that_
// https://tools.ietf.org/html/rfc3986#section-3
if (/^[^:]+:\/*[^/]*$/.test(base)) {
baseUrls[' ' + base] = base + '/';
} else {
baseUrls[' ' + base] = base.replace(/[^/]*$/, '');
}
}
base = baseUrls[' ' + base];
if (href.slice(0, 2) === '//') {
return base.replace(/:[^]*/, ':') + href;
} else if (href.charAt(0) === '/') {
return base.replace(/(:\/*[^/]*)[^]*/, '$1') + href;
} else {
return base + href;
}
}
baseUrls = {};
originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
function noop() {}
noop.exec = noop;
function merge(obj) {
var i = 1
, target
, key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
/**
* Marked
*/
function marked(src, opt, callback) {
if (callback || typeof opt === 'function') {
if (!callback) {
callback = opt;
opt = null;
}
opt = merge({}, marked.defaults, opt || {});
var highlight = opt.highlight
, tokens
, pending
, i = 0;
try {
tokens = Lexer.lex(src, opt)
} catch (e) {
return callback(e);
}
pending = tokens.length;
var done = function(err) {
if (err) {
opt.highlight = highlight;
return callback(err);
}
var out;
try {
out = Parser.parse(tokens, opt);
} catch (e) {
err = e;
}
opt.highlight = highlight;
return err
? callback(err)
: callback(null, out);
};
if (!highlight || highlight.length < 3) {
return done();
}
delete opt.highlight;
if (!pending) return done();
for (; i < tokens.length; i++) {
(function(token) {
if (token.type !== 'code') {
return --pending || done();
}
return highlight(token.text, token.lang, function(err, code) {
if (err) return done(err);
if (code == null || code === token.text) {
return --pending || done();
}
token.text = code;
token.escaped = true;
--pending || done();
});
})(tokens[i]);
}
return;
}
try {
if (opt) opt = merge({}, marked.defaults, opt);
return Parser.parse(Lexer.lex(src, opt), opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/chjj/marked.';
if ((opt || marked.defaults).silent) {
return '<p>An error occured:</p><pre>'
+ escape(e.message + '', true)
+ '</pre>';
}
throw e;
}
}
/**
* Options
*/
marked.options =
marked.setOptions = function(opt) {
merge(marked.defaults, opt);
return marked;
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
sanitizer: null,
mangle: true,
smartLists: false,
silent: false,
highlight: null,
langPrefix: 'lang-',
smartypants: false,
headerPrefix: '',
renderer: new Renderer,
xhtml: false,
baseUrl: null
};
/**
* Expose
*/
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Renderer = Renderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
if (typeof module !== 'undefined' && typeof exports === 'object') {
module.exports = marked;
} else if (typeof define === 'function' && define.amd) {
define(function() { return marked; });
} else {
this.marked = marked;
}
}).call(function() {
return this || (typeof window !== 'undefined' ? window : global);
}());
| jhelbig/postman-linux-app | app/resources/app/node_modules/8fold-marked/lib/marked.js | JavaScript | mit | 29,680 |
// Unit Test (numerical differentiation)
#include <gtest/gtest.h>
#include <cmath>
#include "diff.h"
#include "matrix.h"
using namespace nmlib;
static double f_11(double x){ return cos(x); }
static double f_n1(const Matrix& x){ return cos(x(0))*cos(2*x(1)); }
static Matrix f_nm(const Matrix& x){ Matrix y(3); y(0)=cos(x(0)-x(1)); y(1)=sin(x(0)-x(1)); y(2)=sin(x(0)); return y; }
TEST(diff,gradient11){
for(int i=-10; i<=10; i++){
double x=i*0.9, dx=1.e-3;
EXPECT_NEAR(gradient(f_11,x,dx,false), -sin(x), 10.e-6); // df/dx
EXPECT_NEAR(gradient(f_11,x,dx,true ), -sin(x), 10.e-12); // higher order version
}
}
TEST(diff,gradientN1){
for(int i=-10; i<=10; i++){
Matrix x(2), dx(2), dy(2);
x(0)=i*0.9;
x(1)=1.2;
dx(0)=1.e-3;
dx(1)=1.e-3;
dy(0)=-sin(x(0))*cos(2*x(1));
dy(1)=-cos(x(0))*sin(2*x(1))*2;
for(size_t j=0; j<x.nrow(); j++){
EXPECT_NEAR(gradient(f_n1,x,j,dx(j),false), dy(j), 10.e-6); // df/dxj
EXPECT_NEAR(gradient(f_n1,x,j,dx(j),true ), dy(j), 10.e-12);
}
EXPECT_NEAR(norm(gradient(f_n1,x,dx,false)-dy), 0, 10.e-6); // (df/dxj)_j
EXPECT_NEAR(norm(gradient(f_n1,x,dx,true )-dy), 0, 10.e-12);
EXPECT_NEAR(norm(gradient(f_n1,x,dx(0),false)-dy), 0, 10.e-6);
EXPECT_NEAR(norm(gradient(f_n1,x,dx(0),true)-dy), 0, 10.e-12);
}
}
TEST(diff,jacobian){
for(int i=-10; i<=10; i++){
Matrix x(2), dx(2), dy(3,2);
x(0)=i*0.9;
x(1)=1.2;
dx(0)=1.e-3;
dx(1)=1.e-3;
dy(0,0)=-sin(x(0)-x(1)); dy(0,1)=+sin(x(0)-x(1));
dy(1,0)=+cos(x(0)-x(1)); dy(1,1)=-cos(x(0)-x(1));
dy(2,0)=+cos(x(0)); dy(2,1)=0;
for(size_t j=0; j<x.nrow(); j++){
EXPECT_NEAR(norm(jacobian(f_nm,x,j,dx(j),false)-getvec(dy,j)), 0, 10.e-6); // (dfi/dxj)_i
EXPECT_NEAR(norm(jacobian(f_nm,x,j,dx(j),true )-getvec(dy,j)), 0, 10.e-12);
}
EXPECT_NEAR(norm(jacobian(f_nm,x,dx,false)-dy), 0, 10.e-6); // (dfi/dxj)_ij
EXPECT_NEAR(norm(jacobian(f_nm,x,dx,true )-dy), 0, 10.e-12);
EXPECT_NEAR(norm(jacobian(f_nm,x,dx(0),false)-dy), 0, 10.e-6);
EXPECT_NEAR(norm(jacobian(f_nm,x,dx(0),true )-dy), 0, 10.e-12);
}
}
TEST(diff,hessian){
Matrix x({1,2}), dx({1.e-3,1.e-3}), h=hessian(f_n1,x,dx);
Matrix h1(2,2);
h1(0,0) = -cos(x(0))*cos(2*x(1));
h1(1,1) = -cos(x(0))*cos(2*x(1))*4;
h1(0,1) = h1(1,0) = +sin(x(0))*sin(2*x(1))*2;
EXPECT_NEAR(norm(h-h1), 0, 1.e-5*norm(h));
EXPECT_NEAR(norm(h-tp(h)), 0, 1.e-5*norm(h));
}
| nmakimoto/nmlib | test/gtest_diff.cpp | C++ | mit | 2,456 |
import React from "react";
import { Message } from "semantic-ui-react";
import Bracket from "./Bracket";
import "./index.scss";
import parseStats from './parseStats';
export default class Brackets extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
data: this.updateStats(props),
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.stats !== this.props.stats) {
this.setState({
data: this.updateStats(nextProps),
});
}
}
updateStats = (props) => {
return parseStats(props.stats);
};
render () {
if (!this.props.stats) {
return (
<Message>Waiting for Tournament Stats...</Message>
);
}
return (
<div>
{this.state.data.map((bracket, $index) => (
<div className="tournament-bracket" key={ bracket.match.matchID }>
<Bracket
finished={ this.props.stats.finished }
item={bracket}
key={$index}
totalGames={ this.props.stats.options.numberOfGames }
/>
</div>
))}
</div>
);
}
}
| socialgorithm/ultimate-ttt-web | src/components/Lobby/Tournament/types/Brackets/index.js | JavaScript | mit | 1,151 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./41814c947891496a1acc2233f71c55d6d8d51db20b34ea7b2815cc76b4bf13c8.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | simonmysun/praxis | TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/b27a49775c444cb482bdd5ad724ef29021224f933713fb663dba33bd34c415e1.html | HTML | mit | 550 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>18 --> 19</title>
<link href="./../../assets/style.css" rel="stylesheet">
</head>
<body>
<h2>You have to be fast</h2>
<a href="./d2fe18e71c8455c6ae9719209877704ba01fd0b8a3641bcff330a4d9c8a66210.html">Teleport</a>
<hr>
<a href="./../../about.md">About</a> (Spoilers! )
<script src="./../../assets/md5.js"></script>
<script>
window.currentLevel = 7;
</script>
<script src="./../../assets/script.js"></script>
</body>
</html> | simonmysun/praxis | TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/37b93c337d764afc6c82c4a0e3a29ac3eb67cfb701bc613645d1067f200bb816.html | HTML | mit | 550 |
define([ 'backbone', 'metro', 'util' ], function(Backbone, Metro, Util) {
var MotivationBtnView = Backbone.View.extend({
className: 'motivation-btn-view menu-btn',
events: {
'click': 'toggle',
'mouseover': 'over',
'mouseout': 'out',
},
initialize: function(){
//ensure correct scope
_.bindAll(this, 'render', 'unrender', 'toggle', 'over', 'out');
//initial param
this.motivationView = new MotivationView();
//add to page
this.render();
},
render: function() {
var $button = $('<span class="mif-compass">');
$(this.el).html($button);
$(this.el).attr('title', 'motivation...');
$('body > .container').append($(this.el));
return this;
},
unrender: function() {
this.drawElementsView.unrender();
$(this.el).remove();
},
toggle: function() {
this.drawElementsView.toggle();
},
over: function() {
$(this.el).addClass('expand');
},
out: function() {
$(this.el).removeClass('expand');
}
});
var MotivationView = Backbone.View.extend({
className: 'motivation-view',
events: {
'click .draw': 'draw',
'click .clean': 'clean',
'change .input-type > select': 'clean'
},
initialize: function(){
//ensure correct scope
_.bindAll(this, 'render', 'unrender', 'toggle',
'drawMotivation', 'drawGPS', 'drawAssignedSection', 'drawAugmentedSection');
//motivation param
this.param = {};
this.param.o_lng = 114.05604600906372;
this.param.o_lat = 22.551225247189432;
this.param.d_lng = 114.09120440483093;
this.param.d_lat = 22.545463347318833;
this.param.path = "33879,33880,33881,33882,33883,33884,33885,41084,421,422,423,2383,2377,2376,2334,2335,2565,2566,2567,2568,2569,2570,2571,2572,2573,39716,39717,39718,39719,39720,39721,39722,39723,448,39677,39678";
//GPS param
this.param.gps = "114.05538082122803,22.551086528436926#114.05844390392303,22.551324331927283#114.06151771545409,22.551264881093118#114.06260132789612,22.54908499948478#114.06269788742065,22.5456862971879#114.06271934509277,22.54315951091646#114.06271934509277,22.538938188315093#114.06284809112547,22.53441944644356";
//assigned section param
this.param.assign = "33878,33881,33883,2874,2877,2347,937,941";
//augmented section param //33878,33879,33880,33881,33882,33883,2874,2875,2876,2877,2878,2347,935,936,937,938,939,940,941,
this.param.augment = "33879,33880,33882,2875,2876,2878,935,936,938,939,940";
//add to page
this.render();
},
render: function() {
//this.drawMotivation();
this.drawAssignedSection();
this.drawAugmentedSection();
this.drawGPS();
return this;
},
unrender: function() {
$(this.el).remove();
},
toggle: function() {
$(this.el).css('display') == 'none' ? $(this.el).show() : $(this.el).hide();
},
drawMotivation: function() {
$.get('api/trajectories/motivation', this.param, function(data){
Backbone.trigger('MapView:drawMotivation', data);
});
},
drawGPS: function() {
var self = this;
setTimeout(function() {
var points = self.param.gps.split('#');
_.each(points, function(point_text, index) {
var data = {};
data.geojson = self._getPoint(point_text);
data.options = {};
Backbone.trigger('MapView:drawSampleGPSPoint', data);
});
}, 2000);
},
drawAssignedSection: function() {
$.get('api/elements/sections', {id: this.param.assign}, function(data){
Backbone.trigger('MapView:drawSampleAssignedSection', data);
});
},
drawAugmentedSection: function() {
$.get('api/elements/sections', {id: this.param.augment}, function(data){
Backbone.trigger('MapView:drawSampleAugmentedSection', data);
});
},
_getPoint: function(text) {
var point = text.split(',');
var geojson = {
"type": "FeatureCollection",
"features":[{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [parseFloat(point[0]), parseFloat(point[1])]
}
}]
};
return geojson;
},
});
return MotivationBtnView;
}); | AjaxJackjia/TGA | WebContent/module/view/tools/MotivationBtnView.js | JavaScript | mit | 4,112 |
<!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_11) on Wed Mar 06 13:52:23 HST 2013 -->
<title>S-Index</title>
<meta name="date" content="2013-03-06">
<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="S-Index";
}
//-->
</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="../jsl/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="../jsl/package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-8.html">Prev Letter</a></li>
<li><a href="index-10.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-9.html" target="_top">Frames</a></li>
<li><a href="index-9.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="contentContainer"><a href="index-1.html">D</a> <a href="index-2.html">E</a> <a href="index-3.html">G</a> <a href="index-4.html">I</a> <a href="index-5.html">J</a> <a href="index-6.html">M</a> <a href="index-7.html">O</a> <a href="index-8.html">R</a> <a href="index-9.html">S</a> <a href="index-10.html">T</a> <a name="_S_">
<!-- -->
</a>
<h2 class="title">S</h2>
<dl>
<dt><span class="strong"><a href="../jsl/EasyKillBot.html#setRobotFire()">setRobotFire()</a></span> - Method in class jsl.<a href="../jsl/EasyKillBot.html" title="class in jsl">EasyKillBot</a></dt>
<dd>
<div class="block">Method <code>setRobotFire</code> sets action to fire at a
robot in range and power is proportional to distance.</div>
</dd>
<dt><span class="strong"><a href="../jsl/EasyKillBot.html#setRobotGun()">setRobotGun()</a></span> - Method in class jsl.<a href="../jsl/EasyKillBot.html" title="class in jsl">EasyKillBot</a></dt>
<dd>
<div class="block">Method <code>setRobotGun</code> sets the gun turning for the robot.</div>
</dd>
<dt><span class="strong"><a href="../jsl/EasyKillBot.html#setRobotMove()">setRobotMove()</a></span> - Method in class jsl.<a href="../jsl/EasyKillBot.html" title="class in jsl">EasyKillBot</a></dt>
<dd>
<div class="block">Method <code>setRobotMove</code> sets the turn and traveling
portion of the robot.</div>
</dd>
<dt><span class="strong"><a href="../jsl/EasyKillBot.html#setRobotRadar()">setRobotRadar()</a></span> - Method in class jsl.<a href="../jsl/EasyKillBot.html" title="class in jsl">EasyKillBot</a></dt>
<dd>
<div class="block">Method <code>setRobotRadar</code> sets the radar determines
radar action based on current information.</div>
</dd>
<dt><span class="strong"><a href="../jsl/EasyKillBot.html#setTrackedRadar()">setTrackedRadar()</a></span> - Method in class jsl.<a href="../jsl/EasyKillBot.html" title="class in jsl">EasyKillBot</a></dt>
<dd>
<div class="block">Method <code>setTrackedRadar</code> sets the radar turning for the robot.</div>
</dd>
<dt><span class="strong"><a href="../jsl/EnemyRobot.html#storeEvent(robocode.ScannedRobotEvent)">storeEvent(ScannedRobotEvent)</a></span> - Method in class jsl.<a href="../jsl/EnemyRobot.html" title="class in jsl">EnemyRobot</a></dt>
<dd>
<div class="block">Method <code>storeEvent</code> stores an event to be used later.</div>
</dd>
</dl>
<a href="index-1.html">D</a> <a href="index-2.html">E</a> <a href="index-3.html">G</a> <a href="index-4.html">I</a> <a href="index-5.html">J</a> <a href="index-6.html">M</a> <a href="index-7.html">O</a> <a href="index-8.html">R</a> <a href="index-9.html">S</a> <a href="index-10.html">T</a> </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="../jsl/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="../jsl/package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-8.html">Prev Letter</a></li>
<li><a href="index-10.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-9.html" target="_top">Frames</a></li>
<li><a href="index-9.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 ======= -->
</body>
</html>
| justinslee/robocode-jsl-EasyKillBot | doc/index-files/index-9.html | HTML | mit | 6,055 |
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_NETADDRESS_H
#define BITCOIN_NETADDRESS_H
#include "compat.h"
#include "serialize.h"
#include <stdint.h>
#include <string>
#include <vector>
extern bool fAllowPrivateNet;
enum Network
{
NET_UNROUTABLE = 0,
NET_IPV4,
NET_IPV6,
NET_TOR,
NET_MAX,
};
/** IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96)) */
class CNetAddr
{
protected:
unsigned char ip[16]; // in network byte order
uint32_t scopeId; // for scoped/link-local ipv6 addresses
public:
CNetAddr();
CNetAddr(const struct in_addr& ipv4Addr);
explicit CNetAddr(const char *pszIp, bool fAllowLookup = false);
explicit CNetAddr(const std::string &strIp, bool fAllowLookup = false);
void Init();
void SetIP(const CNetAddr& ip);
/**
* Set raw IPv4 or IPv6 address (in network byte order)
* @note Only NET_IPV4 and NET_IPV6 are allowed for network.
*/
void SetRaw(Network network, const uint8_t *data);
bool SetSpecial(const std::string &strName); // for Tor addresses
bool IsIPv4() const; // IPv4 mapped address (::FFFF:0:0/96, 0.0.0.0/0)
bool IsIPv6() const; // IPv6 address (not mapped IPv4, not Tor)
bool IsRFC1918() const; // IPv4 private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12)
bool IsRFC2544() const; // IPv4 inter-network communications (192.18.0.0/15)
bool IsRFC6598() const; // IPv4 ISP-level NAT (100.64.0.0/10)
bool IsRFC5737() const; // IPv4 documentation addresses (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24)
bool IsRFC3849() const; // IPv6 documentation address (2001:0DB8::/32)
bool IsRFC3927() const; // IPv4 autoconfig (169.254.0.0/16)
bool IsRFC3964() const; // IPv6 6to4 tunnelling (2002::/16)
bool IsRFC4193() const; // IPv6 unique local (FC00::/7)
bool IsRFC4380() const; // IPv6 Teredo tunnelling (2001::/32)
bool IsRFC4843() const; // IPv6 ORCHID (2001:10::/28)
bool IsRFC4862() const; // IPv6 autoconfig (FE80::/64)
bool IsRFC6052() const; // IPv6 well-known prefix (64:FF9B::/96)
bool IsRFC6145() const; // IPv6 IPv4-translated address (::FFFF:0:0:0/96)
bool IsTor() const;
bool IsLocal() const;
bool IsRoutable() const;
bool IsValid() const;
bool IsMulticast() const;
enum Network GetNetwork() const;
std::string ToString() const;
std::string ToStringIP(bool fUseGetnameinfo = true) const;
unsigned int GetByte(int n) const;
uint64_t GetHash() const;
bool GetInAddr(struct in_addr* pipv4Addr) const;
std::vector<unsigned char> GetGroup() const;
int GetReachabilityFrom(const CNetAddr *paddrPartner = NULL) const;
void print() const;
CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0);
bool GetIn6Addr(struct in6_addr* pipv6Addr) const;
friend bool operator==(const CNetAddr& a, const CNetAddr& b);
friend bool operator!=(const CNetAddr& a, const CNetAddr& b);
friend bool operator<(const CNetAddr& a, const CNetAddr& b);
IMPLEMENT_SERIALIZE
(
READWRITE(FLATDATA(ip));
)
friend class CSubNet;
};
class CSubNet
{
protected:
/// Network (base) address
CNetAddr network;
/// Netmask, in network byte order
uint8_t netmask[16];
/// Is this value valid? (only used to signal parse errors)
bool valid;
public:
CSubNet();
CSubNet(const CNetAddr &addr, int32_t mask);
CSubNet(const CNetAddr &addr, const CNetAddr &mask);
//constructor for single ip subnet (<ipv4>/32 or <ipv6>/128)
explicit CSubNet(const CNetAddr &addr);
bool Match(const CNetAddr &addr) const;
std::string ToString() const;
bool IsValid() const;
friend bool operator==(const CSubNet& a, const CSubNet& b);
friend bool operator!=(const CSubNet& a, const CSubNet& b);
friend bool operator<(const CSubNet& a, const CSubNet& b);
IMPLEMENT_SERIALIZE
(
READWRITE(network);
READWRITE(FLATDATA(netmask));
READWRITE(FLATDATA(valid));
)
};
/** A combination of a network address (CNetAddr) and a (TCP) port */
class CService : public CNetAddr
{
protected:
unsigned short port; // host order
public:
CService();
CService(const CNetAddr& ip, unsigned short port);
CService(const struct in_addr& ipv4Addr, unsigned short port);
CService(const struct sockaddr_in& addr);
explicit CService(const char *pszIpPort, int portDefault, bool fAllowLookup = false);
explicit CService(const char *pszIpPort, bool fAllowLookup = false);
explicit CService(const std::string& strIpPort, int portDefault, bool fAllowLookup = false);
explicit CService(const std::string& strIpPort, bool fAllowLookup = false);
void Init();
void SetPort(unsigned short portIn);
unsigned short GetPort() const;
bool GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const;
bool SetSockAddr(const struct sockaddr* paddr);
friend bool operator==(const CService& a, const CService& b);
friend bool operator!=(const CService& a, const CService& b);
friend bool operator<(const CService& a, const CService& b);
std::vector<unsigned char> GetKey() const;
std::string ToString(bool fUseGetnameinfo = true) const;
std::string ToStringPort() const;
std::string ToStringIPPort(bool fUseGetnameinfo = true) const;
void print() const;
CService(const struct in6_addr& ipv6Addr, unsigned short port);
CService(const struct sockaddr_in6& addr);
IMPLEMENT_SERIALIZE
(
CService* pthis = const_cast<CService*>(this);
READWRITE(FLATDATA(ip));
unsigned short portN = htons(port);
READWRITE(portN);
if (fRead)
pthis->port = ntohs(portN);
)
};
#endif // BITCOIN_NETADDRESS_H
| neutroncoin/neutron | src/netaddress.h | C | mit | 6,442 |
<?php
/**
* Switch shortcode
*
* @category TacticalWP-Theme
* @package TacticalWP
* @author Tyler Kemme <[email protected]>
* @license MIT https://opensource.org/licenses/MIT
* @version 1.0.4
* @link https://github.com/tpkemme/tacticalwp-theme
* @since 1.0.0
*/
/**
* Outputs an switch when the [twp-switch] is used
*
* @param [string] $atts shortcode attributes, required.
* @param [string] $content shortcode content, optional.
* @return output of shortcode
* @since 1.0.0
* @version 1.0.4
*/
function twp_switch( $atts, $content = '' ) {
$atts = shortcode_atts( array(
'id' => wp_generate_password( 6, false ),
'size' => 'small',
), $atts, 'twp-switch' );
$out = '';
$out .= '<div class="switch ' . $atts['size'] . '">
<input class="switch-input" id="' . $atts['id'] . '" type="checkbox" name="' . $atts['id'] . '"">
<label class="switch-paddle" for="' . $atts['id'] . '">
<span class="show-for-sr">Tiny Sandwiches Enabled</span>
</label>
</div>';
return $out;
}
add_shortcode( 'twp-switch', 'twp_switch' );
| tpkemme/tacticalwp-theme | library/shortcode/switch.php | PHP | mit | 1,075 |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='fcit',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='1.2.0',
description='A decision-tree based conditional independence test',
long_description=long_description,
# The project's main homepage.
url = 'https://github.com/kjchalup/fcit',
# Author details
author = 'Krzysztof Chalupka',
author_email = '[email protected]',
# Choose your license
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
# What does your project relate to?
keywords='machine learning statistics decision trees',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
# Alternatively, if you want to distribute just a my_module.py, uncomment
# this:
# py_modules=["my_module"],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['numpy', 'sklearn', 'scipy', 'joblib'],
)
| kjchalup/dtit | setup.py | Python | mit | 2,610 |
import pandas as pd
import os
import time
from datetime import datetime
import re
from time import mktime
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import style
style.use("dark_background")
# path = "X:/Backups/intraQuarter" # for Windows with X files :)
# if git clone'ed then use relative path,
# assuming you extracted the downloaded zip into this project's folder:
path = "intraQuarter"
def Key_Stats(gather="Total Debt/Equity (mrq)"):
statspath = path+'/_KeyStats'
stock_list = [x[0] for x in os.walk(statspath)]
df = pd.DataFrame(
columns = [
'Date',
'Unix',
'Ticker',
'DE Ratio',
'Price',
'stock_p_change',
'SP500',
'sp500_p_change',
'Difference',
'Status'
]
)
sp500_df = pd.DataFrame.from_csv("YAHOO-INDEX_GSPC.csv")
ticker_list = []
for each_dir in stock_list[1:25]:
each_file = os.listdir(each_dir)
# ticker = each_dir.split("\\")[1] # Windows only
# ticker = each_dir.split("/")[1] # this didn't work so do this:
ticker = os.path.basename(os.path.normpath(each_dir))
# print(ticker) # uncomment to verify
ticker_list.append(ticker)
starting_stock_value = False
starting_sp500_value = False
if len(each_file) > 0:
for file in each_file:
date_stamp = datetime.strptime(file, '%Y%m%d%H%M%S.html')
unix_time = time.mktime(date_stamp.timetuple())
full_file_path = each_dir + '/' + file
source = open(full_file_path,'r').read()
try:
try:
value = float(source.split(gather+':</td><td class="yfnc_tabledata1">')[1].split('</td>')[0])
except:
value = float(source.split(gather+':</td>\n<td class="yfnc_tabledata1">')[1].split('</td>')[0])
try:
sp500_date = datetime.fromtimestamp(unix_time).strftime('%Y-%m-%d')
row = sp500_df[(sp500_df.index == sp500_date)]
sp500_value = float(row['Adjusted Close'])
except:
sp500_date = datetime.fromtimestamp(unix_time-259200).strftime('%Y-%m-%d')
row = sp500_df[(sp500_df.index == sp500_date)]
sp500_value = float(row['Adjusted Close'])
try:
stock_price = float(source.split('</small><big><b>')[1].split('</b></big>')[0])
except:
try:
stock_price = (source.split('</small><big><b>')[1].split('</b></big>')[0])
#print(stock_price)
stock_price = re.search(r'(\d{1,8}\.\d{1,8})', stock_price)
stock_price = float(stock_price.group(1))
#print(stock_price)
except:
try:
stock_price = (source.split('<span class="time_rtq_ticker">')[1].split('</span>')[0])
#print(stock_price)
stock_price = re.search(r'(\d{1,8}\.\d{1,8})', stock_price)
stock_price = float(stock_price.group(1))
#print(stock_price)
except:
print('wtf stock price lol',ticker,file, value)
time.sleep(5)
if not starting_stock_value:
starting_stock_value = stock_price
if not starting_sp500_value:
starting_sp500_value = sp500_value
stock_p_change = ((stock_price - starting_stock_value) / starting_stock_value) * 100
sp500_p_change = ((sp500_value - starting_sp500_value) / starting_sp500_value) * 100
location = len(df['Date'])
difference = stock_p_change-sp500_p_change
if difference > 0:
status = "outperform"
else:
status = "underperform"
df = df.append({'Date':date_stamp,
'Unix':unix_time,
'Ticker':ticker,
'DE Ratio':value,
'Price':stock_price,
'stock_p_change':stock_p_change,
'SP500':sp500_value,
'sp500_p_change':sp500_p_change,
############################
'Difference':difference,
'Status':status},
ignore_index=True)
except Exception as e:
pass
#print(ticker,e,file, value)
#print(ticker_list)
#print(df)
for each_ticker in ticker_list:
try:
plot_df = df[(df['Ticker'] == each_ticker)]
plot_df = plot_df.set_index(['Date'])
if plot_df['Status'][-1] == 'underperform':
color = 'r'
else:
color = 'g'
plot_df['Difference'].plot(label=each_ticker, color=color)
plt.legend()
except Exception as e:
print(str(e))
plt.show()
save = gather.replace(' ','').replace(')','').replace('(','').replace('/','')+str('.csv')
print(save)
df.to_csv(save)
Key_Stats()
| PythonProgramming/Support-Vector-Machines---Basics-and-Fundamental-Investing-Project | p10.py | Python | mit | 4,949 |
/*
* App Actions
*
* Actions change things in your application
* Since this boilerplate uses a uni-directional data flow, specifically redux,
* we have these actions which are the only way your application interacts with
* your application state. This guarantees that your state is up to date and nobody
* messes it up weirdly somewhere.
*
* To add a new Action:
* 1) Import your constant
* 2) Add a function like this:
* export function yourAction(var) {
* return { type: YOUR_ACTION_CONSTANT, var: var }
* }
*/
import {
LOAD_SONGS,
LOAD_SONGS_SUCCESS,
LOAD_SONGS_ERROR,
} from './constants';
// /**
// * Load the repositories, this action starts the request saga
// *
// * @return {object} An action object with a type of LOAD_REPOS
// */
export function loadSongs() {
return {
type: LOAD_SONGS,
};
}
// /**
// * Dispatched when the repositories are loaded by the request saga
// *
// * @param {array} repos The repository data
// * @param {string} username The current username
// *
// * @return {object} An action object with a type of LOAD_REPOS_SUCCESS passing the repos
// */
export function songsLoaded(repos, username) {
return {
type: LOAD_SONGS_SUCCESS,
repos,
username,
};
}
// /**
// * Dispatched when loading the repositories fails
// *
// * @param {object} error The error
// *
// * @return {object} An action object with a type of LOAD_REPOS_ERROR passing the error
// */
export function songsLoadingError(error) {
return {
type: LOAD_SONGS_ERROR,
error,
};
}
| madHEYsia/Muzk | app/containers/App/actions.js | JavaScript | mit | 1,581 |
# oninput-fix
>Fix input event in jquery, support low version of ie.
### Introduction:
Default is CommonJS module
If not CommonJS you must do this:
>1.Remove first and last line of the code
>
>2.Wrap code useing:
```js
(function ($){
// the code of remove first and last line
}(jQuery));
```
### API:
Sample:
>
```js
$('#input').on('input', callback);
$('#input').input(callback);
$('#input').off('input', callback);
$('#input').uninput(callback);
```
### Notice:
Dot change input value in low version of ie without condition statement, because it will go into an infinite loop!
| nuintun/oninput-fix | README.md | Markdown | mit | 587 |
package cmd
import (
"errors"
"github.com/cretz/go-safeclient/client"
"github.com/spf13/cobra"
"log"
"os"
)
var lsShared bool
var lsCmd = &cobra.Command{
Use: "ls [dir]",
Short: "Fetch directory information",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("One and only one argument allowed")
}
c, err := getClient()
if err != nil {
log.Fatalf("Unable to obtain client: %v", err)
}
info := client.GetDirInfo{DirPath: args[0], Shared: lsShared}
dir, err := c.GetDir(info)
if err != nil {
log.Fatalf("Failed to list dir: %v", err)
}
writeDirResponseTable(os.Stdout, dir)
return nil
},
}
func init() {
lsCmd.Flags().BoolVarP(&lsShared, "shared", "s", false, "Use shared area for user")
RootCmd.AddCommand(lsCmd)
}
| cretz/go-safeclient | cmd/ls.go | GO | mit | 804 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>rb-aem manual | 3. Packing and unpacking data</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css" media="all"><!--@import url(../full.css);--></style>
</head>
<body>
<h1><img src="../rb-appscript-logo.png" alt="rb-appscript" title="rb-appscript" /></h1>
<!-- top navigation -->
<div class="navbar">
<a href="02_apioverview.html">Previous</a> •
<a href="index.html">Up</a> •
<a href="04_references.html">Next</a>
<span>
<a href="../appscript-manual/index.html">appscript</a> /
<a href="../mactypes-manual/index.html">mactypes</a> /
<a href="../osax-manual/index.html">osax</a> /
<strong><a href="../aem-manual/index.html">aem</a></strong>
</span>
</div>
<!-- content -->
<div id="content">
<h2>3. Packing and unpacking data</h2>
<h3>Codecs</h3>
<p>The <code>AEM::Codecs</code> class provides methods for converting Ruby data to <code>AE::AEDesc</code> objects, and vice-versa.</p>
<pre><code>Codecs
Constructor:
new
Methods:
# pack/unpack data
pack(data) -- convert Ruby data to an AEDesc; will raise
a TypeError if data's type/class is unsupported
data : anything
Result : AEDesc
unpack(desc) -- convert an AEDesc to Ruby data; will return
the AEDesc unchanged if it's an unsupported type
desc : AEDesc
Result : anything
# compatibility options
add_unit_types(types) -- register custom unit type
definitions
types : list -- a list of lists, where each sublist
is of form [name, code, pack_proc, unpack_proc]
or [name, code]; if the packer and unpacker
procs are omitted, the AEDesc data is packed/
unpacked as a double-precision float
dont_cache_unpacked_specifiers -- by default, object
specifier descriptors returned by an application
are reused for efficiency; invoke this method to
use AppleScript-style behavior instead (i.e. fully
unpacking and repacking object specifiers each time)
for better compatibility with problem applications
pack_strings_as_type(code) -- by default, strings are
packed as typeUnicodeText descriptors; some older
non-Unicode-aware applications may require text
to be supplied as typeChar/typeIntlText descriptors
code : String -- four-char code, e.g. KAE::TypeChar
(see KAE module for available text types)
use_ascii_8bit -- by default, text descriptors are unpacked
as Strings with UTF-8 Encoding on Ruby 1.9+; invoke
this method to mimic Ruby 1.8-style behavior where
Strings contain UTF-8 encoded data and ASCII-8BIT
Encoding
use_datetime -- by default, dates are unpacked as Time
instances; invoke this method to unpack dates as
DateTime instances instead</code></pre>
<h3>AE types</h3>
<p>The Apple Event Manager defines several types for representing type/class names, enumerator names, etc. that have no direct equivalent in Ruby. Accordingly, aem defines several classes to represent these types on the Ruby side. All share a common abstract base class, <code>AETypeBase</code>:</p>
<pre><code>AETypeBase -- Abstract base class
Constructor:
new(code)
code : str -- a four-character Apple event code
Methods:
code
Result : str -- Apple event code</code></pre>
<p>The four concrete classes are:</p>
<pre><code>AEType < AETypeBase -- represents an AE object of typeType
AEEnum < AETypeBase -- represents an AE object of typeEnumeration
AEProp < AETypeBase -- represents an AE object of typeProperty
AEKey < AETypeBase -- represents an AE object of typeKeyword</code></pre>
</div>
<!-- bottom navigation -->
<div class="footer">
<a href="02_apioverview.html">Previous</a> •
<a href="index.html">Up</a> •
<a href="04_references.html">Next</a>
</div>
</body>
</html> | mattgraham/play-graham | vendor/gems/ruby/1.8/gems/rb-appscript-0.6.1/doc/aem-manual/03_packingandunpackingdata.html | HTML | mit | 4,487 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<base data-ice="baseUrl">
<title data-ice="title">Home | incarnate</title>
<link type="text/css" rel="stylesheet" href="css/style.css">
<link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">
<script src="script/prettify/prettify.js"></script>
<script src="script/manual.js"></script>
<meta name="description" content="Dependency Injection (DI) with Lifecycle features for JavaScript."><meta property="twitter:card" content="summary"><meta property="twitter:title" content="incarnate"><meta property="twitter:description" content="Dependency Injection (DI) with Lifecycle features for JavaScript."></head>
<body class="layout-container" data-ice="rootContainer">
<header>
<a href="./">Home</a>
<a href="identifiers.html">Reference</a>
<a href="source.html">Source</a>
<div class="search-box">
<span>
<img src="./image/search.png">
<span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span>
</span>
<ul class="search-result"></ul>
</div>
<a style="position:relative; top:3px;" href="https://github.com/resistdesign/incarnate"><img width="20px" src="./image/github.png"></a></header>
<nav class="navigation" data-ice="nav"><div>
<ul>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/ConfigurableInstance.jsx~ConfigurableInstance.html">ConfigurableInstance</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/DependencyDeclaration.jsx~DependencyDeclaration.html">DependencyDeclaration</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/HashMatrix.jsx~HashMatrix.html">HashMatrix</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/Incarnate.jsx~Incarnate.html">Incarnate</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/LifePod.jsx~LifePod.html">LifePod</a></span></span></li>
<li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/SubMapDeclaration.jsx~SubMapDeclaration.html">SubMapDeclaration</a></span></span></li>
</ul>
</div>
</nav>
<div class="content" data-ice="content"><div data-ice="index" class="github-markdown"><h1 id="incarnate--a-href--https---travis-ci-org-resistdesign-incarnate---img-src--https---travis-ci-org-resistdesign-incarnate-svg-branch-master--alt--build-status----a-">Incarnate <a href="https://travis-ci.org/resistdesign/incarnate"><img src="https://travis-ci.org/resistdesign/incarnate.svg?branch=master" alt="Build Status"></a></h1><p>Runtime Dependency Lifecycle Management for JavaScript.</p>
<h2 id="install">Install</h2><p><code>npm i -S incarnate</code></p>
<h2 id="api-docs">API Docs</h2><p><a href="http://incarnate.resist.design">http://incarnate.resist.design</a></p>
<h2 id="usage-example">Usage Example</h2><pre><code class="lang-jsx"><code class="source-code prettyprint">import Incarnate from 'incarnate';
// Declare your application dependencies.
const inc = new Incarnate({
subMap: {
// Keep track of your state.
state: {
subMap: {
user: {
factory: () => ({
authToken: undefined
})
}
}
},
// Supply some services.
services: {
// Some services need authorization information.
shared: {
user: 'state.user'
},
subMap: {
user: true,
login: {
factory: () => {
return async (username, password) => {
// Make a login request, get the `authToken`.
const fakeToken = `${username}:${password}`;
// For demo purposes we'll use the `Buffer` API in node.js to base64 encode the credentials.
return Buffer.from(fakeToken).toString('base64');
};
}
},
accounts: {
dependencies: {
user: 'user'
},
factory: ({dependencies: {user: {authToken = ''} = {}} = {}} = {}) => {
return async () => {
// NOTE: IF we call this service method AFTER `login`,
// the `authToken` will have been automatically updated,
// in this service, by Incarnate.
if (!authToken) {
throw new Error('The accounts service requires an authorization token but one was not supplied.');
}
// Get a list of accounts with the `authToken` in the headers.
console.log('Getting accounts with headers:', {
Authorization: `Bearer: ${authToken}`
});
return [
{name: 'Account 1'},
{name: 'Account 2'},
{name: 'Account 3'},
{name: 'Account 4'}
];
};
}
}
}
},
// Expose some actions that call services and store the results in a nice, tidy, reproducible way.
actions: {
shared: {
user: 'state.user',
loginService: 'services.login'
},
subMap: {
user: true,
loginService: true,
login: {
dependencies: {
loginService: 'loginService'
},
setters: {
setUser: 'user'
},
factory: ({dependencies: {loginService} = {}, setters: {setUser} = {}} = {}) => {
return async ({username, password} = {}) => {
// Login
const authToken = await loginService(username, password);
// Store the `authToken`.
setUser({
authToken
});
return true;
};
}
}
}
}
}
});
// Here's your app.
export default async function app() {
// Get the Login Action.
const loginAction = inc.getResolvedPath('actions.login');
// Do the login.
const loginResult = await loginAction({
username: 'TestUser',
password: 'StopTryingToReadThis'
});
// Get the Accounts Service. It needs the User's `authToken`,
// but you declared it as a Dependency,
// so Incarnate took care of that for you.
const accountsService = inc.getResolvedPath('services.accounts');
// Get those accounts you've been dying to see...
const accounts = await accountsService();
// Here they are!
console.log('These are the accounts:', accounts);
}
// You need to run your app.
app();</code>
</code></pre>
<h2 id="license">License</h2><p><a href="LICENSE.txt">MIT</a></p>
</div>
</div>
<footer class="footer">
Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(1.0.4)</span><img src="./image/esdoc-logo-mini-black.png"></a>
</footer>
<script src="script/search_index.js"></script>
<script src="script/search.js"></script>
<script src="script/pretty-print.js"></script>
<script src="script/inherited-summary.js"></script>
<script src="script/test-summary.js"></script>
<script src="script/inner-link.js"></script>
<script src="script/patch-for-local.js"></script>
</body>
</html>
| resistdesign/incarnate | docs/index.html | HTML | mit | 7,614 |
const simple_sort = (key, a, b) => {
if (a[key] < b[key]) return -1
if (a[key] > b[key]) return 1
return 0
}
const name_sort = (a, b) => simple_sort('name', a, b)
const skill_sort = (a, b) => simple_sort('skill', a, b)
const speed_sort = (a, b) => simple_sort('speed', a, b)
export {
simple_sort,
name_sort,
skill_sort,
speed_sort
} | stevegood/tython | util/sorting.js | JavaScript | mit | 348 |
export { default } from './EditData';
| caspg/datamaps.co | src/pages/Editor/pages/MapEditor/pages/EditData/index.js | JavaScript | mit | 38 |
<footer id="footer" role="contentinfo">
<a href="#" class="gotop js-gotop"><i class="icon-arrow-up2"></i></a>
<div class="container">
<div class="">
<div class="col-md-12 text-center">
<p>{{ with .Site.Params.footer.copyright }}{{ . | markdownify }}{{ end }}</p>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
<ul class="social social-circle">
{{ range .Site.Params.footer.links }}
<li><a href="{{ with index . 1}}{{ . }}{{ end }}"><i class="{{ with index . 0}}{{ . }}{{ end }}"></i></a></li>
{{ end }}
</ul>
</div>
</div>
</div>
</footer>
| saey55/hugo-elate-theme | layouts/partials/footer.html | HTML | mit | 647 |
using System.Xml.Linq;
namespace Lux.Serialization.Xml
{
public interface IXmlConfigurable
{
void Configure(XElement element);
}
} | LazyTarget/Lux | src/Lux/Serialization/Xml/Interfaces/IXmlConfigurable.cs | C# | mit | 154 |
<?php
/*
Section: signup
Language: Hungarian
Translator: uno20001 <[email protected]>
*/
$translations = array(
'h1' => 'Regisztráció',
'mysql-db-name' => 'MySQL adatbázis név',
'mysql-user-name' => 'MySQL felhasználónév',
'mysql-user-password' => 'MySQL jelszó',
'mysql-user-password-verification' => 'MySQL jelszó megerősítése',
'email-address' => 'Email cím',
'agree-conditions' => 'Elolvastam a <a href="conditions.php">felhasználási feltételeket</a> és egyetértek velük.',
'ph1' => '6-16 karakter, nem lehet nagybetű, az 1. karakternek betűnek kell lennie.',
'ph2' => 'Min. 8 karakter.',
'ph3' => 'Írd be az email címed',
'explanation' => 'A felhasználónév és az adatbázis név tartalmazhat kisbetűket, számokat és \'_\' (aláhúzás) karaktert, a hosszának 6 és 16 karakter között kell lennie. Nem használhatsz <a href="https://dev.mysql.com/doc/refman/8.0/en/keywords.html">a MySQL számára fenntartott szavakat</a>!',
'maintenance-notice' => 'Karbantartás miatt a regisztráció jelenleg nem érhető el.',
'agm-p1' => 'A regisztrációddal elfogadod a következőket:',
'agm-li1' => 'A db4free.net egy tesztelési környezet',
'agm-li2' => 'A db4free.net nem megfelelő nem teszt jellegű használathoz',
'agm-li3' => 'Ha úgy döntesz, hogy nem teszt jellegű dolgokhoz kívánod használni a db4free.net-et, akkor azt csak a saját felelősségedre tedd (a nagyon gyakori mentések nagyon ajánlottak)',
'agm-li4' => 'Adatvesztések és üzemidő kiesések bármikor történhetnek (az ezzel kapcsolatos panaszok valószínűleg figyelmen kívül lesznek hagyva)',
'agm-li5' => 'A db4free.net csapata nem biztosít semmilyen garanciát, felelősséget',
'agm-li6' => 'A db4free.net csapata fenntartja a jogot, hogy bármikor, figyelmeztetés nélkül törölje az adatbázisod és/vagy fiókod',
'agm-li7' => 'A db4free.net-tel kapcsolatos legfrissebb információkat elérheted a <a href="twitter.php">Twitteren</a> és a <a href="blog.php">db4free.net blogon</a>',
'agm-li8' => 'A db4free.net csak MySQL adatbázist biztosít, nem ad webtárhelyet (nincs lehetőséged itt tárolni a fájljaidat)',
'agm-p2' => 'Továbbiakban:',
'agm-li9' => 'A db4free.net egy tesztelő szolgáltatás, nem "éles" szolgáltatásokhoz készült. Azok az adatbázisok, amelyek 200 MB-nál több adatot tartalmaznak, értesítés nélkül kiürítésre kerülnek.',
'agm-li10' => 'Kérlek <a href="/delete-account.php">távolítsd el</a> azokat az adatokat és/vagy fiókot amikre/amelyre már nincs szükséged. Ez megkönnyíti a ténylegesen használt adatok visszaállítását, ha a szerver "összeomlik"',
'signup-error1' => 'El kell fogadnod a felhasználási feltételeket!',
'signup-error2' => 'Hiba lépett fel a regisztráció során!',
'signup-error3' => 'Hiba lépett fel a megerősítő email küldése közben!',
'signup-success' => 'Köszönjük a regisztrációt! Hamarosan kapsz egy megerősítő emailt!',
);
?>
| mpopp75/db4free-net-l10n | hu/signup.php | PHP | mit | 3,111 |
// ==========================================================================
// DG.ScatterPlotModel
//
// Author: William Finzer
//
// Copyright (c) 2014 by The Concord Consortium, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ==========================================================================
sc_require('components/graph/plots/plot_model');
sc_require('components/graph/plots/numeric_plot_model_mixin');
/** @class DG.ScatterPlotModel
@extends DG.PlotModel
*/
DG.ScatterPlotModel = DG.PlotModel.extend(DG.NumericPlotModelMixin,
/** @scope DG.ScatterPlotModel.prototype */
{
/**
*
* @param iPlace {DG.GraphTypes.EPlace}
* @return { class }
*/
getDesiredAxisClassFor: function( iPlace) {
if( iPlace === DG.GraphTypes.EPlace.eX || iPlace === DG.GraphTypes.EPlace.eY)
return DG.CellLinearAxisModel;
else if(iPlace === DG.GraphTypes.EPlace.eY2) {
return (this.getPath('dataConfiguration.y2AttributeID') === DG.Analysis.kNullAttribute) ?
DG.AxisModel : DG.CellLinearAxisModel;
}
},
/**
@property { DG.MovablePointModel }
*/
movablePoint: null,
/**
@property { Boolean }
*/
isMovablePointVisible: function () {
return !SC.none(this.movablePoint) && this.movablePoint.get('isVisible');
}.property(),
isMovablePointVisibleDidChange: function() {
this.notifyPropertyChange('isMovablePointVisible');
}.observes('*movablePoint.isVisible'),
/**
@property { DG.MovableLineModel }
*/
movableLine: null,
/**
@property { Boolean, read only }
*/
isMovableLineVisible: function () {
return !SC.none(this.movableLine) && this.movableLine.get('isVisible');
}.property(),
isMovableLineVisibleDidChange: function() {
this.notifyPropertyChange('isMovableLineVisible');
}.observes('*movableLine.isVisible'),
/**
@property { DG.MultipleLSRLsModel }
*/
multipleLSRLs: null,
/**
@property { Boolean, read only }
*/
isLSRLVisible: function () {
return !SC.none(this.multipleLSRLs) && this.multipleLSRLs.get('isVisible');
}.property(),
isLSRLVisibleDidChange: function() {
this.notifyPropertyChange('isLSRLVisible');
}.observes('*multipleLSRLs.isVisible'),
/**
@property { Boolean }
*/
isInterceptLocked: function ( iKey, iValue) {
if( !SC.none( iValue)) {
this.setPath('movableLine.isInterceptLocked', iValue);
this.setPath('multipleLSRLs.isInterceptLocked', iValue);
}
return !SC.none(this.movableLine) && this.movableLine.get('isInterceptLocked') ||
!SC.none(this.multipleLSRLs) && this.multipleLSRLs.get('isInterceptLocked');
}.property(),
isInterceptLockedDidChange: function() {
this.notifyPropertyChange('isInterceptLocked');
}.observes('*movableLine.isInterceptLocked', '*multipleLSRLs.isInterceptLocked'),
/**
@property { Boolean }
*/
areSquaresVisible: false,
/**
* Used for notification
* @property{}
*/
squares: null,
init: function() {
sc_super();
this.addObserver('movableLine.slope',this.lineDidChange);
this.addObserver('movableLine.intercept',this.lineDidChange);
},
destroy: function() {
this.removeObserver('movableLine.slope',this.lineDidChange);
this.removeObserver('movableLine.intercept',this.lineDidChange);
sc_super();
},
dataConfigurationDidChange: function() {
sc_super();
var tDataConfiguration = this.get('dataConfiguration');
if( tDataConfiguration) {
tDataConfiguration.set('sortCasesByLegendCategories', false);
// This is a cheat. The above line _should_ bring this about, but I couldn't make it work properly
tDataConfiguration.invalidateCaches();
}
}.observes('dataConfiguration'),
/**
Returns true if the plot is affected by the specified change such that
a redraw is required, false otherwise.
@param {Object} iChange -- The change request to/from the DataContext
@returns {Boolean} True if the plot must redraw, false if it is unaffected
*/
isAffectedByChange: function (iChange) {
if (!iChange || !iChange.operation) return false;
return sc_super() ||
(this.isAdornmentVisible('connectingLine') &&
(iChange.operation === 'moveAttribute' || iChange.operation === 'moveCases'));
},
/**
* Used for notification
*/
lineDidChange: function () {
SC.run(function() {
this.notifyPropertyChange('squares');
}.bind(this));
},
/**
* Utility function to create a movable line when needed
*/
createMovablePoint: function () {
if (SC.none(this.movablePoint)) {
this.beginPropertyChanges();
this.set('movablePoint', DG.MovablePointModel.create( {
plotModel: this
}));
this.movablePoint.recomputeCoordinates(this.get('xAxis'), this.get('yAxis'));
this.endPropertyChanges();
}
},
/**
* Utility function to create a movable line when needed
*/
createMovableLine: function () {
if (SC.none(this.movableLine)) {
this.beginPropertyChanges();
this.set('movableLine', DG.MovableLineModel.create( {
plotModel: this,
showSumSquares: this.get('areSquaresVisible')
}));
this.movableLine.recomputeSlopeAndIntercept(this.get('xAxis'), this.get('yAxis'));
this.endPropertyChanges();
}
},
squaresVisibilityChanged: function() {
var tMovableLine = this.get('movableLine'),
tMultipleLSRLs = this.get('multipleLSRLs'),
tSquaresVisible = this.get('areSquaresVisible');
if( tMovableLine)
tMovableLine.set('showSumSquares', tSquaresVisible);
if( tMultipleLSRLs)
tMultipleLSRLs.set('showSumSquares', tSquaresVisible);
}.observes('areSquaresVisible'),
enableMeasuresForSelectionDidChange: function(){
sc_super();
this.setPath('multipleLSRLs.enableMeasuresForSelection', this.get('enableMeasuresForSelection'));
}.observes('enableMeasuresForSelection'),
/**
If we need to make a movable line, do so. In any event toggle its visibility.
*/
toggleMovablePoint: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
if (SC.none(iPlot.movablePoint)) {
iPlot.createMovablePoint(); // Default is to be visible
}
else {
iPlot.movablePoint.recomputePositionIfNeeded(iPlot.get('xAxis'), iPlot.get('yAxis'));
iPlot.movablePoint.set('isVisible', !iPlot.movablePoint.get('isVisible'));
}
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
var willShow = !this.movablePoint || !this.movablePoint.get('isVisible');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleMovablePoint",
undoString: (willShow ? 'DG.Undo.graph.showMovablePoint' : 'DG.Undo.graph.hideMovablePoint'),
redoString: (willShow ? 'DG.Redo.graph.showMovablePoint' : 'DG.Redo.graph.hideMovablePoint'),
log: "toggleMovablePoint: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle movable point',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
},
undo: function () {
toggle();
}
}));
},
/**
If we need to make a movable line, do so. In any event toggle its visibility.
*/
toggleMovableLine: function () {
var this_ = this;
function toggle() {
function doToggle(iPlot) {
if (SC.none(iPlot.movableLine)) {
iPlot.createMovableLine(); // Default is to be visible
}
else {
iPlot.movableLine.recomputeSlopeAndInterceptIfNeeded(iPlot.get('xAxis'), iPlot.get('yAxis'));
iPlot.movableLine.set('isVisible', !iPlot.movableLine.get('isVisible'));
}
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
var willShow = !this.movableLine || !this.movableLine.get('isVisible');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleMovableLine",
undoString: (willShow ? 'DG.Undo.graph.showMovableLine' : 'DG.Undo.graph.hideMovableLine'),
redoString: (willShow ? 'DG.Redo.graph.showMovableLine' : 'DG.Redo.graph.hideMovableLine'),
log: "toggleMovableLine: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle movable line',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
},
undo: function () {
toggle();
}
}));
},
/**
* Utility function to create the multipleLSRLs object when needed
*/
createLSRLLines: function () {
if (SC.none(this.multipleLSRLs)) {
this.set('multipleLSRLs', DG.MultipleLSRLsModel.create( {
plotModel: this,
showSumSquares: this.get('areSquaresVisible'),
isInterceptLocked: this.get('isInterceptLocked'),
enableMeasuresForSelection: this.get('enableMeasuresForSelection')
}));
this.setPath('multipleLSRLs.isVisible', true);
}
},
/**
If we need to make a movable line, do so. In any event toggle its visibility.
*/
toggleLSRLLine: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
if (SC.none(iPlot.get('multipleLSRLs'))) {
iPlot.createLSRLLines();
}
else {
iPlot.setPath('multipleLSRLs.isVisible', !iPlot.getPath('multipleLSRLs.isVisible'));
}
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
var willShow = !this.multipleLSRLs || !this.multipleLSRLs.get('isVisible');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleLSRLLine",
undoString: (willShow ? 'DG.Undo.graph.showLSRL' : 'DG.Undo.graph.hideLSRL'),
redoString: (willShow ? 'DG.Redo.graph.showLSRL' : 'DG.Redo.graph.hideLSRL'),
log: "toggleLSRL: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle LSRL',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
},
undo: function () {
toggle();
}
}));
},
/**
If we need to make a movable line, do so. In any event toggle whether its intercept is locked.
*/
toggleInterceptLocked: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
if (!SC.none(iPlot.movableLine)) {
iPlot.movableLine.toggleInterceptLocked();
iPlot.movableLine.recomputeSlopeAndInterceptIfNeeded(iPlot.get('xAxis'), iPlot.get('yAxis'));
}
if (!SC.none(iPlot.multipleLSRLs)) {
iPlot.multipleLSRLs.toggleInterceptLocked();
}
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
function gatherUndoData() {
function doGatherUndoData( iPlot) {
tResult.push( {
movableLine: iPlot.movableLine ? iPlot.movableLine.createStorage() : null,
lsrlStorage: iPlot.multipleLSRLs ? iPlot.multipleLSRLs.createStorage() : null
});
}
var tResult = [];
doGatherUndoData( this_);
this_.get('siblingPlots').forEach( doGatherUndoData);
return tResult;
}
function restoreFromUndoData( iUndoData) {
function doRestoreFromUndoData( iPlot, iIndexMinusOne) {
var tUndoData = iUndoData[ iIndexMinusOne + 1];
if( iPlot.movableLine)
iPlot.movableLine.restoreStorage(tUndoData.movableLine);
if( iPlot.multipleLSRLs)
iPlot.multipleLSRLs.restoreStorage(tUndoData.lsrlStorage);
}
doRestoreFromUndoData( this_, -1);
this_.get('siblingPlots').forEach( doRestoreFromUndoData);
}
var willLock = (this.movableLine && !this.movableLine.get('isInterceptLocked')) ||
(this.multipleLSRLs && !this.multipleLSRLs.get('isInterceptLocked'));
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleLockIntercept",
undoString: (willLock ? 'DG.Undo.graph.lockIntercept' : 'DG.Undo.graph.unlockIntercept'),
redoString: (willLock ? 'DG.Redo.graph.lockIntercept' : 'DG.Redo.graph.unlockIntercept'),
log: "lockIntercept: %@".fmt(willLock),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle lock intercept',
type: 'DG.GraphView'
}
},
execute: function () {
this._undoData = gatherUndoData();
toggle();
},
undo: function () {
restoreFromUndoData( this._undoData);
this._undoData = null;
}
}));
},
/**
If we need to make a plotted function, do so. In any event toggle its visibility.
*/
togglePlotFunction: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
iPlot.toggleAdornmentVisibility('plottedFunction', 'togglePlotFunction');
}
this_.get('siblingPlots').forEach( doToggle);
doToggle( this_);
}
function connectFunctions() {
var tSiblingPlots = this_.get('siblingPlots'),
tMasterPlottedFunction = this_.getAdornmentModel('plottedFunction');
tMasterPlottedFunction.set('siblingPlottedFunctions',
tSiblingPlots.map( function( iPlot) {
return iPlot.getAdornmentModel( 'plottedFunction');
}));
}
var willShow = !this.isAdornmentVisible('plottedFunction');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.togglePlotFunction",
undoString: (willShow ? 'DG.Undo.graph.showPlotFunction' : 'DG.Undo.graph.hidePlotFunction'),
redoString: (willShow ? 'DG.Redo.graph.showPlotFunction' : 'DG.Redo.graph.hidePlotFunction'),
log: "togglePlotFunction: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle plot function',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
connectFunctions();
},
undo: function () {
toggle();
this_.getAdornmentModel('plottedFunction').set('siblingPlottedFunctions', null);
}
}));
},
/**
If we need to make a connecting line, do so. In any event toggle its visibility.
*/
toggleConnectingLine: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
var tAdornModel = iPlot.toggleAdornmentVisibility('connectingLine', 'toggleConnectingLine');
if (tAdornModel && tAdornModel.get('isVisible'))
tAdornModel.recomputeValue(); // initialize
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
var willShow = !this.isAdornmentVisible('connectingLine');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleConnectingLine",
undoString: (willShow ? 'DG.Undo.graph.showConnectingLine' : 'DG.Undo.graph.hideConnectingLine'),
redoString: (willShow ? 'DG.Redo.graph.showConnectingLine' : 'DG.Redo.graph.hideConnectingLine'),
log: "toggleConnectingLine: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle connecting line',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
},
undo: function () {
toggle();
}
}));
},
/**
* Toggle where the squares drawn from points to lines and functions are being shown
*/
toggleShowSquares: function () {
var this_ = this;
function toggle() {
function doToggle( iPlot) {
iPlot.set('areSquaresVisible', !iPlot.get('areSquaresVisible'));
}
doToggle( this_);
this_.get('siblingPlots').forEach( doToggle);
}
var willShow = !this.get('areSquaresVisible');
DG.UndoHistory.execute(DG.Command.create({
name: "graph.toggleShowSquares",
undoString: (willShow ? 'DG.Undo.graph.showSquares' : 'DG.Undo.graph.hideSquares'),
redoString: (willShow ? 'DG.Redo.graph.showSquares' : 'DG.Redo.graph.hideSquares'),
log: "toggleShowSquares: %@".fmt(willShow ? "show" : "hide"),
executeNotification: {
action: 'notify',
resource: 'component',
values: {
operation: 'toggle show squares',
type: 'DG.GraphView'
}
},
execute: function () {
toggle();
},
undo: function () {
toggle();
}
}));
},
handleDataConfigurationChange: function (iKey) {
sc_super();
this.rescaleAxesFromData(iKey !== 'hiddenCases', /* allow scale shrinkage */
true /* do animation */);
var adornmentModel = this.getAdornmentModel('connectingLine');
if (adornmentModel) {
adornmentModel.setComputingNeeded(); // invalidate if axis model/attribute change
}
},
/**
Each axis should rescale based on the values to be plotted with it.
@param{Boolean} Default is false
@param{Boolean} Default is true
@param{Boolean} Default is false
*/
rescaleAxesFromData: function (iAllowScaleShrinkage, iAnimatePoints, iLogIt, isUserAction) {
if (iAnimatePoints === undefined)
iAnimatePoints = true;
this.doRescaleAxesFromData([DG.GraphTypes.EPlace.eX, DG.GraphTypes.EPlace.eY, DG.GraphTypes.EPlace.eY2],
iAllowScaleShrinkage, iAnimatePoints, isUserAction);
if (iLogIt && !isUserAction)
DG.logUser("rescaleScatterplot");
},
/**
@param{ {x: {Number}, y: {Number} } }
@param{Number}
*/
dilate: function (iFixedPoint, iFactor) {
this.doDilation([DG.GraphTypes.EPlace.eX, DG.GraphTypes.EPlace.eY], iFixedPoint, iFactor);
},
/**
* Return a list of objects { key, class, useAdornmentModelsArray, storage }
* Subclasses should override calling sc_super first.
* @return {[Object]}
*/
getAdornmentSpecs: function() {
var tSpecs = sc_super(),
this_ = this;
['movablePoint', 'movableLine', 'multipleLSRLs'].forEach( function( iKey) {
var tAdorn = this_.get( iKey);
if (tAdorn)
tSpecs.push({
key: iKey,
"class": tAdorn.constructor,
useAdornmentModelsArray: false,
storage: tAdorn.createStorage()
});
});
DG.ObjectMap.forEach( this._adornmentModels, function( iKey, iAdorn) {
tSpecs.push( {
key: iKey,
"class": iAdorn.constructor,
useAdornmentModelsArray: true,
storage: iAdorn.createStorage()
});
});
return tSpecs;
},
/**
* Base class will do most of the work. We just have to finish up setting the axes.
* @param {DG.PlotModel} iSourcePlot
*/
installAdornmentModelsFrom: function( iSourcePlot) {
sc_super();
var tMovablePoint = this.get('movablePoint');
if (tMovablePoint) {
tMovablePoint.set('xAxis', this.get('xAxis'));
tMovablePoint.set('yAxis', this.get('yAxis'));
tMovablePoint.recomputeCoordinates(this.get('xAxis'), this.get('yAxis'));
}
var tMultipleLSRLs = this.get('multipleLSRLs');
if (tMultipleLSRLs) {
tMultipleLSRLs.recomputeSlopeAndInterceptIfNeeded(this.get('xAxis'), this.get('yAxis'));
}
},
checkboxDescriptions: function () {
var this_ = this;
return sc_super().concat([
{
title: 'DG.Inspector.graphConnectingLine',
value: this_.isAdornmentVisible('connectingLine'),
classNames: 'dg-graph-connectingLine-check'.w(),
valueDidChange: function () {
this_.toggleConnectingLine();
}.observes('value')
},
{
title: 'DG.Inspector.graphMovablePoint',
value: this_.get('isMovablePointVisible'),
classNames: 'dg-graph-movablePoint-check'.w(),
valueDidChange: function () {
this_.toggleMovablePoint();
}.observes('value')
},
{
title: 'DG.Inspector.graphMovableLine',
value: this_.get('isMovableLineVisible'),
classNames: 'dg-graph-movableLine-check'.w(),
valueDidChange: function () {
this_.toggleMovableLine();
}.observes('value')
},
{
title: 'DG.Inspector.graphLSRL',
value: this_.get('isLSRLVisible'),
classNames: 'dg-graph-lsrl-check'.w(),
valueDidChange: function () {
this_.toggleLSRLLine();
}.observes('value')
},
{
title: 'DG.Inspector.graphInterceptLocked',
classNames: 'dg-graph-interceptLocked-check'.w(),
_changeInProgress: true,
valueDidChange: function () {
if( !this._changeInProgress)
this_.toggleInterceptLocked();
}.observes('value'),
lineVisibilityChanged: function() {
this._changeInProgress = true;
var tLineIsVisible = this_.get('isMovableLineVisible') || this_.get('isLSRLVisible');
if( !tLineIsVisible)
this_.set('isInterceptLocked', false);
this.set('value', this_.get('isInterceptLocked'));
this.set('isEnabled', tLineIsVisible);
this._changeInProgress = false;
},
init: function() {
sc_super();
this.lineVisibilityChanged();
this_.addObserver('isMovableLineVisible', this, 'lineVisibilityChanged');
this_.addObserver('isLSRLVisible', this, 'lineVisibilityChanged');
this._changeInProgress = false;
},
destroy: function() {
this_.removeObserver('isMovableLineVisible', this, 'lineVisibilityChanged');
this_.removeObserver('isLSRLVisible', this, 'lineVisibilityChanged');
sc_super();
}
},
{
title: 'DG.Inspector.graphPlottedFunction',
value: this_.isAdornmentVisible('plottedFunction'),
classNames: 'dg-graph-plottedFunction-check'.w(),
valueDidChange: function () {
this_.togglePlotFunction();
}.observes('value')
},
{
title: 'DG.Inspector.graphPlottedValue',
value: this_.isAdornmentVisible('plottedValue'),
classNames: 'dg-graph-plottedValue-check'.w(),
valueDidChange: function () {
this_.togglePlotValue();
}.observes('value')
},
{
title: 'DG.Inspector.graphSquares',
value: this_.get('areSquaresVisible'),
classNames: 'dg-graph-squares-check'.w(),
lineVisibilityChanged: function() {
var tLineIsVisible = this_.get('isMovableLineVisible') || this_.get('isLSRLVisible');
this.set('isEnabled', tLineIsVisible);
if( this_.get('areSquaresVisible') && !tLineIsVisible)
this.set('value', false);
},
init: function() {
sc_super();
this.lineVisibilityChanged();
this_.addObserver('isMovableLineVisible', this, 'lineVisibilityChanged');
this_.addObserver('isLSRLVisible', this, 'lineVisibilityChanged');
},
destroy: function() {
this_.removeObserver('isMovableLineVisible', this, 'lineVisibilityChanged');
this_.removeObserver('isLSRLVisible', this, 'lineVisibilityChanged');
},
valueDidChange: function () {
this_.toggleShowSquares();
}.observes('value')
}
]);
}.property(),
/**
* When making a copy of a plot (e.g. for use in split) the returned object
* holds those properties that should be assigned to the copy.
* @return {{}}
*/
getPropsForCopy: function() {
var tResult = sc_super();
return $.extend( tResult, {
areSquaresVisible: this.get('areSquaresVisible')
});
},
/**
* @return { Object } with properties specific to a given subclass
*/
createStorage: function () {
var tStorage = sc_super(),
tMovablePoint = this.get('movablePoint'),
tMovableLine = this.get('movableLine'),
tLSRL = this.get('multipleLSRLs');
if (!SC.none(tMovablePoint))
tStorage.movablePointStorage = tMovablePoint.createStorage();
if (!SC.none(tMovableLine))
tStorage.movableLineStorage = tMovableLine.createStorage();
if (!SC.none(tLSRL) && tLSRL.get('isVisible'))
tStorage.multipleLSRLsStorage = tLSRL.createStorage();
if (this.get('areSquaresVisible'))
tStorage.areSquaresVisible = true;
if (this.get('isLSRLVisible'))
tStorage.isLSRLVisible = true;
return tStorage;
},
/**
* @param { Object } with properties specific to a given subclass
*/
restoreStorage: function (iStorage) {
/* Older documents stored adornments individually in the plot model
* that used them, e.g. movable lines and function plots were stored
* here with the scatter plot model. In newer documents, there is an
* 'adornments' property in the base class (plot model) which stores
* all or most of the adornments. To preserve file format compatibility
* we move the locally stored storage objects into the base class
* 'adornments' property where the base class will process them when
* we call sc_super().
*/
this.moveAdornmentStorage(iStorage, 'movableLine', iStorage.movableLineStorage);
this.moveAdornmentStorage(iStorage, 'multipleLSRLs', iStorage.multipleLSRLsStorage);
this.moveAdornmentStorage(iStorage, 'plottedFunction', iStorage.plottedFunctionStorage);
sc_super();
if (iStorage.movablePointStorage) {
if (SC.none(this.movablePoint))
this.createMovablePoint();
this.get('movablePoint').restoreStorage(iStorage.movablePointStorage);
}
if (iStorage.movableLineStorage) {
if (SC.none(this.movableLine))
this.createMovableLine();
this.get('movableLine').restoreStorage(iStorage.movableLineStorage);
}
this.areSquaresVisible = iStorage.areSquaresVisible;
if (iStorage.multipleLSRLsStorage) {
if (SC.none(this.multipleLSRLs))
this.createLSRLLines();
this.get('multipleLSRLs').restoreStorage(iStorage.multipleLSRLsStorage);
}
// Legacy document support
if (iStorage.plottedFunctionStorage) {
if (SC.none(this.plottedFunction))
this.set('plottedFunction', DG.PlottedFunctionModel.create());
this.get('plottedFunction').restoreStorage(iStorage.plottedFunctionStorage);
}
},
onRescaleIsComplete: function () {
if (!SC.none(this.movableLine))
this.movableLine.recomputeSlopeAndInterceptIfNeeded(this.get('xAxis'), this.get('yAxis'));
if (!SC.none(this.movablePoint))
this.movablePoint.recomputePositionIfNeeded(this.get('xAxis'), this.get('yAxis'));
},
/**
* Get an array of non-missing case counts in each axis cell.
* Also cell index on primary and secondary axis, with primary axis as major axis.
* @return {Array} [{count, primaryCell, secondaryCell},...] (all values are integers 0+).
*/
getCellCaseCounts: function ( iForSelectionOnly) {
var tCases = iForSelectionOnly ? this.get('selection') : this.get('cases'),
tXVarID = this.get('xVarID'),
tYVarID = this.get('yVarID'),
tCount = 0,
tValueArray = [];
if (!( tXVarID && tYVarID )) {
return tValueArray; // too early to recompute, caller must try again later.
}
// compute count and percent cases in each cell, excluding missing values
tCases.forEach(function (iCase, iIndex) {
var tXVal = iCase.getForcedNumericValue(tXVarID),
tYVal = iCase.getForcedNumericValue(tYVarID);
if (isFinite(tXVal) && isFinite(tYVal)) ++tCount;
});
// initialize the values for the single 'cell' of the scatterplot
var tCell = { primaryCell: 0, secondaryCell: 0 };
if( iForSelectionOnly)
tCell.selectedCount = tCount;
else
tCell.count = tCount;
tValueArray.push(tCell);
return tValueArray;
}
});
| concord-consortium/codap | apps/dg/components/graph/plots/scatter_plot_model.js | JavaScript | mit | 31,775 |
const Koa = require('koa')
const screenshot = require('./screenshot')
const app = new Koa()
app.use(async ctx => {
var url = ctx.query.url
console.log('goto:', url)
if (!/^https?:\/\/.+/.test(url)) {
ctx.body = 'url 不合法'
} else {
if (!isNaN(ctx.query.wait)) {
ctx.query.wait = ~~ctx.query.wait
}
let data = await screenshot(url, ctx.query.wait, ~~ctx.query.width)
if (ctx.query.base64) {
ctx.body = 'data:image/jpeg;base64,' + data
} else {
ctx.body = `<img src="data:image/jpeg;base64,${data}" />`
}
}
})
app.listen(8000)
console.log('server start success at 8000')
// process.on('unCaughtException', function (err) {
// console.log(err)
// })
| lwdgit/chrome-automator | examples/screenshot/index.js | JavaScript | mit | 710 |
// Test get machiens
var fs = require('fs');
try {
fs.accessSync('testdb.json', fs.F_OK);
fs.unlinkSync('testdb.json');
// Do something
} catch (e) {
// It isn't accessible
console.log(e);
}
var server = require('../server.js').createServer(8000, 'testdb.json');
var addTestMachine = function(name) {
var newMachine = {};
newMachine.name = name;
newMachine.type = 'washer';
newMachine.queue = [];
newMachine.operational = true;
newMachine.problemMessage = "";
newMachine.activeJob = {};
server.db('machines').push(newMachine);
}
describe('ALL THE TESTS LOL', function() {
it('should add a machine', function(done) {
var options = {
method: 'POST',
url: '/machines',
payload: {
name: 'test1',
type: 'washer'
}
}
server.inject(options, function(response) {
expect(response.statusCode).toBe(200);
var p = JSON.parse(response.payload);
expect(p.name).toBe(options.payload.name);
expect(p.type).toBe(options.payload.type);
done();
})
});
it('should get all machines', function(done) {
var name = 'testMachine';
var name2 = 'anotherMachine';
addTestMachine(name);
addTestMachine(name2);
var options = {
method: 'GET',
url: '/machines',
}
server.inject(options, function(res) {
expect(res.statusCode).toBe(200);
var p = JSON.parse(res.payload);
// check p has test and anotherMachine
done();
});
});
it('should get one machine', function(done) {
var name = 'sweetTestMachine';
addTestMachine(name);
var options = {
method: 'GET',
url: '/machines/'+name
};
server.inject(options, function(res) {
expect(res.statusCode).toBe(200);
var p = JSON.parse(res.payload);
expect(p.name).toBe(name);
done();
});
});
it('should add a job the queue then th queue should have the person', function(done) {
addTestMachine('queueTest');
var addOptions = {
method: 'POST',
url: '/machines/queueTest/queue',
payload: {
user: '[email protected]',
pin: 1234,
minutes: 50
}
};
server.inject(addOptions, function(res) {
expect(res.statusCode).toBe(200);
var p = JSON.parse(res.payload);
expect(p.name).toBe('queueTest');
var getQueue = {
method: 'GET',
url: '/machines/queueTest/queue'
};
server.inject(getQueue, function(newRes) {
expect(newRes.statusCode).toBe(200);
var q = JSON.parse(newRes.payload);
console.log(q);
expect(q.queue[0].user).toBe('[email protected]');
expect(q.queue[0].pin).toBe(1234);
done();
})
})
});
it('should delete a job from the queue', function(done) {
addTestMachine('anotherQueue');
var addOptions = {
method: 'POST',
url: '/machines/anotherQueue/queue',
payload: {
user: '[email protected]',
pin: 1235,
minutes: 50
}
};
server.inject(addOptions, function(res) {
var deleteOptions = addOptions;
deleteOptions.url = '/machines/anotherQueue/queue/delete';
deleteOptions.payload = {
user: addOptions.payload.user,
pin: addOptions.payload.pin
}
server.inject(deleteOptions, function(r) {
expect(r.statusCode).toBe(200);
console.log(JSON.parse(r.payload));
done();
})
})
})
it('should add a job to the active queue', function(done) {
addTestMachine('activeQueue');
var addOptions = {
method: 'POST',
url: '/machines/activeQueue/queue',
payload: {
user: '[email protected]',
pin: 1235,
minutes: 50
}
};
server.inject(addOptions, function(r) {
var runJobOptions = {
method: 'POST',
url: '/machines/activeQueue/queue/start',
payload: {
command: 'next',
pin: 1235,
minutes: 0
}
};
server.inject(runJobOptions, function(res) {
expect(res.statusCode).toBe(200);
done();
})
})
});
}); | sdierauf/laundrytime | spec/getMachinesSpec.js | JavaScript | mit | 4,145 |
require "administrate/field/base"
class EnumField < Administrate::Field::Base
def to_s
data
end
end
| MontrealNewTech/website | app/fields/enum_field.rb | Ruby | mit | 109 |
require('./loader.jsx');
| arjunmehta/react-frontend-template | src/index.js | JavaScript | mit | 25 |
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Public Class PaintToolBar
'¦¹Ãþ§O©w¸qÃö©ó¤u¨ã¦C¥~Æ[¤Î¦æ¬°
Inherits PaintWithRegistry
Protected ToolBarCommand As Integer = 7 '¨Ï¥ÎªÌ¤u¨ã¦C©R¥O¿ï¾Ü
Protected LastCommand As Integer '¤W¤@Ó©R¥O
Protected pnToolbar As Panel '¤u¨ã¦C
Protected radbtnToolbar(15) As NoFocusRadbtn '¤u¨ã¦C¥\¯à
Sub New()
'¤u¨ã¦C«Øºc¤¸
Dim tx, coly, sy As Integer
If bToolbar Then tx = 60 Else tx = 0
If bColorbar Then coly = 50 Else coly = 0
If bStatusbar Then sy = 22 Else sy = 0
pnToolbar = New Panel
With pnToolbar
.Parent = Me
.BorderStyle = BorderStyle.None
.Location = New Point(0, 0)
.Size = New Size(60, ClientSize.Height - coly - sy)
End With
Dim TotTool As New ToolTip
Dim strTotTool() As String = {"¿ï¾Ü¥ô·N½d³ò", "¿ï¾Ü", "¾ó¥ÖÀ¿/±m¦â¾ó¥ÖÀ¿", "¶ñ¤J¦â±m", _
"¬D¿ïÃC¦â", "©ñ¤jÃè", "¹]µ§", "¯»¨ê", "¼Qºj", "¤å¦r", _
"ª½½u", "¦±½u", "¯x§Î", "¦hÃä§Î", "¾ò¶ê§Î", "¶ê¨¤¯x§Î"}
Dim i, cx As Integer
For i = 0 To 15
radbtnToolbar(i) = New NoFocusRadbtn
With radbtnToolbar(i)
.Name = (i + 1).ToString
.Parent = pnToolbar
.Appearance = Appearance.Button
.Size = New Size(26, 26)
.Image = New Bitmap(Me.GetType(), "toolbutton" & (i + 1).ToString & ".bmp")
If (i + 1) Mod 2 <> 0 Then cx = 3 Else cx = 29
.Location = New Point(cx, (i \ 2) * 26)
End With
TotTool.SetToolTip(radbtnToolbar(i), strTotTool(i))
AddHandler radbtnToolbar(i).MouseEnter, AddressOf ToolbarHelp
AddHandler radbtnToolbar(i).MouseLeave, AddressOf ToolbarHelpLeave
AddHandler radbtnToolbar(i).Click, AddressOf ToolbarRadbtnSelect
Next i
radbtnToolbar(6).Checked = True
pnWorkarea.Cursor = New Cursor(Me.GetType(), "Pen.cur")
End Sub
Protected Overrides Sub FormSizeChanged(ByVal obj As Object, ByVal ea As EventArgs)
'©w¸q¦]µøÄ±¤¸¥óÅܧó(¤u¨ã¦C,¦â¶ô°Ï)¤u¨ã¦C®y¼Ð°t¸m
MyBase.FormSizeChanged(obj, ea)
Dim tx, cy, sy As Integer
If bColorbar Then cy = 50 Else cy = 0
If bStatusbar Then sy = 22 Else sy = 0
pnToolbar.Size = New Size(60, ClientSize.Height - cy - sy)
End Sub
Protected Overridable Sub ToolbarHelp(ByVal obj As Object, ByVal ea As EventArgs)
'·í·Æ¹«²¾¦Ü¤u¨ã¦C¤¸¥ó¤W®É,Åã¥Ü¸Ó¤¸¥ó¦bª¬ºA¦Cªº¸ê°T.¥Ñ PaintStatusbar Âмg
End Sub
Protected Overridable Sub ToolbarHelpLeave(ByVal obj As Object, ByVal ea As EventArgs)
'·í·Æ¹«²¾¥X¤u¨ã¦C¤¸¥ó®É,Åã¥Ü¸Ó¤¸¥ó¦bª¬ºA¦Cªº¸ê°T.¥Ñ PaintStatusbar Âмg
End Sub
Protected Overridable Sub ToolbarRadbtnSelect(ByVal obj As Object, ByVal ea As EventArgs)
'©w¸q·í¨Ï¥ÎªÌ¿ï¾Ü¤u¨ã¦C¤¸¥ó®É,©Ò²£¥Íªº¦æ¬°
Dim radbtnSelect As NoFocusRadbtn = DirectCast(obj, NoFocusRadbtn)
LastCommand = ToolBarCommand '¨ú±o¤W¤@Ó¥\¯à
ToolBarCommand = CInt(radbtnSelect.Name) '¨ú±o¨Ï¥ÎªÌ©Ò¿ï¾Üªº¥\¯à
Dim CursorName As String
Select Case ToolBarCommand
Case 1, 2, 10, 11, 12, 13, 14, 15, 16
CursorName = "Cross.cur"
Case 3
CursorName = "Null.cur"
Case 4
CursorName = "FillColor.cur"
Case 5
CursorName = "Color.cur"
Case 6
CursorName = "ZoomSet.cur"
Case 7
CursorName = "Pen.cur"
Case 8
CursorName = "Brush.cur"
Case 9
CursorName = "Spray.cur"
End Select
pnWorkarea.Cursor = New Cursor(Me.GetType(), CursorName)
'³o¨ì¥Ø«e¬°¤î,¶È©w¸q¤F,¹ïÀ³©óø¹Ï¤u§@°Ïªº¹C¼ÐÅã¥Ü,¥Dnªº±±¨î¬yµ{,¥Ñ OverridesÂмg
End Sub
End Class
| neville1/MSPaint | MsPaint Sub/PaintToolbar.vb | Visual Basic | mit | 4,078 |
Vous êtes invité par {{ $user->name }} à rejoindre le projet {{$kanban->title}} sur <a href="google.com">kaban.com</a> | Smart-Pix/Kanban | resources/views/emails/subscribe.blade.php | PHP | mit | 121 |
---
title: 代码构建
taxonomy:
category: docs
---
代码构建获取源码、编译、打包,最终生成docker镜像。
代码构建之前需要做好如下准备工作:
1. 代码已经托管在“代码托管平台”(目前平台支持github、bitbucket)
2. 源代码中包含项目对应的[Dockerfile](../dockerfile)。
## 创建构建 ##
1. 打开“代码构建“子页面
2. 点击“创建构建”
3. 选择代码源(github、bitbucket等),点击“获取代码列表”
4. 假定选定的bitbucket,此时可能会跳出bitbucket的登录页面,登陆之后会跳出如下页面。点击Grant access

5. 此时已经跳转回naturecloud的构建页面,同时会出现bitbucket中的项目列表,选中其中一个项目,跳出一个对话框,输入构建信息即可。
## 构建历史及详情 ##
在“代码构建”页面,点击某个构建,即可查看构建历史。在构建历史页面中,选择其中一次构建,即可查看该次构建的结果输出。
| naturecloud/docs | pages/02.img/02.imgBuild/01.sourceBuild/docs.md | Markdown | mit | 1,037 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>sudoku: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.1 / sudoku - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
sudoku
<small>
8.8.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-02-09 07:07:27 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-09 07:07:27 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.11.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.11.2 Official release 4.11.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/sudoku"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Sudoku"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [ "keyword: sudoku" "keyword: puzzles" "keyword: Davis-Putnam" "category: Miscellaneous/Logical Puzzles and Entertainment" "date: 2006-02" ]
authors: [ "Laurent Théry <[email protected]> [http://www-sop.inria.fr/lemme/personnel/Laurent.Thery/me.html]" ]
bug-reports: "https://github.com/coq-contribs/sudoku/issues"
dev-repo: "git+https://github.com/coq-contribs/sudoku.git"
synopsis: "A certified Sudoku solver"
description: """
ftp://ftp-sop.inria.fr/lemme/Laurent.Thery/Sudoku.zip
A formalisation of Sudoku in Coq. It implements a naive
Davis-Putnam procedure to solve sudokus."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/sudoku/archive/v8.8.0.tar.gz"
checksum: "md5=1eb2565d4b3bc20e7e1a5a58e7aa5377"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-sudoku.8.8.0 coq.8.11.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1).
The following dependencies couldn't be met:
- coq-sudoku -> coq < 8.9~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-sudoku.8.8.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.11.2-2.0.7/released/8.11.1/sudoku/8.8.0.html | HTML | mit | 6,861 |
from __future__ import absolute_import
from .base import WhiteNoise
__version__ = '2.0.3'
__all__ = ['WhiteNoise']
| KnockSoftware/whitenoise | whitenoise/__init__.py | Python | mit | 118 |
game.PlayerEntity = me.Entity.extend ({ //builds the player class
init: function(x, y, settings){
this.setSuper(x, y);
this.setPlayerTimer();
this.setAttributes();
this.type="PlayerEntity";
this.setFlags();
me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); //locks camera on the character
this.addAnimation();
this.renderable.setCurrentAnimation("idle"); //sets the idle animation
},
setSuper: function(x, y){
this._super(me.Entity, 'init', [x, y, {//._super reaches to the object entity
image: "player",//uses the image player
width: 64, //preserves the height and width for player
height: 64,
spritewidth: "64", //uses height and width for player
spriteheight: "64",
getShape: function(){
return(new me.Rect(0, 0, 64, 64)) . toPolygon(); //creates a little rectangle for what the player can walk into.
}
}]);
},
setPlayerTimer: function(){
this.now = new Date().getTime(); //keeps track of what time it is
this.lastHit = this.now; //same as this.now
this.lastSpear = this.now;
this.lastAttack = new Date().getTime();
},
setAttributes: function(){
this.health = game.data.playerHealth;
this.body.setVelocity(game.data.playerMoveSpeed, 20); //sets velocity to 5
this.attack = game.data.playerAttack;
},
setFlags: function(){
this.facing = "right"; //makes the character face right
this.dead = false;
this.attacking = false;
},
addAnimation: function(){
this.renderable.addAnimation("idle", [78]); //idle animation
this.renderable.addAnimation("walk", [143, 144, 145, 146, 147, 148, 149, 150, 151], 80); //walking animation
this.renderable.addAnimation("attack", [195, 196, 197, 198, 199, 200], 80); //setting the attack animation
},
update: function(delta){
this.now = new Date().getTime(); //everytime we call update it updates the time
this.dead = this.checkIfDead();
this.checkKeyPressesAndMove();
this.checkAbilityKeys();
this.setAnimation();
me.collision.check(this, true, this.collideHandler.bind(this), true);
this.body.update(delta); //delta is the change in time
this._super(me.Entity, "update", [delta]);
return true;
},
checkIfDead: function(){
if (this.health <= 0){
return true;
}
},
checkKeyPressesAndMove: function(){
if(me.input.isKeyPressed("right")){ //checks to see if the right key is pressed
this.moveRight();
}
else if(me.input.isKeyPressed("left")){ //allows the player to move left
this.moveLeft();
}
else{
this.body.vel.x = 0; //stops the movement
}
if(me.input.isKeyPressed("jump") && !this.jumping && !this.falling){ //allows the player to jump without double jumping or falling and jumping
this.jump();
}
this.attacking = me.input.isKeyPressed("attack"); //attack key
},
moveRight: function(){
this.body.vel.x += this.body.accel.x * me.timer.tick; //adds the velocity to the set velocity and mutiplies by the me.timer.tick and makes the movement smooth
this.facing = "right"; //sets the character to face right
this.flipX(false);
},
moveLeft: function(){
this.body.vel.x -= this.body.accel.x * me.timer.tick;
this.facing = "left";
this.flipX(true);
},
jump: function(){
this.body.jumping = true;
this.body.vel.y -= this.body.accel.y * me.timer.tick;
},
checkAbilityKeys: function(){
if(me.input.isKeyPressed("skill1")){
// this.speedBurst();
}else if(me.input.isKeyPressed("skill2")){
// this.eatCreep();
}else if(me.input.isKeyPressed("skill3")){
this.throwSpear();
}
},
throwSpear: function(){
if(this.now-this.lastSpear >= game.data.spearTimer*100 && game.data.ability3 > 0){
this.lastSpear = this.now;
var spear = me.pool.pull("spear", this.pos.x, this.pos.y, {}, this.facing);
me.game.world.addChild(spear, 10);
}
},
setAnimation: function(){
if(this.attacking){
if(!this.renderable.isCurrentAnimation("attack")){
this.renderable.setCurrentAnimation("attack", "idle");
this.renderable.setAnimationFrame();
}
}
else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){ //changes the animation from attack to walking
if (!this.renderable.isCurrentAnimation("walk")) { //sets the current animation for walk
this.renderable.setCurrentAnimation("walk");
};
}
else if(!this.renderable.isCurrentAnimation("attack")){ //changes the animation from attack to idle
this.renderable.setCurrentAnimation("idle"); //if the player is not walking it uses idle animation
}
},
loseHealth: function(damage){
this.health = this.health - damage;
},
collideHandler: function(response){
if(response.b.type==='EnemyBaseEntity'){ //sees if the enemy base entitiy is near a player entity and if so it is solid from left and right and top
this.collideWithEnemyBase(response);
}
else if(response.b.type==='EnemyCreep'){
this.collideWithEnemyCreep(response);
}
},
collideWithEnemyBase: function(response){
var ydif = this.pos.y - response.b.pos.y;
var xdif = this.pos.x - response.b.pos.x;
if(ydif<-40 && xdif<70 && xdif>-35){
this.body.falling=false;
this.body.vel.y = -1;
}
if(xdif>-35 && this.facing==='right' && (xdif<0)){
this.body.vel.x = 0;
//this.pos.x = this.pos.x -1;
}
else if(xdif<70 && this.facing==='left' && (xdif>0)){
this.body.vel.x=0;
//this.pos.x = this.pos.x +1;
}
if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){ //if the animation is attack it will lose the base health and that it will check when the lasthit was
this.lastHit = this.now;
response.b.loseHealth(game.data.playerAttack);
}
},
collideWithEnemyCreep: function(response){
var xdif = this.pos.x - response.b.pos.x;
var ydif = this.pos.y - response.b.pos.y;
this.stopMovement(xdif);
if(this.checkAttack(xdif, ydif)){
this.hitCreep(response);
};
},
stopMovement: function(xdif){
if(xdif > 0){
//this.pos.x = this.pos.x + 1;
if (this.facing === "left"){
this.body.vel.x = 0;
}
}
else{
//this.pos.x = this.pos.x - 1;
if(this.facing === "right"){
this.body.vel.x = 0;
}
}
},
checkAttack: function(xdif, ydif){
if(this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= game.data.playerAttackTimer
&& (Math.abs(ydif) <=40) &&
((xdif>0) && this.facing==="left") || (((xdif<0) && this.facing === "right"))){
this.lastHit = this.now;
return true;
}
return false;
},
hitCreep: function(response){
if(response.b.health <= game.data.playerAttack){
game.data.gold += 1;
}
response.b.loseHealth(game.data.playerAttack);
}
});
//intermeidiae challenge creating an ally creep
game.MyCreep = me.Entity.extend({
init: function(x, y, settings){
this._super(me.Entity, 'init', [x, y, {
image: "creep2",
width: 100,
height:85,
spritewidth: "100",
spriteheight: "85",
getShape: function(){
return (new me.Rect(0, 0, 52, 100)).toPolygon();
}
}]);
this.health = game.data.allyCreepHealth;
this.alwaysUpdate = true;
// //this.attacking lets us know if the enemy is currently attacking
this.attacking = false;
// //keeps track of when our creep last attacked anyting
this.lastAttacking = new Date().getTime();
this.lastHit = new Date().getTime();
this.now = new Date().getTime();
this.body.setVelocity(game.data.allyCreepMoveSpeed, 20);
this.type = "MyCreep";
this.renderable.addAnimation("walk", [0, 1, 2, 3, 4], 80);
this.renderable.setCurrentAnimation("walk");
},
update: function(delta) {
// this.now = new Date().getTime();
this.body.vel.x += this.body.accel.x * me.timer.tick;
this.flipX(true);
me.collision.check(this, true, this.collideHandler.bind(this), true);
this.body.update(delta);
this._super(me.Entity, "update", [delta]);
return true;
},
collideHandler: function(response) {
if(response.b.type==='EnemyBaseEntity'){
this.attacking = true;
//this.lastAttacking = this.now;
this.body.vel.x = 0;
this.pos.x = this.pos.x +1;
//checks that it has been at least 1 second since this creep hit a base
if((this.now-this.lastHit <= game.data.allyCreepAttackTimer)){
//updates the last hit timer
this.lastHit = this.now;
//makes the player base call its loseHealth function and passes it a damage of 1
response.b.loseHealth(1);
}
}
}
});
| romulus1/FinalAwesomauts | js/entities/entities.js | JavaScript | mit | 8,421 |
<!DOCTYPE html>
<html xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-16" http-equiv="Content-Type" />
<title _locid="PortabilityAnalysis0">.NET Portability Report</title>
<style>
/* Body style, for the entire document */
body {
background: #F3F3F4;
color: #1E1E1F;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 0;
margin: 0;
}
/* Header1 style, used for the main title */
h1 {
padding: 10px 0px 10px 10px;
font-size: 21pt;
background-color: #E2E2E2;
border-bottom: 1px #C1C1C2 solid;
color: #201F20;
margin: 0;
font-weight: normal;
}
/* Header2 style, used for "Overview" and other sections */
h2 {
font-size: 18pt;
font-weight: normal;
padding: 15px 0 5px 0;
margin: 0;
}
/* Header3 style, used for sub-sections, such as project name */
h3 {
font-weight: normal;
font-size: 15pt;
margin: 0;
padding: 15px 0 5px 0;
background-color: transparent;
}
h4 {
font-weight: normal;
font-size: 12pt;
margin: 0;
padding: 0 0 0 0;
background-color: transparent;
}
/* Color all hyperlinks one color */
a {
color: #1382CE;
}
/* Paragraph text (for longer informational messages) */
p {
font-size: 10pt;
}
/* Table styles */
table {
border-spacing: 0 0;
border-collapse: collapse;
font-size: 10pt;
}
table th {
background: #E7E7E8;
text-align: left;
text-decoration: none;
font-weight: normal;
padding: 3px 6px 3px 6px;
}
table td {
vertical-align: top;
padding: 3px 6px 5px 5px;
margin: 0px;
border: 1px solid #E7E7E8;
background: #F7F7F8;
}
.NoBreakingChanges {
color: darkgreen;
font-weight:bold;
}
.FewBreakingChanges {
color: orange;
font-weight:bold;
}
.ManyBreakingChanges {
color: red;
font-weight:bold;
}
.BreakDetails {
margin-left: 30px;
}
.CompatMessage {
font-style: italic;
font-size: 10pt;
}
.GoodMessage {
color: darkgreen;
}
/* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */
.localLink {
color: #1E1E1F;
background: #EEEEED;
text-decoration: none;
}
.localLink:hover {
color: #1382CE;
background: #FFFF99;
text-decoration: none;
}
/* Center text, used in the over views cells that contain message level counts */
.textCentered {
text-align: center;
}
/* The message cells in message tables should take up all avaliable space */
.messageCell {
width: 100%;
}
/* Padding around the content after the h1 */
#content {
padding: 0px 12px 12px 12px;
}
/* The overview table expands to width, with a max width of 97% */
#overview table {
width: auto;
max-width: 75%;
}
/* The messages tables are always 97% width */
#messages table {
width: 97%;
}
/* All Icons */
.IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded {
min-width: 18px;
min-height: 18px;
background-repeat: no-repeat;
background-position: center;
}
/* Success icon encoded */
.IconSuccessEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==);
}
/* Information icon encoded */
.IconInfoEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=);
}
/* Warning icon encoded */
.IconWarningEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==);
}
/* Error icon encoded */
.IconErrorEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=);
}
</style>
</head>
<body>
<h1 _locid="PortabilityReport">.NET Portability Report</h1>
<div id="content">
<div id="submissionId" style="font-size:8pt;">
<p>
<i>
Submission Id
5da409e4-45ba-4997-854f-9f90b5611b95
</i>
</p>
</div>
<h2 _locid="SummaryTitle">
<a name="Portability Summary"></a>Portability Summary
</h2>
<div id="summary">
<table>
<tbody>
<tr>
<th>Assembly</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
</tr>
<tr>
<td><strong><a href="#IKVM.OpenJDK.Beans">IKVM.OpenJDK.Beans</a></strong></td>
<td class="text-center">99.46 %</td>
<td class="text-center">99.35 %</td>
<td class="text-center">100.00 %</td>
<td class="text-center">99.35 %</td>
</tr>
</tbody>
</table>
</div>
<div id="details">
<a name="IKVM.OpenJDK.Beans"><h3>IKVM.OpenJDK.Beans</h3></a>
<table>
<tbody>
<tr>
<th>Target type</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
<th>Recommended changes</th>
</tr>
<tr>
<td>System.Diagnostics.DebuggableAttribute</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">#ctor(System.Boolean,System.Boolean)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Runtime.Serialization.ISerializable</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Runtime.Serialization.SerializationInfo</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Remove serialization constructors on custom Exception types</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Threading.Thread</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use System.Threading.Interlocked.MemoryBarrier instead</td>
</tr>
<tr>
<td style="padding-left:2em">MemoryBarrier</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use System.Threading.Interlocked.MemoryBarrier instead</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
<p>
<a href="#Portability Summary">Back to Summary</a>
</p>
</div>
</div>
</body>
</html> | kuhlenh/port-to-core | Reports/ne/netcdf-ikvm.4.1.0/IKVM.OpenJDK.Beans-Net40.html | HTML | mit | 15,187 |
//-*-c++-*-
/****************************************************************/
/**
** @file errors.h
** @brief Header file for CHILD error-handling routines.
**
** Created Dec. 97
** $Id: errors.h,v 1.11 2004-01-07 10:53:25 childcvs Exp $
*/
/****************************************************************/
#ifndef ERRORS_H
#define ERRORS_H
#include "../compiler.h"
void ReportFatalError( const char *errStr ) ATTRIBUTE_NORETURN;
void ReportWarning( const char *errstr );
#endif
| childmodel/child | src/errors/errors.h | C | mit | 492 |
package uk.gov.dvsa.ui.pages.vehicleinformation;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import uk.gov.dvsa.domain.model.vehicle.Make;
import uk.gov.dvsa.domain.navigation.PageNavigator;
import uk.gov.dvsa.framework.config.webdriver.MotAppDriver;
import uk.gov.dvsa.helper.FormDataHelper;
import uk.gov.dvsa.helper.PageInteractionHelper;
import uk.gov.dvsa.ui.pages.Page;
public class VehicleMakePage extends Page {
private static final String PAGE_TITLE = "What is the vehicle's make?";
public static final String PATH = "/create-vehicle/make";
@FindBy(id = "vehicleMake") private WebElement vehicleMakeDropdown;
@FindBy(className = "button") private WebElement continueButton;
public VehicleMakePage(MotAppDriver driver) {
super(driver);
selfVerify();
}
@Override
protected boolean selfVerify() {
return PageInteractionHelper.verifyTitle(this.getTitle(), PAGE_TITLE);
}
public VehicleMakePage selectMake(Make make){
FormDataHelper.selectFromDropDownByValue(vehicleMakeDropdown, make.getId().toString());
vehicleMakeDropdown.sendKeys(Keys.TAB);
return this;
}
public VehicleModelPage continueToVehicleModelPage() {
continueButton.click();
return new VehicleModelPage(driver);
}
public VehicleModelPage updateVehicleMake(Make make) {
FormDataHelper.selectFromDropDownByValue(vehicleMakeDropdown, make.getId().toString());
vehicleMakeDropdown.sendKeys(Keys.TAB);
return continueToVehicleModelPage();
}
}
| dvsa/mot | mot-selenium/src/main/java/uk/gov/dvsa/ui/pages/vehicleinformation/VehicleMakePage.java | Java | mit | 1,635 |
# New Format site for Reiker Seiffe
### A simple resume site build off of SCSS, running on a Node.JS server with express and twig. | Reikerseiffe/Website-New-Format | README.md | Markdown | mit | 131 |
<?php
namespace Tecnokey\ShopBundle\Controller\Frontend\User;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Tecnokey\ShopBundle\Entity\Shop\Order;
use Tecnokey\ShopBundle\Form\Shop\OrderType;
/**
* Shop\Order controller.
*
* @Route("/tienda/usuario/pedidos")
*/
class OrderController extends Controller
{
/**
* Lists all Shop\Order entities.
*
* @Route("/", name="TKShopFrontendOrderIndex")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getEntityManager();
$entities = $em->getRepository('TecnokeyShopBundle:Shop\Order')->findAll();
return array('entities' => $entities);
}
/**
*
*
* @Route("/realizados", name="TKShopFrontendOrdersShowDelivered")
* @Template()
*/
public function showDeliveredAction()
{
$orderBy = $this->get('view.sort');
$orderBy->add('pedido', 'publicId', 'pedido')
->add('fecha', 'created_at', 'Fecha')
->add('cantidad', 'quantity', 'Cantidad')
->add('importe', 'totalPrice', 'Importe')
->add('estado', 'status', 'Estado')
->initialize();
$em = $this->getDoctrine()->getEntityManager();
$user = $this->get('userManager')->getCurrentUser();
$entities = $em->getRepository('TecnokeyShopBundle:Shop\\User')->findDeliveredOrders($user, $orderBy->getValues());
return array(
'entities' => $entities,
'orderBy' => $orderBy->switchMode(),
);
}
/**
*
*
* @Route("/en_proceso", name="TKShopFrontendOrdersShowInProcess")
* @Template()
*/
public function showInProcessAction()
{
$orderBy = $this->get('view.sort');
$orderBy->add('pedido', 'publicId', 'pedido')
->add('fecha', 'createdAt', 'Fecha')
->add('cantidad', 'quantity', 'Cantidad')
->add('importe', 'totalPrice', 'Importe')
->add('estado', 'status', 'Estado')
->initialize();
$em = $this->getDoctrine()->getEntityManager();
$user = $this->get('userManager')->getCurrentUser();
$entities = $em->getRepository('TecnokeyShopBundle:Shop\\User')->findInProcessOrders($user, $orderBy->getValues());
return array(
'entities' => $entities,
'orderBy' => $orderBy->switchMode(),
);
}
/**
* Finds and displays a Shop\Order entity.
*
* @Route("/{publicId}/show", name="TKShopFrontendOrderShow")
* @Template()
*/
public function showAction($publicId)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('TecnokeyShopBundle:Shop\Order')->findByPublicId($publicId);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Shop\Order entity.');
}
return array(
'order' => $entity,
);
}
/**
* Finds and displays a Shop\Order entity.
*
* @Route("/confirmar", name="TKShopFrontendOrderCreateFromShoppingCart")
* @Template()
*/
public function createFromShoppingCartAction()
{
$confirmed = $this->confirmOrder();
if ($confirmed == true) {
return $this->redirect($this->generateUrl('TKShopFrontendOrdersShowInProcess'));
}
else{
return $this->redirect($this->generateUrl('TKShopFrontendUserShoppingCartEdit'));
}
}
// HELPER FUNCTIONS //
/**
* Redirects to home page if there is a problem with Oder
*
* @param type $msg
* @param type $redirect
* @return type
*/
protected function orderErrorHandler($msg = NULL, $redirect=NULL){
//TODO: Redirect to index
$this->get('session')->setFlash('order_error',"Atencion: El usuario no puede tener pedidos, cree un usuario de tipo cliente");
return $this->redirect($this->generateUrl("TKShopFrontendIndex"));
}
/**
* Get the Order from the logged user
*
* @return Order
*/
protected function getOrderFromCurrentUser(){
$user = $this->get('userManager')->getCurrentUser();
$shoppingCart = NULL;
if($this->get('userManager')->isDBUser($user)){
return $user->getOrders();
}
else{
return NULL;
}
}
/**
*
* @param ShoppingCart $shoppingCart
* @return boolean
*/
public function confirmOrder() {
$sc = $this->getUserShoppingCart();
$items = $sc->getItems();
if (count($items) < 1) {
return false;
}
try {
$checkoutManager = $this->get('checkoutManager');
$sc = $checkoutManager->checkout($sc);
// generate an order
$order = $checkoutManager->shoppingCartToOrder($sc);
$user = $this->get('userManager')->getCurrentUser();
$order->setUser($user);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($order);
$em->flush();
//End generating an order
// remove all cart items
$this->get('shoppingCartManager')->removeAllItems($sc);
$em->flush();
//End removing all cart items
return true;
} catch (Exception $e) {
return false;
}
}
/**
* Get the ShoppingCart from the logged user
* If the user does NOT have a shoppingCart then one is created and attached to user but not persisted to database
*
* @return ShoppingCart
*/
protected function getUserShoppingCart() {
$user = $this->get('userManager')->getCurrentUser();
$shoppingCart = NULL;
if ($this->get('userManager')->isDBUser($user)) {
$shoppingCart = $user->getShoppingCart();
if ($shoppingCart == NULL) {
$shoppingCart = new ShoppingCart();
$user->setShoppingCart($shoppingCart);
}
}
return $shoppingCart;
}
}
| mqmtech/Tecnokey | src/Tecnokey/ShopBundle/Controller/Frontend/User/OrderController.php | PHP | mit | 6,501 |
import {Component, ViewChild} from '@angular/core';
import { Platform, MenuController, NavController} from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { HomeComponent } from './pages/home-page/home.component';
import {CityListPage} from './pages/city-list/city-list';
import {ClausePage} from './pages/clause/clause';
@Component({
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('content') content: NavController;
// make HelloIonicPage the root (or first) page
rootPage: any = HomeComponent;
pages: Array<{title: string, component: any}>;
// stroage: Storage;
constructor(
private platform: Platform,
private menu: MenuController,
private splashScreen: SplashScreen
) {
this.initializeApp();
// set our app's pages
this.pages = [
{ title: '首页', component: HomeComponent },
{ title: '城市', component: CityListPage },
{ title: '许可条款', component: ClausePage }
];
}
initializeApp() {
this.platform.ready().then(() => {
this.splashScreen.hide();
});
}
ionViewDidLoad(){
}
openPage(page) {
// close the menu when clicking a link from the menu
this.menu.close();
// navigate to the new page if it is not the current page
this.content.setRoot(page.component);
}
}
| zhuzhiqiang/tianyingqing | src/app/app.component.ts | TypeScript | mit | 1,412 |
import { Log } from './log';
//import Url = require('./url');
import { Url } from './url';
import { HashString } from './lib';
/**
* Делаем HTTP (Ajax) запрос.
*
* @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().
* @see {@link https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings}
*/
export const Ajax = (opts: JQueryAjaxSettings) => {
// обязательно добавить в запрос тип возвращаемых данных
if (opts.dataType == 'json') {
if (opts.data == null) {
opts.data = { datatype: 'json' }
} else if (typeof opts.data === "string") { // opts.data - строка
let params: HashString = Url.SplitUrlParams(opts.data);
params['datatype'] = 'json';
opts.data = Url.JoinUrlParams(params);
} else { // opts.data - объект
opts.data.datatype = 'json';
}
}
if (opts.xhrFields == null || opts.xhrFields == undefined) {
opts.xhrFields = {
withCredentials: true
};
}
if (opts.error == null || typeof opts.error !== 'function') {
opts.error = function (jqXHR, textStatus, errorThrown) {
Log('error:', textStatus, errorThrown);
};
} else {
let original = opts.error;
opts.error = function (jqXHR, textStatus, errorThrown) {
// никаких call, apply надо сохранить контекст вызова иногда это важно
original(jqXHR, textStatus, errorThrown);
Log('Ajax.error()', textStatus, errorThrown);
};
}
return $.ajax(opts);
};
| 96467840/AspNetCore | src/AspNetCore/PublishOutput/wwwroot/lib/unobtrusive-typescript/dist/utils/ajax.ts | TypeScript | mit | 1,767 |
<div class="all_levels_area_of_interest @if($from == "account") account_listing_skills @endif">
@if(count($firstBox_areaOfInterest) > 0)
<div class="hierarchy_parent">
<select name="title" id="area_of_interest_firstbox" class="first_level hierarchy" size="5" data-number="1">
@foreach($firstBox_areaOfInterest as $area_of_interest_id=>$area_of_interest)
<option value="{{$area_of_interest_id}}" data-type="{{$area_of_interest['type']}}">{{$area_of_interest['name']}} ></option>
@endforeach
</select>
@if($from == "site_admin")
<div style="margin-left:10px;margin-top:5px;">
<a class="btn black-btn btn-xs add_category" data-pos="first" id="add_category_btn" style="padding:5px 10px 5px;
text-decoration:none;">
<i class="fa fa-plus plus"></i> <span class="plus_text" style="left:-5px;">ADD</span>
</a>
</div>
@endif
</div>
@endif
</div>
@if($from != "site_admin")
<div class="row">
<div class="col-xs-12">
<div class="text-center"><h5>You have selected:<span class="selected_text_area">None</span></h5></div>
</div>
</div>
@endif | javulorg/javul | resources/views/admin/partials/area_of_interest_browse.blade.php | PHP | mit | 1,334 |
# frozen_string_literal: true
describe ContactController, type: :controller do
include AuthHelper
let!(:ada) { create(:published_profile, email: "[email protected]", main_topic_en: 'math') }
describe 'create action' do
it 'when profile active' do
get :create, params: { id: ada.id, message: { name: "Maxi"} }
expect(response).to be_successful
expect(response.response_code).to eq(200)
end
it 'when profile inactive' do
ada.update!(inactive: true)
get :create, params: { id: ada.id, message: { name: "Maxi"} }
expect(response).not_to be_successful
expect(response.response_code).to eq(302)
expect(response).to redirect_to("/#{I18n.locale}/profiles")
end
it 'when unpublished profiles' do
ada.update!(published: false)
get :create, params: { id: ada.id, message: { name: "Maxi"} }
expect(response).not_to be_successful
expect(response.response_code).to eq(302)
expect(response).to redirect_to("/#{I18n.locale}/profiles")
end
end
end
| rubymonsters/speakerinnen_liste | spec/controllers/contact_controller_spec.rb | Ruby | mit | 1,042 |
<?php
namespace LCoder\Bundle\BlogBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('l_coder_blog');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| latviancoder/blog | src/LCoder/Bundle/BlogBundle/DependencyInjection/Configuration.php | PHP | mit | 885 |
// Copyright (c) 2011-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_MACNOTIFICATIONHANDLER_H
#define BITCOIN_QT_MACNOTIFICATIONHANDLER_H
#include <QObject>
/** Macintosh-specific notification handler (supports UserNotificationCenter).
*/
class MacNotificationHandler : public QObject
{
Q_OBJECT
public:
/** shows a macOS 10.8+ UserNotification in the UserNotificationCenter
*/
void showNotification(const QString &title, const QString &text);
/** check if OS can handle UserNotifications */
bool hasUserNotificationCenterSupport();
static MacNotificationHandler *instance();
};
#endif // BITCOIN_QT_MACNOTIFICATIONHANDLER_H
| thelazier/dash | src/qt/macnotificationhandler.h | C | mit | 806 |
package tsmt
import (
"encoding/xml"
"github.com/fgrid/iso20022"
)
type Document01800105 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsmt.018.001.05 Document"`
Message *FullPushThroughReportV05 `xml:"FullPushThrghRpt"`
}
func (d *Document01800105) AddMessage() *FullPushThroughReportV05 {
d.Message = new(FullPushThroughReportV05)
return d.Message
}
// Scope
// The FullPushThroughReport message is sent by the matching application to a party involved in a transaction.
// This message is used to pass on information that the matching application has received from the submitter. The forwarded information can originate from an InitialBaselineSubmission or BaselineReSubmission or BaselineAmendmentRequest message.
// Usage
// The FullPushThroughReport message can be sent by the matching application to a party to convey
// - the details of an InitialBaselineSubmission message that it has obtained,or
// - the details of a BaselineResubmission message that it has obtained,or
// - the details of a BaselineAmendmentRequest message that it has obtained.
type FullPushThroughReportV05 struct {
// Identifies the report.
ReportIdentification *iso20022.MessageIdentification1 `xml:"RptId"`
// Unique identification assigned by the matching application to the transaction.
// This identification is to be used in any communication between the parties.
TransactionIdentification *iso20022.SimpleIdentificationInformation `xml:"TxId"`
// Unique identification assigned by the matching application to the baseline when it is established.
EstablishedBaselineIdentification *iso20022.DocumentIdentification3 `xml:"EstblishdBaselnId,omitempty"`
// Identifies the status of the transaction by means of a code.
TransactionStatus *iso20022.TransactionStatus4 `xml:"TxSts"`
// Reference to the transaction for the financial institution which submitted the baseline.
UserTransactionReference []*iso20022.DocumentIdentification5 `xml:"UsrTxRef,omitempty"`
// Specifies the type of report.
ReportPurpose *iso20022.ReportType1 `xml:"RptPurp"`
// Specifies the commercial details of the underlying transaction.
PushedThroughBaseline *iso20022.Baseline5 `xml:"PushdThrghBaseln"`
// Person to be contacted in the organisation of the buyer.
BuyerContactPerson []*iso20022.ContactIdentification1 `xml:"BuyrCtctPrsn,omitempty"`
// Person to be contacted in the organisation of the seller.
SellerContactPerson []*iso20022.ContactIdentification1 `xml:"SellrCtctPrsn,omitempty"`
// Person to be contacted in the buyer's bank.
BuyerBankContactPerson []*iso20022.ContactIdentification1 `xml:"BuyrBkCtctPrsn,omitempty"`
// Person to be contacted in the seller's bank.
SellerBankContactPerson []*iso20022.ContactIdentification1 `xml:"SellrBkCtctPrsn,omitempty"`
// Person to be contacted in another bank than the seller or buyer's bank.
OtherBankContactPerson []*iso20022.ContactIdentification3 `xml:"OthrBkCtctPrsn,omitempty"`
// Information on the next processing step required.
RequestForAction *iso20022.PendingActivity2 `xml:"ReqForActn,omitempty"`
}
func (f *FullPushThroughReportV05) AddReportIdentification() *iso20022.MessageIdentification1 {
f.ReportIdentification = new(iso20022.MessageIdentification1)
return f.ReportIdentification
}
func (f *FullPushThroughReportV05) AddTransactionIdentification() *iso20022.SimpleIdentificationInformation {
f.TransactionIdentification = new(iso20022.SimpleIdentificationInformation)
return f.TransactionIdentification
}
func (f *FullPushThroughReportV05) AddEstablishedBaselineIdentification() *iso20022.DocumentIdentification3 {
f.EstablishedBaselineIdentification = new(iso20022.DocumentIdentification3)
return f.EstablishedBaselineIdentification
}
func (f *FullPushThroughReportV05) AddTransactionStatus() *iso20022.TransactionStatus4 {
f.TransactionStatus = new(iso20022.TransactionStatus4)
return f.TransactionStatus
}
func (f *FullPushThroughReportV05) AddUserTransactionReference() *iso20022.DocumentIdentification5 {
newValue := new(iso20022.DocumentIdentification5)
f.UserTransactionReference = append(f.UserTransactionReference, newValue)
return newValue
}
func (f *FullPushThroughReportV05) AddReportPurpose() *iso20022.ReportType1 {
f.ReportPurpose = new(iso20022.ReportType1)
return f.ReportPurpose
}
func (f *FullPushThroughReportV05) AddPushedThroughBaseline() *iso20022.Baseline5 {
f.PushedThroughBaseline = new(iso20022.Baseline5)
return f.PushedThroughBaseline
}
func (f *FullPushThroughReportV05) AddBuyerContactPerson() *iso20022.ContactIdentification1 {
newValue := new(iso20022.ContactIdentification1)
f.BuyerContactPerson = append(f.BuyerContactPerson, newValue)
return newValue
}
func (f *FullPushThroughReportV05) AddSellerContactPerson() *iso20022.ContactIdentification1 {
newValue := new(iso20022.ContactIdentification1)
f.SellerContactPerson = append(f.SellerContactPerson, newValue)
return newValue
}
func (f *FullPushThroughReportV05) AddBuyerBankContactPerson() *iso20022.ContactIdentification1 {
newValue := new(iso20022.ContactIdentification1)
f.BuyerBankContactPerson = append(f.BuyerBankContactPerson, newValue)
return newValue
}
func (f *FullPushThroughReportV05) AddSellerBankContactPerson() *iso20022.ContactIdentification1 {
newValue := new(iso20022.ContactIdentification1)
f.SellerBankContactPerson = append(f.SellerBankContactPerson, newValue)
return newValue
}
func (f *FullPushThroughReportV05) AddOtherBankContactPerson() *iso20022.ContactIdentification3 {
newValue := new(iso20022.ContactIdentification3)
f.OtherBankContactPerson = append(f.OtherBankContactPerson, newValue)
return newValue
}
func (f *FullPushThroughReportV05) AddRequestForAction() *iso20022.PendingActivity2 {
f.RequestForAction = new(iso20022.PendingActivity2)
return f.RequestForAction
}
| fgrid/iso20022 | tsmt/FullPushThroughReportV05.go | GO | mit | 5,855 |
namespace Kondor.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ExampleChangedEntityChanged : DbMigration
{
public override void Up()
{
AddColumn("dbo.Cards", "RowStatus", c => c.Int(nullable: false));
AddColumn("dbo.CardStates", "RowStatus", c => c.Int(nullable: false));
AddColumn("dbo.StringResources", "RowStatus", c => c.Int(nullable: false));
AddColumn("dbo.ExampleViews", "RowStatus", c => c.Int(nullable: false));
AddColumn("dbo.Examples", "ExampleUniqueId", c => c.Guid(nullable: false));
AddColumn("dbo.Examples", "RowStatus", c => c.Int(nullable: false));
AddColumn("dbo.Media", "RowStatus", c => c.Int(nullable: false));
AddColumn("dbo.Notifications", "RowStatus", c => c.Int(nullable: false));
AddColumn("dbo.Responses", "RowStatus", c => c.Int(nullable: false));
AddColumn("dbo.Settings", "RowStatus", c => c.Int(nullable: false));
AddColumn("dbo.Updates", "RowStatus", c => c.Int(nullable: false));
}
public override void Down()
{
DropColumn("dbo.Updates", "RowStatus");
DropColumn("dbo.Settings", "RowStatus");
DropColumn("dbo.Responses", "RowStatus");
DropColumn("dbo.Notifications", "RowStatus");
DropColumn("dbo.Media", "RowStatus");
DropColumn("dbo.Examples", "RowStatus");
DropColumn("dbo.Examples", "ExampleUniqueId");
DropColumn("dbo.ExampleViews", "RowStatus");
DropColumn("dbo.StringResources", "RowStatus");
DropColumn("dbo.CardStates", "RowStatus");
DropColumn("dbo.Cards", "RowStatus");
}
}
}
| odises/kondor | src/Kondor.Data/Migrations/201610060535379_ExampleChangedEntityChanged.cs | C# | mit | 1,810 |
# frozen_string_literal: true
class Dummy::Ui::CardListCell < ApplicationCell
def show
render if model.present?
end
end
| sinfin/folio | test/dummy/app/cells/dummy/ui/card_list_cell.rb | Ruby | mit | 129 |
# frozen_string_literal: true
# :nocov:
class UniqueJobWithoutUniqueArgsParameter
include Sidekiq::Worker
sidekiq_options backtrace: true,
lock: :until_executed,
queue: :customqueue,
retry: true,
lock_args_method: :unique_args
def perform(optional = true) # rubocop:disable Style/OptionalBooleanParameter
optional
# NO-OP
end
def self.unique_args; end
end
| mhenrixon/sidekiq-unique-jobs | spec/support/workers/unique_job_without_unique_args_parameter.rb | Ruby | mit | 450 |
import struct
''' Refer to docs for all the exact formats. There are many so check them out before converting things yourself '''
''' If there's a specific offset you want to do things from, use pack_into and unack_into from the docs '''
#Integer to string
i1= 1234
print "Int to string as 8 byte little endian", repr(struct.pack("<Q",i1))
print "Int to string as 8 byte big endian", repr(struct.pack(">Q",i1))
#String to integer. Make sure size of destination matches the length of the string
s1= '1234'
print "String to 4 byte integer little endian", struct.unpack("<i", s1)
print "String to 4 byte integer big endian", struct.unpack(">i", s1)
''' Whenever you want to convert to and from binary, think of binascii '''
import binascii
h1= binascii.b2a_hex(s1)
print "String to hex", h1
uh1= binascii.a2b_hex(h1)
print "Hex to string, even a binary string", uh1
| arvinddoraiswamy/LearnPython | 17.py | Python | mit | 867 |
\begin{figure}[H]
\centering
\includegraphics[width=6in]{figs/run_1/run_1_turb_visc_reynolds_vs_r_meshscatter}
\caption{Scatter plot of $
u_T$ reynolds stress term vs radius at $z/c$=5.37, $V_{free}$=15.22, station 1.}
\label{fig:run_1_turb_visc_reynolds_vs_r_meshscatter}
\end{figure}
| Jwely/pivpr | texdocs/figs/run_1/run_1_turb_visc_reynolds_vs_r_meshscatter.tex | TeX | mit | 288 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module MobileCenterApi
module Models
#
# Model object.
#
#
class Event
# @return [String]
attr_accessor :id
# @return [String]
attr_accessor :name
# @return [Integer]
attr_accessor :device_count
# @return [Integer] the device count of previous time range of the event
attr_accessor :previous_device_count
# @return [Integer]
attr_accessor :count
# @return [Integer] the event count of previous time range of the event
attr_accessor :previous_count
# @return [Integer]
attr_accessor :count_per_device
# @return [Integer]
attr_accessor :count_per_session
#
# Mapper for Event class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
required: false,
serialized_name: 'Event',
type: {
name: 'Composite',
class_name: 'Event',
model_properties: {
id: {
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
device_count: {
required: false,
serialized_name: 'deviceCount',
type: {
name: 'Number'
}
},
previous_device_count: {
required: false,
serialized_name: 'previous_device_count',
type: {
name: 'Number'
}
},
count: {
required: false,
serialized_name: 'count',
type: {
name: 'Number'
}
},
previous_count: {
required: false,
serialized_name: 'previous_count',
type: {
name: 'Number'
}
},
count_per_device: {
required: false,
serialized_name: 'count_per_device',
type: {
name: 'Number'
}
},
count_per_session: {
required: false,
serialized_name: 'count_per_session',
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| ewgenius/fastlane-plugin-mobile_center | lib/generated/mobile_center_api/models/event.rb | Ruby | mit | 2,868 |
## About This Project
This Software licensed under the [MIT license](http://opensource.org/licenses/MIT).
This is developed as a part of home automation system. This project addesses the user management capability of that project.
| AyeshJayasekara/User-Management-System | readme.md | Markdown | mit | 235 |
require 'helper'
class TestLicenseeMatcher < Minitest::Test
should "match the license without raising an error" do
assert_nil Licensee::Matcher.match(nil)
end
end
| JuanitoFatas/licensee | test/test_licensee_matcher.rb | Ruby | mit | 172 |
import Helper from '@ember/component/helper';
import { inject as service } from '@ember/service';
import { get } from '@ember/object';
export default class MediaHelper extends Helper {
@service() media;
constructor() {
super(...arguments);
this.media.on('mediaChanged', () => {
this.recompute();
});
}
compute([prop]) {
return get(this, `media.${prop}`);
}
}
| freshbooks/ember-responsive | addon/helpers/media.js | JavaScript | mit | 395 |
Enum = {
BarDrawDirect: {
Horizontal: "Horizontal",
Vertical: "Vertical"
},
PowerType: {
MP: 0,
Angery: 1
},
EffectType: {
StateChange: "StateChange",
HpChange: "HpChange",
Timing: "Timing",
Control: "Control"
},
EffectControlType: {
Stun: "Stun",
Silence: "Silence",
Sleep: "Sleep"
},
EffectCharacterType: {
Passive: "Passive",
Self: "Self",
Column: "Column",
Single: "Single",
Row: "Row",
All: "All"
},
EffectRange: {
Melee: "Melee",
Range: "Range"
},
StateChangeClass: {
Plus: "Plus",
Minus: "Minus"
},
StateChangeType: {
HitRate: "HitRate",
DodgeRate: "DodgeRate"
},
HpChangeClass: {
Damage: "Damage",
Heal: "Heal"
},
HpChangeType: {
Normal: "Normal",
Critial: "Critial"
},
BattleActionType: {
Physical: "Physical",
Magical: "Magical"
},
EffectStyle: {
Temp: "Temp",
Static: "Static",
UniqueTemp: "UniqueTemp"
},
Align: {
Left: "Left",
Right: "Right",
Center: "Center"
}
} | mt830813/code | Project/HTML5Test/Test1/Scripts/Customer/Setting/Enum.js | JavaScript | mit | 1,263 |
package io.prajesh.config;
import io.prajesh.domain.HelloWorld;
import io.prajesh.service.HelloWorldService;
import io.prajesh.service.HelloWorldServiceImpl;
import io.prajesh.service.factory.HelloWorldFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* @author Prajesh Ananthan
* Created on 16/7/2017.
*/
@Configuration
public class HelloConfig {
@Bean
public HelloWorldFactory helloWorldFactory() {
return new HelloWorldFactory();
}
@Bean
public HelloWorldService helloWorldService() {
return new HelloWorldServiceImpl();
}
@Bean
@Profile("English")
public HelloWorld helloWorldEn(HelloWorldFactory factory) {
return factory.getHelloWorldFactory("en");
}
@Bean
@Profile("Malay")
public HelloWorld helloWorldMy(HelloWorldFactory factory) {
return factory.getHelloWorldFactory("my");
}
}
| prajesh-ananthan/spring-playfield | spring-core/src/main/java/io/prajesh/config/HelloConfig.java | Java | mit | 980 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2013 The PPCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include "kernel.h"
#include "main.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <cstdlib>
#include "GetNextTargetRequired.h"
#include "GetProofOfStakeReward.h"
#include "GetProofOfWorkReward.h"
using namespace std;
using namespace boost;
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
set<pair<COutPoint, unsigned int> > setStakeSeen;
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
CBigNum bnBestChainTrust = 0;
CBigNum bnBestInvalidTrust = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64 nTimeBestReceived = 0;
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
map<uint256, uint256> mapProofOfStake;
map<uint256, CDataStream*> mapOrphanTransactions;
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = COIN_NAME " Signed Message:\n";
double dHashesPerSec;
int64 nHPSTimerStart;
// Settings
int64 nTransactionFee = MIN_TX_FEES;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// check whether the passed transaction is from us
bool static IsFromMe(CTransaction& tx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
return true;
return false;
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
{
if (!fConnect)
{
// ppcoin: wallets need to refund inputs when disconnecting coinstake
if (tx.IsCoinStake())
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
pwallet->DisableTransaction(tx);
}
return;
}
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void static ResendWalletTransactions()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions();
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CDataStream& vMsg)
{
CTransaction tx;
CDataStream(vMsg) >> tx;
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
CDataStream* pvMsg = new CDataStream(vMsg);
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
if (pvMsg->size() > 5000)
{
printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
delete pvMsg;
return false;
}
mapOrphanTransactions[hash] = pvMsg;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CDataStream* pvMsg = mapOrphanTransactions[hash];
CTransaction tx;
CDataStream(*pvMsg) >> tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
delete pvMsg;
mapOrphanTransactions.erase(hash);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction and CTxIndex
//
bool CTransaction::ReadFromDisk(CTxDB& txdb, const uint256& hash, CTxIndex& txindexRet)
{
SetNull();
if (!txdb.ReadTxIndex(hash, txindexRet))
return false;
if (!ReadFromDisk(txindexRet.pos))
return false;
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
{
if (!ReadFromDisk(txdb, prevout.hash, txindexRet))
return false;
if (prevout.n >= vout.size())
{
SetNull();
return false;
}
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
{
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::ReadFromDisk(COutPoint prevout)
{
CTxDB txdb("r");
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::IsStandard() const
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
// pay-to-script-hash, which is 3 ~80-byte signatures, 3
// ~65-byte public keys, plus a few script ops.
if (txin.scriptSig.size() > 500)
return false;
if (!txin.scriptSig.IsPushOnly())
return false;
}
unsigned int nDataOut = 0;
txnouttype whichType;
BOOST_FOREACH(const CTxOut& txout, vout) {
if (!::IsStandard(txout.scriptPubKey, whichType)) {
return false;
}
if (whichType == TX_NULL_DATA)
nDataOut++;
}
// only one OP_RETURN txout is permitted
if (nDataOut > 1) {
return false;
}
return true;
}
//
// Check transaction inputs, and make sure any
// pay-to-script-hash transactions are evaluating IsStandard scripts
//
// Why bother? To avoid denial-of-service attacks; an attacker
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
// expensive-to-check-upon-redemption script like:
// DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
{
if (IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (!Solver(subscript, whichType2, vSolutions2))
return false;
if (whichType2 == TX_SCRIPTHASH)
return false;
int tmpExpected;
tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int
CTransaction::GetLegacySigOpCount() const
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
if (fClient)
{
if (hashBlock == 0)
return 0;
}
else
{
CBlock blockTmp;
if (pblock == NULL)
{
// Load the block this tx is in
CTxIndex txindex;
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
return 0;
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
return 0;
pblock = &blockTmp;
}
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::IsRestrictedCoinStake() const
{
if (!IsCoinStake())
return false;
int64 nValueIn = 0;
CScript onlyAllowedScript;
for (unsigned int i = 0; i < vin.size(); ++i)
{
const COutPoint& prevout = vin[i].prevout;
CTxDB txdb("r");
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, prevout, txindex))
return false;
txdb.Close();
const CTxOut& prevtxo = txPrev.vout[prevout.n];
const CScript& prevScript = prevtxo.scriptPubKey;
if (i == 0)
{
onlyAllowedScript = prevScript;
if (onlyAllowedScript.empty())
{
return false;
}
}
else
{
if (prevScript != onlyAllowedScript)
{
return false;
}
}
nValueIn += prevtxo.nValue;
}
int64 nValueOut = 0;
for (unsigned int i = 1; i < vout.size(); ++i)
{
const CTxOut& txo = vout[i];
if (txo.nValue == 0)
continue ;
if (txo.scriptPubKey != onlyAllowedScript)
return false;
nValueOut += txo.nValue;
}
if (nValueOut < nValueIn)
return false;
return true;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Time (prevent mempool memory exhaustion attack)
if (nTime > GetAdjustedTime() + MAX_CLOCK_DRIFT)
return DoS(10, error("CTransaction::CheckTransaction() : timestamp is too far into the future"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64 nValueOut = 0;
for (size_t i = 0; i < vout.size(); i++)
{
const CTxOut& txout = vout[i];
if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake()))
return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
// ppcoin: enforce minimum output amount
if ((!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum (%d)", txout.nValue));
if (txout.nValue > MAX_MONEY_STACK)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high (%d)", txout.nValue));
nValueOut += txout.nValue;
if (!IsValidAmount(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
bool* pfMissingInputs)
{
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("CTxMemPool::accept() : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
// ppcoin: coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
// To help v0.1.5 clients who would see it as a negative number
if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
// Rather not work on nonstandard transactions
if (!tx.IsStandard())
return error("CTxMemPool::accept() : nonstandard transaction type");
// Do we already have it?
uint256 hash = tx.GetHash();
{
LOCK(cs);
if (mapTx.count(hash))
return false;
}
if (fCheckInputs)
if (txdb.ContainsTx(hash))
return false;
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
// Allow replacing with a newer version of the same transaction
if (i != 0)
return false;
ptxOld = mapNextTx[outpoint].ptx;
if (ptxOld->IsFinal())
return false;
if (!tx.IsNewerThan(*ptxOld))
return false;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
if (fCheckInputs)
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
if (pfMissingInputs)
*pfMissingInputs = true;
return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
}
// Check for non-standard pay-to-script-hash in inputs
if (!tx.AreInputsStandard(mapInputs))
return error("CTxMemPool::accept() : nonstandard transaction input");
// Note: if you modify this code to accept non-standard transactions, then
// you should add code here to check that the transaction does a
// reasonable number of ECDSA signature verifications.
int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
if (nFees < tx.GetMinFee(1000, false, GMF_RELAY))
return error("CTxMemPool::accept() : not enough fees");
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make other's transactions take longer to confirm.
if (nFees < MIN_RELAY_TX_FEES)
{
static CCriticalSection cs;
static double dFreeCount;
static int64 nLastTime;
int64 nNow = GetTime();
{
LOCK(cs);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
if (fDebug)
printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
{
return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
}
}
// Store transaction in memory
{
LOCK(cs);
if (ptxOld)
{
printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
remove(*ptxOld);
}
addUnchecked(tx);
}
///// are we sure this is ok when loading transactions or restoring block txes
// If updated, erase old tx from wallet
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str());
return true;
}
bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
{
return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
}
bool CTxMemPool::addUnchecked(CTransaction &tx)
{
printf("addUnchecked(): size %lu\n", mapTx.size());
// Add to memory pool without checking anything. Don't call this directly,
// call CTxMemPool::accept to properly check the transaction first.
{
LOCK(cs);
uint256 hash = tx.GetHash();
mapTx[hash] = tx;
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
nTransactionsUpdated++;
}
return true;
}
bool CTxMemPool::remove(CTransaction &tx)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
int depth = GetDepthInMainChain();
if (depth == 0) // Not in the blockchain
return COINBASE_MATURITY;
return max(0, COINBASE_MATURITY - (depth - 1));
}
bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
{
if (fClient)
{
if (!IsInMainChain() && !ClientConnectInputs())
return false;
return CTransaction::AcceptToMemoryPool(txdb, false);
}
else
{
return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
}
}
bool CMerkleTx::AcceptToMemoryPool()
{
CTxDB txdb("r");
return AcceptToMemoryPool(txdb);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
{
{
LOCK(mempool.cs);
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool(txdb, fCheckInputs);
}
}
return AcceptToMemoryPool(txdb, fCheckInputs);
}
return false;
}
bool CWalletTx::AcceptWalletTransaction()
{
CTxDB txdb("r");
return AcceptWalletTransaction(txdb);
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
{
{
LOCK(cs_main);
{
LOCK(mempool.cs);
if (mempool.exists(hash))
{
tx = mempool.lookup(hash);
return true;
}
}
CTxDB txdb("r");
CTxIndex txindex;
if (tx.ReadFromDisk(txdb, hash, txindex))
{
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
hashBlock = block.GetHash();
return true;
}
// look for transaction in disconnected blocks to find orphaned CoinBase and CoinStake transactions
BOOST_FOREACH(PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
if (pindex == pindexBest || pindex->pnext != 0)
continue;
CBlock block;
if (!block.ReadFromDisk(pindex))
continue;
BOOST_FOREACH(const CTransaction& txOrphan, block.vtx)
{
if (txOrphan.GetHash() == hash)
{
tx = txOrphan;
return true;
}
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->GetHash();
}
// ppcoin: find block wanted by given orphan block
uint256 WantedByOrphan(const CBlock* pblockOrphan)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
return pblockOrphan->hashPrevBlock;
}
//
// minimum amount of work that could possibly be required nTime after
// minimum work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
{
CBigNum bnResult;
bnResult.SetCompact(nBase);
bnResult *= 2;
while (nTime > 0 && bnResult < POW_MAX_TARGET)
{
// Maximum 200% adjustment per day...
bnResult *= 2;
nTime -= 24 * 60 * 60;
}
if (bnResult > POW_MAX_TARGET)
bnResult = POW_MAX_TARGET;
return bnResult.GetCompact();
}
// ppcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
pindex = pindex->pprev;
return pindex;
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, bool triggerErrors)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > POW_MAX_TARGET)
return triggerErrors ? error("CheckProofOfWork() : nBits below minimum work") : false;
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return triggerErrors ? error("CheckProofOfWork() : hash doesn't match nBits") : false;
return true;
}
// Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
}
bool IsInitialBlockDownload()
{
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64 nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 10 &&
pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->bnChainTrust > bnBestInvalidTrust)
{
bnBestInvalidTrust = pindexNew->bnChainTrust;
CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust);
MainFrameRepaint();
}
printf("InvalidChainFound: invalid block=%s height=%d trust=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, CBigNum(pindexNew->bnChainTrust).ToString().c_str());
printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(bnBestChainTrust).ToString().c_str());
// ppcoin: should not enter safe mode for longer invalid chain
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(GetBlockTime(), GetAdjustedTime());
}
bool CTransaction::DisconnectInputs(CTxDB& txdb)
{
// Relinquish previous transactions' spent pointers
if (!IsCoinBase())
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
// Get prev txindex from disk
CTxIndex txindex;
if (!txdb.ReadTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : ReadTxIndex failed");
if (prevout.n >= txindex.vSpent.size())
return error("DisconnectInputs() : prevout.n out of range");
// Mark outpoint as not spent
txindex.vSpent[prevout.n].SetNull();
// Write back
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : UpdateTxIndex failed");
}
}
// Remove transaction from index
// This can fail if a duplicate of this transaction was in a chain that got
// reorganized away. This is only possible if this transaction was completely
// spent, so erasing it would be a no-op anway.
txdb.EraseTxIndex(*this);
return true;
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
// (in which case the transaction should be stored as an orphan)
// or because the transaction is malformed (in which case the transaction should
// be dropped). If tx is definitely invalid, fInvalid will be set to true.
fInvalid = false;
if (IsCoinBase())
return true; // Coinbase transactions have no inputs to fetch.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
if (inputsRet.count(prevout.hash))
continue; // Got it already
// Read txindex
CTxIndex& txindex = inputsRet[prevout.hash].first;
bool fFound = true;
if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
{
// Get txindex from current proposed changes
txindex = mapTestPool.find(prevout.hash)->second;
}
else
{
// Read txindex from txdb
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
}
if (!fFound && (fBlock || fMiner))
return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
// Read txPrev
CTransaction& txPrev = inputsRet[prevout.hash].second;
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
{
// Get prev tx from single transactions in memory
{
LOCK(mempool.cs);
if (!mempool.exists(prevout.hash))
return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
txPrev = mempool.lookup(prevout.hash);
}
if (!fFound)
txindex.vSpent.resize(txPrev.vout.size());
}
else
{
// Get prev tx from disk
if (!txPrev.ReadFromDisk(txindex.pos))
return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
}
}
// Make sure all prevout.n's are valid:
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint prevout = vin[i].prevout;
assert(inputsRet.count(prevout.hash) != 0);
const CTxIndex& txindex = inputsRet[prevout.hash].first;
const CTransaction& txPrev = inputsRet[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
{
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
}
}
return true;
}
const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
{
MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
if (mi == inputs.end())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
const CTransaction& txPrev = (mi->second).second;
if (input.prevout.n >= txPrev.vout.size())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
return txPrev.vout[input.prevout.n];
}
int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64 nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
nResult += GetOutputFor(vin[i], inputs).nValue;
}
return nResult;
}
unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prevout = GetOutputFor(vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
}
return nSigOps;
}
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
{
// Take over previous transactions' spent pointers
// fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
// fMiner is true when called from the internal bitcoin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64 nValueIn = 0;
int64 nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
// If prev is coinbase/coinstake, check that it's matured
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight);
// ppcoin: check transaction timestamp
if (txPrev.nTime > nTime)
return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
// Check for negative or overflow input values
nValueIn += txPrev.vout[prevout.n].nValue;
if (!IsValidAmount(txPrev.vout[prevout.n].nValue) || !IsValidAmount(nValueIn))
return DoS(100, error("ConnectInputs() : txin values out of range"));
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
// Check for conflicts (double-spend)
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!txindex.vSpent[prevout.n].IsNull())
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
// Skip ECDSA signature verification when connecting blocks (fBlock=true)
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
{
// Verify signature
if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
{
// only during transition phase for P2SH: do not invoke anti-DoS code for
// potentially old clients relaying bad P2SH transactions
if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
}
}
// Mark outpoints as spent
txindex.vSpent[prevout.n] = posThisTx;
// Write back
if (fBlock || fMiner)
{
mapTestPool[prevout.hash] = txindex;
}
}
if (IsCoinStake())
{
// ppcoin: coin stake tx earns reward instead of paying fee
uint64 nCoinAge;
if (!GetCoinAge(txdb, nCoinAge))
return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
int64 nStakeReward = GetValueOut() - nValueIn;
if (nStakeReward > GetProofOfStakeReward(nCoinAge, pindexBlock->pprev->nHeight) - GetMinFee() + MIN_TX_FEES)
return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
}
else
{
if (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
// Tally transaction fees
int64 nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
// ppcoin: enforce transaction fees for every block
if (nTxFee < GetMinFee())
return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false;
nFees += nTxFee;
if (!IsValidAmount(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
}
return true;
}
bool CTransaction::ClientConnectInputs()
{
if (IsCoinBase())
return false;
// Take over previous transactions' spent pointers
{
LOCK(mempool.cs);
int64 nValueIn = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
// Get prev tx from single transactions in memory
COutPoint prevout = vin[i].prevout;
if (!mempool.exists(prevout.hash))
return false;
CTransaction& txPrev = mempool.lookup(prevout.hash);
if (prevout.n >= txPrev.vout.size())
return false;
// Verify signature
if (!VerifySignature(txPrev, *this, i, true, 0))
return error("ConnectInputs() : VerifySignature failed");
///// this is redundant with the mempool.mapNextTx stuff,
///// not sure which I want to get rid of
///// this has to go away now that posNext is gone
// // Check for conflicts
// if (!txPrev.vout[prevout.n].posNext.IsNull())
// return error("ConnectInputs() : prev tx already used");
//
// // Flag outpoints as used
// txPrev.vout[prevout.n].posNext = posThisTx;
nValueIn += txPrev.vout[prevout.n].nValue;
if (!IsValidAmount(txPrev.vout[prevout.n].nValue) || !IsValidAmount(nValueIn)) {
return error("ClientConnectInputs() : txin values out of range");
}
}
if (GetValueOut() > nValueIn) {
return false;
}
}
return true;
}
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Disconnect in reverse order
for (int i = vtx.size()-1; i >= 0; i--)
if (!vtx[i].DisconnectInputs(txdb))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = 0;
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("DisconnectBlock() : WriteBlockIndex failed");
}
// ppcoin: clean up wallet after disconnecting coinstake
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, false, false);
return true;
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Check it again in case a previous version let a bad block in
if (!CheckBlock())
return false;
// Check coinbase reward
if (IsProofOfWork() && vtx[0].GetValueOut() > (IsProofOfWork() ? (GetProofOfWorkReward(pindex->pprev ? pindex->pprev->nHeight : -1) - vtx[0].GetMinFee() + MIN_TX_FEES) : 0))
return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s", FormatMoney(vtx[0].GetValueOut()).c_str(), FormatMoney(IsProofOfWork() ? GetProofOfWorkReward(pindex->pprev ? pindex->pprev->nHeight : -1) : 0).c_str()));
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction id's entirely.
BOOST_FOREACH(CTransaction& tx, vtx)
{
CTxIndex txindexOld;
if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
{
BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
if (pos.IsNull())
return false;
}
}
// BIP16 didn't become active until Apr 1 2012
int64 nBIP16SwitchTime = 1333238400;
bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
//// issue here: it doesn't know the version
unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
int64 nFees = 0;
int64 nValueIn = 0;
int64 nValueOut = 0;
unsigned int nSigOps = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (tx.IsCoinBase())
nValueOut += tx.GetValueOut();
else
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
if (fStrictPayToScriptHash)
{
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
}
int64 nTxValueIn = tx.GetValueIn(mapInputs);
int64 nTxValueOut = tx.GetValueOut();
nValueIn += nTxValueIn;
nValueOut += nTxValueOut;
if (!tx.IsCoinStake())
nFees += nTxValueIn - nTxValueOut;
if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
return false;
}
mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
}
// ppcoin: track money supply and mint amount info
pindex->nMint = nValueOut - nValueIn + nFees;
pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
return error("Connect() : WriteBlockIndex for pindex failed");
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
}
// ppcoin: fees are not collected by miners as in bitcoin
// ppcoin: fees are destroyed to compensate the entire network
if (fDebug && GetBoolArg("-printcreation"))
printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = pindex->GetBlockHash();
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("ConnectBlock() : WriteBlockIndex for blockindexPrev failed");
}
// Watch for transactions paying to me
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, true);
return true;
}
bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
{
printf("REORGANIZE\n");
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("Reorganize() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("Reorganize() : pfork->pprev is null");
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
// Disconnect shorter branch
vector<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for disconnect failed");
if (!block.DisconnectBlock(txdb, pindex))
return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
// Queue memory transactions to resurrect
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
vResurrect.push_back(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for connect failed");
if (!block.ConnectBlock(txdb, pindex))
{
// Invalid block
txdb.TxnAbort();
return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
}
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
return error("Reorganize() : WriteHashBestChain failed");
// Make sure it's successfully written to disk before changing memory structure
if (!txdb.TxnCommit())
return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
tx.AcceptToMemoryPool(txdb, false);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete)
mempool.remove(tx);
printf("REORGANIZE: done\n");
return true;
}
// Called from inside SetBestChain: attaches a block to the new best chain being built
bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
{
uint256 hash = GetHash();
// Adding to current best branch
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return false;
}
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
// Add to current best branch
pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions
BOOST_FOREACH(CTransaction& tx, vtx)
mempool.remove(tx);
return true;
}
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
{
uint256 hash = GetHash();
if (!txdb.TxnBegin())
return error("SetBestChain() : TxnBegin failed");
if (pindexGenesisBlock == NULL && hash == GENESIS_HASH)
{
txdb.WriteHashBestChain(hash);
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashBestChain)
{
if (!SetBestChainInner(txdb, pindexNew))
return error("SetBestChain() : SetBestChainInner failed");
}
else
{
// the first block in the new chain that will cause it to become the new best chain
CBlockIndex *pindexIntermediate = pindexNew;
// list of blocks that need to be connected afterwards
std::vector<CBlockIndex*> vpindexSecondary;
// Reorganize is costly in terms of db load, as it works in a single db transaction.
// Try to limit how much needs to be done inside
while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
printf("Postponing %i reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect futher blocks
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
{
printf("SetBestChain() : ReadFromDisk failed\n");
break;
}
if (!txdb.TxnBegin()) {
printf("SetBestChain() : TxnBegin 2 failed\n");
break;
}
// errors now are not fatal, we still did a reorganisation to a new chain in a valid way
if (!block.SetBestChainInner(txdb, pindex))
break;
}
}
// Update best block in wallet (so we can detect restored wallets)
bool fIsInitialDownload = IsInitialBlockDownload();
if (!fIsInitialDownload)
{
const CBlockLocator locator(pindexNew);
::SetBestChain(locator);
}
// New best block
hashBestChain = hash;
pindexBest = pindexNew;
nBestHeight = pindexBest->nHeight;
bnBestChainTrust = pindexNew->bnChainTrust;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
printf("SetBestChain: new best=%s height=%d trust=%s moneysupply=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(), FormatMoney(pindexBest->nMoneySupply).c_str());
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
// ppcoin: total coin age spent in transaction, in the unit of coin-days.
// Only those coins meeting minimum age requirement counts. As those
// transactions not in main chain are not currently indexed so we
// might not find out about their coin age. Older transactions are
// guaranteed to be in main chain by sync-checkpoint. This rule is
// introduced to help nodes establish a consistent view of the coin
// age (trust score) of competing branches.
bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
{
CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
nCoinAge = 0;
if (IsCoinBase())
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// First try finding the previous transaction in database
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
continue; // previous transaction not in main chain
if (nTime < txPrev.nTime)
return false; // Transaction timestamp violation
// Read block header
CBlock block;
if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
return false; // unable to read block of previous transaction
if (block.GetBlockTime() + STAKE_MIN_AGE > nTime)
continue; // only count coins meeting min age requirement
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
if (fDebug && GetBoolArg("-printcoinage"))
{
printf("coin age nValueIn=%-12"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
}
}
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
nCoinAge = bnCoinDay.getuint64();
return true;
}
// ppcoin: total coin age spent in block, in the unit of coin-days.
bool CBlock::GetCoinAge(uint64& nCoinAge) const
{
nCoinAge = 0;
CTxDB txdb("r");
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uint64 nTxCoinAge;
if (tx.GetCoinAge(txdb, nTxCoinAge))
nCoinAge += nTxCoinAge;
else
return false;
}
if (nCoinAge == 0) // block coin age minimum 1 coin-day
nCoinAge = 1;
if (fDebug && GetBoolArg("-printcoinage"))
printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
pindexNew->phashBlock = &hash;
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
// ppcoin: compute chain trust score
pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
// ppcoin: compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit()))
return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
// ppcoin: record proof-of-stake hash value
if (pindexNew->IsProofOfStake())
{
if (!mapProofOfStake.count(hash))
return error("AddToBlockIndex() : hashProofOfStake not found in map");
pindexNew->hashProofOfStake = mapProofOfStake[hash];
}
// ppcoin: compute stake modifier
uint64 nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x", checksum=0x%08x", pindexNew->nHeight, nStakeModifier, pindexNew->nStakeModifierChecksum);
// Add to mapBlockIndex
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
// Write to disk block index
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
// New best
if (pindexNew->bnChainTrust > bnBestChainTrust)
if (!SetBestChain(txdb, pindexNew))
return false;
txdb.Close();
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = vtx[0].GetHash();
}
MainFrameRepaint();
return true;
}
bool CBlock::CheckBlock() const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
// Check proof of work matches claimed amount
if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > GetAdjustedTime() + MAX_CLOCK_DRIFT)
return error("CheckBlock() : block timestamp too far in the future");
// First transaction must be coinbase, the rest must not be
if (vtx.empty() || !vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
for (unsigned int i = 1; i < vtx.size(); i++)
if (vtx[i].IsCoinBase())
return DoS(100, error("CheckBlock() : more than one coinbase"));
// ppcoin: only the second transaction can be the optional coinstake
for (size_t i = 2; i < vtx.size(); i++)
if (vtx[i].IsCoinStake())
return DoS(100, error("CheckBlock() : coinstake in wrong position"));
// ppcoin: coinbase output should be empty if proof-of-stake block
if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()))
return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
// Check coinbase timestamp
if (GetBlockTime() > (int64)vtx[0].nTime + MAX_CLOCK_DRIFT)
return DoS(50, error("CheckBlock() : coinbase timestamp is too early (block: %d, vtx[0]: %d)", GetBlockTime(), vtx[0].nTime));
// Check coinstake timestamp
if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%u nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
// Check coinbase reward
//
// Note: We're not doing the reward check here, because we need to know the block height.
// Check inside ConnectBlock instead.
// Check transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
{
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// ppcoin: check transaction timestamp
if (GetBlockTime() < (int64)tx.nTime)
return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
}
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uniqueTx.insert(tx.GetHash());
}
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkleroot
if (hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
// ppcoin: check block signature
if (!CheckBlockSignature())
return DoS(100, error("CheckBlock() : bad block signature"));
return true;
}
bool CBlock::AcceptBlock()
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
// Check proof-of-work or proof-of-stake
if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + MAX_CLOCK_DRIFT < pindexPrev->GetBlockTime())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.IsFinal(nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a hardened checkpoint
if (!Checkpoints::CheckHardened(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight));
// ppcoin: check that the block satisfies synchronized checkpoint
if (!Checkpoints::CheckSync(hash, pindexPrev))
return error("AcceptBlock() : rejected by synchronized checkpoint");
// Write block to history file
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
unsigned int nFile = -1;
unsigned int nBlockPos = 0;
if (!WriteToDisk(nFile, nBlockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(nFile, nBlockPos))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
// ppcoin: check pending sync-checkpoint
Checkpoints::AcceptPendingSyncCheckpoint();
return true;
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex.at(hash)->nHeight, hash.ToString().substr(0,20).c_str());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
// ppcoin: check proof-of-stake
if (pblock->IsProofOfStake())
{
std::pair<COutPoint, unsigned int> proofOfStake = pblock->GetProofOfStake();
if (pindexBest->IsProofOfStake() && proofOfStake.first == pindexBest->prevoutStake)
{
if (!pblock->CheckBlockSignature())
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : invalid signature in a duplicate Proof-of-Stake kernel");
}
RelayBlock(*pblock, hash);
BlacklistProofOfStake(proofOfStake, hash);
CTxDB txdb;
CBlock bestPrevBlock;
bestPrevBlock.ReadFromDisk(pindexBest->pprev);
if (!bestPrevBlock.SetBestChain(txdb, pindexBest->pprev))
return error("ProcessBlock() : Proof-of-stake rollback failed");
return error("ProcessBlock() : duplicate Proof-of-Stake kernel (%s, %d) in block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
}
else if (setStakeSeen.count(proofOfStake) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
{
return error("ProcessBlock() : duplicate Proof-of-Stake kernel (%s, %d) in block %s", proofOfStake.first.ToString().c_str(), proofOfStake.second, hash.ToString().c_str());
}
}
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
if (bnNewBlock > bnRequired)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
}
}
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
// We remove the previous block from the blacklisted kernels, if needed
CleanProofOfStakeBlacklist(pblock->hashPrevBlock);
// Find the previous block
std::map<uint256, CBlockIndex*>::iterator parentBlockIt = mapBlockIndex.find(pblock->hashPrevBlock);
// If we don't already have it, shunt off the block to the holding area until we get its parent
if (parentBlockIt == mapBlockIndex.end())
{
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
CBlock* pblock2 = new CBlock(*pblock);
// ppcoin: check proof-of-stake
if (pblock2->IsProofOfStake())
setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
if (pfrom)
{
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
// ppcoin: getblocks may not obtain the ancestor block rejected
// earlier by duplicate-stake check so we ask for it again directly
if (!IsInitialBlockDownload())
{
pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
}
}
return true;
}
// ppcoin: verify hash target and signature of coinstake tx
if (pblock->IsProofOfStake())
{
uint256 hashProofOfStake = 0;
const CBlockIndex * pindexPrev = parentBlockIt->second;
if (!CheckProofOfStake(pindexPrev, pblock->vtx[1], pblock->nBits, hashProofOfStake))
{
printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
return false; // do not error here as we expect this during initial block download
}
if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
{
mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
}
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
CBlockIndex* pindexPrev = mapBlockIndex.at(hashPrev);
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi)
{
bool validated = true;
CBlock* pblockOrphan = (*mi).second;
uint256 orphanHash = pblockOrphan->GetHash();
if (pblockOrphan->IsProofOfStake())
{
uint256 hashProofOfStake = 0;
if (CheckProofOfStake(pindexPrev, pblockOrphan->vtx[1], pblockOrphan->nBits, hashProofOfStake))
{
if (!mapProofOfStake.count(orphanHash))
mapProofOfStake.insert(make_pair(orphanHash, hashProofOfStake));
validated = true;
}
else
{
validated = false;
}
}
if (validated && pblockOrphan->AcceptBlock())
vWorkQueue.push_back(orphanHash);
mapOrphanBlocks.erase(orphanHash);
setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
// ppcoin: if responsible for sync-checkpoint send it
if (pfrom && !CHECKPOINT_PRIVATE_KEY.empty())
Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
return true;
}
// ppcoin: sign block
bool CBlock::SignBlock(const CKeyStore& keystore)
{
vector<valtype> vSolutions;
txnouttype whichType;
const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
// Sign
const valtype& vchPubKey = vSolutions[0];
CKey key;
if (!keystore.GetKey(Hash160(vchPubKey), key))
return false;
if (key.GetPubKey() != vchPubKey)
return false;
return key.Sign(GetHash(), vchBlockSig);
}
else if (whichType == TX_SCRIPTHASH)
{
CScript subscript;
if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
return false;
if (!Solver(subscript, whichType, vSolutions))
return false;
if (whichType != TX_COLDMINTING)
return false;
CKey key;
if (!keystore.GetKey(uint160(vSolutions[0]), key))
return false;
return key.Sign(GetHash(), vchBlockSig);
}
return false;
}
// ppcoin: check block signature
bool CBlock::CheckBlockSignature() const
{
if (GetHash() == GENESIS_HASH)
return vchBlockSig.empty();
vector<valtype> vSolutions;
txnouttype whichType;
const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
const valtype& vchPubKey = vSolutions[0];
CKey key;
if (!key.SetPubKey(vchPubKey))
return false;
if (vchBlockSig.empty())
return false;
return key.Verify(GetHash(), vchBlockSig);
}
else if (whichType == TX_SCRIPTHASH)
{
// Output is a pay-to-script-hash
// Only allowed with cold minting
if (!IsProofOfStake())
return false;
// CoinStake scriptSig should contain 3 pushes: the signature, the pubkey and the cold minting script
CScript scriptSig = vtx[1].vin[0].scriptSig;
if (!scriptSig.IsPushOnly())
return false;
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, scriptSig, CTransaction(), 0, 0))
return false;
if (stack.size() != 3)
return false;
// Verify the script is a cold minting script
const valtype& scriptSerialized = stack.back();
CScript script(scriptSerialized.begin(), scriptSerialized.end());
if (!Solver(script, whichType, vSolutions))
return false;
if (whichType != TX_COLDMINTING)
return false;
// Verify the scriptSig pubkey matches the minting key
valtype& vchPubKey = stack[1];
if (Hash160(vchPubKey) != uint160(vSolutions[0]))
return false;
// Verify the block signature with the minting key
CKey key;
if (!key.SetPubKey(vchPubKey))
return false;
if (vchBlockSig.empty())
return false;
return key.Verify(GetHash(), vchBlockSig);
}
return false;
}
// ppcoin: entropy bit for stake modifier if chosen by modifier
unsigned int CBlock::GetStakeEntropyBit() const
{
unsigned int nEntropyBit = 0;
nEntropyBit = ((GetHash().Get64()) & 1llu); // last bit of block hash
if (fDebug && GetBoolArg("-printstakemodifier"))
printf("GetStakeEntropyBit(v0.4+): nTime=%u hashBlock=%s entropybit=%d\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
return nEntropyBit;
}
bool CheckDiskSpace(uint64 nAdditionalBytes)
{
uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for 15MB because database could create another 10MB log file at any time
if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
{
fShutdown = true;
string strMessage = _("Warning: Disk space is low");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
ThreadSafeMessageBox(strMessage, COIN_NAME, wxOK | wxICON_EXCLAMATION | wxMODAL);
StartShutdown();
return false;
}
return true;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if (nFile == static_cast<unsigned int>(-1))
return NULL;
FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
INFINITE_LOOP
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < 0x7F000000 - MAX_SIZE)
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
//
// Load block index
//
CTxDB txdb("cr");
if (!txdb.LoadBlockIndex())
return false;
txdb.Close();
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
// Genesis Block:
// CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
// CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
// CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
// CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
// vMerkleTree: 4a5e1e
const char* pszTimestamp = GENESIS_IDENT;
CTransaction txNew;
txNew.nTime = GENESIS_TX_TIME;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].SetEmpty();
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = GENESIS_BLOCK_VERSION;
block.nTime = GENESIS_BLOCK_TIME;
block.nBits = POW_INITIAL_TARGET.GetCompact();
block.nNonce = GENESIS_BLOCK_NONCE;
printf("target : %s\n", POW_INITIAL_TARGET.getuint256().ToString().c_str());
printf("nBits : %08X\n", block.nBits);
printf("expected genesis hash : %s\n", GENESIS_HASH.ToString().c_str());
printf("true genesis hash : %s\n", block.GetHash().ToString().c_str());
// If genesis block hash does not match, then generate new genesis hash.
if (block.GetHash() != GENESIS_HASH || !CheckProofOfWork(block.GetHash(), block.nBits, false)) {
printf("\n");
printf("FATAL ERROR: The genesis block is invalid.\n");
printf("Please notify the coins maintainers at " COIN_BUGTRACKER ".\n");
printf("If you're working on an Altcoin, we suggest you to use the following parameters as new genesis (wait a bit):\n");
// This will figure out a valid hash and Nonce if you're
// creating a different genesis block:
while (!CheckProofOfWork(block.GetHash(), block.nBits, false)) {
if ((block.nNonce & 0xFFF) == 0)
printf("Trying nonce %08X and above...\n", block.nNonce);
++block.nNonce;
if (block.nNonce == 0) {
printf("NONCE WRAPPED, incrementing time\n");
++block.nTime;
}
}
printf("A matching block has been found, with the following parameters:\n");
printf(" - GENESIS_MERKLE_HASH : %s\n", block.hashMerkleRoot.ToString().c_str());
printf(" - GENESIS_HASH : %s\n", block.GetHash().ToString().c_str());
printf(" - GENESIS_TIME : %u\n", block.nTime);
printf(" - GENESIS_NONCE : %u\n", block.nNonce);
std::exit( 1 );
}
//// debug print
assert(block.hashMerkleRoot == GENESIS_MERKLE_HASH);
assert(block.GetHash() == GENESIS_HASH);
assert(block.CheckBlock());
// Start new block file
unsigned int nFile;
unsigned int nBlockPos;
if (!block.WriteToDisk(nFile, nBlockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(nFile, nBlockPos))
return error("LoadBlockIndex() : genesis block not accepted");
// ppcoin: initialize synchronized checkpoint
if (!Checkpoints::WriteSyncCheckpoint(GENESIS_HASH)) {
return error("LoadBlockIndex() : failed to init sync checkpoint");
}
}
// ppcoin: if checkpoint master key changed must reset sync-checkpoint
{
CTxDB txdb;
string strPubKey = "";
if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CHECKPOINT_PUBLIC_KEY)
{
// write checkpoint master key to db
txdb.TxnBegin();
if (!txdb.WriteCheckpointPubKey(CHECKPOINT_PUBLIC_KEY))
return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
if (!txdb.TxnCommit())
return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
if (!Checkpoints::ResetSyncCheckpoint())
return error("LoadBlockIndex() : failed to reset sync-checkpoint");
}
txdb.Close();
}
return true;
}
void PrintBlockTree()
{
// precompute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
printf("| ");
printf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
printf("| ");
printf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
printf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (%u,%u) %s %08lx %s mint %7s tx %d",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString().c_str(),
block.nBits,
DateTimeStrFormat(block.GetBlockTime()).c_str(),
FormatMoney(pindex->nMint).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main timechain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
map<uint256, CAlert> mapAlerts;
CCriticalSection cs_mapAlerts;
static string strMintMessage = _("Warning: Minting suspended due to locked wallet.");
static string strMintWarning;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
// ppcoin: wallet lock warning for minting
if (strMintWarning != "")
{
nPriority = 0;
strStatusBar = strMintWarning;
}
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// ppcoin: if detected invalid checkpoint enter safe mode
if (Checkpoints::hashInvalidCheckpoint != 0)
{
nPriority = 3000;
strStatusBar = strRPC = "Warning: An invalid checkpoint has been found! Displayed transactions may not be correct! You may need to upgrade, and/or notify developers of the issue.";
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
if (nPriority > 1000)
{
strRPC = strStatusBar; // ppcoin: safe mode for high alert
}
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
bool CAlert::ProcessAlert()
{
if (!CheckSignature())
return false;
if (!IsInEffect())
return false;
{
LOCK(cs_mapAlerts);
// Cancel previous alerts
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
{
const CAlert& alert = (*mi).second;
if (Cancels(alert))
{
printf("cancelling alert %d\n", alert.nID);
mapAlerts.erase(mi++);
}
else if (!alert.IsInEffect())
{
printf("expiring alert %d\n", alert.nID);
mapAlerts.erase(mi++);
}
else
mi++;
}
// Check if this alert has been cancelled
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.Cancels(*this))
{
printf("alert already cancelled by %d\n", alert.nID);
return false;
}
}
// Add to mapAlerts
mapAlerts.insert(make_pair(GetHash(), *this));
}
printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
MainFrameRepaint();
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
{
LOCK(mempool.cs);
txInMap = (mempool.exists(inv.hash));
}
return txInMap ||
mapOrphanTransactions.count(inv.hash) ||
txdb.ContainsTx(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug) {
printf("%s ", DateTimeStrFormat(GetTime()).c_str());
printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
}
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64 nTime;
CAddress addrMe;
CAddress addrFrom;
uint64 nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PROTO_VERSION)
{
// Since February 20, 2012, the protocol is initiated at version 209,
// and earlier versions are no longer supported
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
pfrom->fDisconnect = true;
return true;
}
// ppcoin: record my external IP reported by peer
if (addrFrom.IsRoutable() && addrMe.IsRoutable())
addrSeenByPeer = addrMe;
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() &&
!IsInitialBlockDownload())
{
CAddress addr(addrLocalHost);
addr.nTime = GetAdjustedTime();
pfrom->PushAddress(addr);
}
// Get recent addresses
if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Ask the first connected node for block updates
static int nAskedForBlocks = 0;
if (!pfrom->fClient &&
(pfrom->nVersion < NOBLKS_VERSION_START ||
pfrom->nVersion >= NOBLKS_VERSION_END))
{
nAskedForBlocks++;
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
// ppcoin: relay sync-checkpoint
{
LOCK(Checkpoints::cs_hashSyncCheckpoint);
if (!Checkpoints::checkpointMessage.IsNull())
Checkpoints::checkpointMessage.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
cPeerBlockCounts.input(pfrom->nStartingHeight);
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %d", vAddr.size());
}
// Store the new addresses
int64 nNow = GetAdjustedTime();
int64 nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
if (fShutdown)
return true;
// ignore IPv6 for now, since it isn't implemented anyway
if (!addr.IsIPv4())
continue;
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
int64 hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = 2;
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
}
addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > 50000)
{
pfrom->Misbehaving(20);
return error("message inv size() = %d", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
CTxDB txdb("r");
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
if (fShutdown)
return true;
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(txdb, inv);
if (fDebug)
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave)
{
pfrom->AskFor(inv);
}
else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
{
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
}
else if (nInv == nLastBlock)
{
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
std::vector<CInv> vGetData(1,inv);
pfrom->PushGetBlocks(mapBlockIndex.at(inv.hash), uint256(0));
if (fDebug)
{
printf("force request: %s\n", inv.ToString().c_str());
}
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > 50000)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %d", vInv.size());
}
BOOST_FOREACH(const CInv& inv, vInv)
{
if (fShutdown)
return true;
printf("received getdata for: %s\n", inv.ToString().c_str());
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
pfrom->PushMessage("block", block);
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
// ppcoin: send latest proof-of-work block to allow the
// download node to accept as orphan (proof-of-stake
// block might be rejected by stake connection check)
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end())
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
}
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500 + locator.GetDistanceBack();
unsigned int nBytes = 0;
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
// ppcoin: tell downloading node about the latest block if it's
// without risk being rejected due to stake connection check
if (hashStop != hashBestChain && pindex->GetBlockTime() + STAKE_MIN_AGE > pindexBest->GetBlockTime())
pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
CBlock block;
block.ReadFromDisk(pindex, true);
nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CDataStream vMsg(vRecv);
CTxDB txdb("r");
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
{
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const CDataStream& vMsg = *((*mi).second);
CTransaction tx;
CDataStream(vMsg) >> tx;
CInv inv(MSG_TX, tx.GetHash());
bool fMissingInputs2 = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
}
else if (!fMissingInputs2)
{
// invalid orphan
vEraseQueue.push_back(inv.hash);
printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(vMsg);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_BLOCK_ORPHAN_TX);
if (nEvicted > 0)
printf("mapOrphan overflow, removed %u tx\n", nEvicted);
}
if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
}
else if (strCommand == "block")
{
CBlock block;
vRecv >> block;
printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
// block.print();
CInv inv(MSG_BLOCK, block.GetHash());
pfrom->AddInventoryKnown(inv);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
else if (strCommand == "getaddr")
{
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr);
}
else if (strCommand == "checkorder")
{
uint256 hashReply;
vRecv >> hashReply;
if (!GetBoolArg("-allowreceivebyip"))
{
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
return true;
}
CWalletTx order;
vRecv >> order;
/// we have a chance to check the order here
// Keep giving the same key to the same ip until they use it
if (!mapReuseKey.count(pfrom->addr))
pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
// Send back approval of order and pubkey to use
CScript scriptPubKey;
scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
}
else if (strCommand == "reply")
{
uint256 hashReply;
vRecv >> hashReply;
CRequestTracker tracker;
{
LOCK(pfrom->cs_mapRequests);
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
if (mi != pfrom->mapRequests.end())
{
tracker = (*mi).second;
pfrom->mapRequests.erase(mi);
}
}
if (!tracker.IsNull())
tracker.fn(tracker.param1, vRecv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64 nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "alert")
{
CAlert alert;
vRecv >> alert;
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alert.GetHash());
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
}
else if (strCommand == "checkpoint")
{
CSyncCheckpoint checkpoint;
vRecv >> checkpoint;
if (checkpoint.ProcessSyncCheckpoint(pfrom))
{
// Relay
pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
bool ProcessMessages(CNode* pfrom)
{
CDataStream& vRecv = pfrom->vRecv;
if (vRecv.empty())
return true;
//if (fDebug)
// printf("ProcessMessages(%u bytes)\n", vRecv.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
unsigned char pchMessageStart[4];
GetMessageStart(pchMessageStart);
static int64 nTimeLastPrintMessageStart = 0;
if (fDebug && GetBoolArg("-printmessagestart") && nTimeLastPrintMessageStart + 30 < GetAdjustedTime())
{
string strMessageStart((const char *)pchMessageStart, sizeof(pchMessageStart));
vector<unsigned char> vchMessageStart(strMessageStart.begin(), strMessageStart.end());
printf("ProcessMessages : AdjustedTime=%"PRI64d" MessageStart=%s\n", GetAdjustedTime(), HexStr(vchMessageStart).c_str());
nTimeLastPrintMessageStart = GetAdjustedTime();
}
INFINITE_LOOP
{
// Safe guards to prevent the node to ignore a requested shutdown
// in case of long processing
if (fRequestShutdown)
{
StartShutdown();
return true;
}
// Scan for message start
CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
if (vRecv.end() - pstart < nHeaderSize)
{
if ((int)vRecv.size() > nHeaderSize)
{
printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
}
break;
}
if (pstart - vRecv.begin() > 0)
printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
vRecv.erase(vRecv.begin(), pstart);
// Read header
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> hdr;
if (!hdr.IsValid())
{
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
if (nMessageSize > MAX_SIZE)
{
printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
continue;
}
if (nMessageSize > vRecv.size())
{
// Rewind and wait for rest of message
vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
break;
}
// Checksum
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Copy message to its own buffer
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
vRecv.ignore(nMessageSize);
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
fRet = ProcessMessage(pfrom, strCommand, vMsg);
}
if (fShutdown)
return true;
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from underlength message on vRecv
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from overlong size
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
}
vRecv.Compact();
return true;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
// Keep-alive ping. We send a nonce of zero because we don't use it anywhere
// right now.
if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
uint64 nonce = 0;
if (pto->nVersion > BIP0031_VERSION)
pto->PushMessage("ping", nonce);
else
pto->PushMessage("ping");
}
// Resend wallet transactions that haven't gotten in a block yet
ResendWalletTransactions();
// Address refresh broadcast
static int64 nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable())
{
CAddress addr(addrLocalHost);
addr.nTime = GetAdjustedTime();
pnode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
// always trickle our own transactions
if (!fTrickleWait)
{
CWalletTx wtx;
if (GetTransaction(inv.hash, wtx))
if (wtx.fFromMe)
fTrickleWait = true;
}
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64 nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(txdb, inv))
{
printf("sending getdata: %s\n", inv.ToString().c_str());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
}
mapAlreadyAskedFor[inv] = nNow;
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
}
};
uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;
int64 nLastCoinStakeSearchInterval = 0;
// CreateNewBlock:
// fProofOfStake: try (best effort) to make a proof-of-stake block
CBlock* CreateNewBlock(CReserveKey& reservekey, CWallet* pwallet, bool fProofOfStake)
{
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// ppcoin: if coinstake available add coinstake tx
static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
CBlockIndex* pindexPrev = pindexBest;
if (fProofOfStake) // attemp to find a coinstake
{
pblock->nBits = GetNextTargetRequired(pindexPrev, true);
CTransaction txCoinStake;
int64 nSearchTime = txCoinStake.nTime; // search to current time
if (nSearchTime > nLastCoinStakeSearchTime)
{
if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
{
if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT))
{ // make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
pblock->vtx[0].vout[0].SetEmpty();
pblock->vtx[0].nTime = txCoinStake.nTime;
pblock->vtx.push_back(txCoinStake);
}
}
nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
nLastCoinStakeSearchTime = nSearchTime;
}
}
pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
// Collect memory pool transactions into the block
int64 nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
multimap<double, CTransaction*> mapPriority;
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
continue;
COrphan* porphan = NULL;
double dPriority = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
continue;
}
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
// Read block header
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
if (fDebug && GetBoolArg("-printpriority"))
printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
}
// Priority is sum(valuein * age) / txsize
dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (porphan)
porphan->dPriority = dPriority;
else
mapPriority.insert(make_pair(-dPriority, &(*mi).second));
if (fDebug && GetBoolArg("-printpriority"))
{
printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
if (porphan)
porphan->print();
printf("\n");
}
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64 nBlockSize = 1000;
uint64 nBlockTx = 0;
int nBlockSigOps = 100;
while (!mapPriority.empty())
{
// Take highest priority transaction off priority queue
CTransaction& tx = *(*mapPriority.begin()).second;
mapPriority.erase(mapPriority.begin());
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Timestamp limit
if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
continue;
// ppcoin: simplify transaction fee - allow free = false
int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
if (fDebug && GetBoolArg("-printpriority")) {
printf("CreateNewBlock(): total size %lu\n", nBlockSize);
}
}
if (pblock->IsProofOfWork())
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight);
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
if (pblock->IsProofOfStake())
pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT);
if (pblock->IsProofOfWork())
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Prebuild hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hash = pblock->GetHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
printf("Hash: %s\nTarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
if (hash > hashTarget && pblock->IsProofOfWork())
return error("BitcoinMiner : proof-of-work not meeting target");
//// debug print
printf("BitcoinMiner:\n");
printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("%s ", DateTimeStrFormat(GetTime()).c_str());
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("BitcoinMiner : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("BitcoinMiner : ProcessBlock, block not accepted");
}
return true;
}
void static ThreadBitcoinMiner(void* parg);
bool fStaking = true;
static bool fGenerateBitcoins = false;
static bool fLimitProcessors = false;
static int nLimitProcessors = -1;
bool BitcoinMiner(CWallet *pwallet, bool fProofOfStake, uint256 * minedBlock, uint64 nTimeout)
{
printf("CPUMiner started for proof-of-%s (%d)\n", fProofOfStake? "stake" : "work",
vnThreadsRunning[fProofOfStake? THREAD_MINTER : THREAD_MINER]);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
uint64 nStartTime = GetTime();
// Each thread has its own key and counter
CReserveKey reservekey(pwallet);
unsigned int nExtraNonce = 0;
while (minedBlock || fGenerateBitcoins || fProofOfStake)
{
if (fShutdown || (fProofOfStake && !fStaking))
return false;
if (nTimeout && (GetTime() - nStartTime > nTimeout))
return false;
while (vNodes.empty() || IsInitialBlockDownload())
{
Sleep(1000);
if (fShutdown || (fProofOfStake && !fStaking))
return false;
if (!minedBlock && (!fGenerateBitcoins && !fProofOfStake))
return false;
}
while (pwallet->IsLocked())
{
strMintWarning = strMintMessage;
Sleep(1000);
}
strMintWarning.clear();
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrev = pindexBest;
auto_ptr<CBlock> pblock(CreateNewBlock(reservekey, pwallet, fProofOfStake));
if (!pblock.get()) return false;
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
if (fProofOfStake)
{
// ppcoin: if proof-of-stake block found then process block
if (pblock->IsProofOfStake())
{
if (!pblock->SignBlock(*pwalletMain))
{
strMintWarning = strMintMessage;
continue;
}
strMintWarning.clear();
printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
SetThreadPriority(THREAD_PRIORITY_NORMAL);
bool fSucceeded = CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
if (fSucceeded && minedBlock)
{
*minedBlock = pblock->GetHash();
return true;
}
}
Sleep(500);
continue;
}
printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
//
// Search
//
int64 nStart = GetTime();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
INFINITE_LOOP
{
unsigned int nHashesDone = 0;
pblock->nNonce = 0;
INFINITE_LOOP
{
if (pblock->GetHash() <= hashTarget)
break;
pblock->nNonce += 1;
nHashesDone += 1;
if ((pblock->nNonce & 0xFFFF) == 0)
break;
}
// Check if something found
if (pblock->GetHash() <= hashTarget)
{
if (!pblock->SignBlock(*pwalletMain))
{
strMintWarning = strMintMessage;
break;
}
else
{
strMintWarning = "";
}
SetThreadPriority(THREAD_PRIORITY_NORMAL);
bool fSucceeded = CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
if (fSucceeded && minedBlock)
{
*minedBlock = pblock->GetHash();
return true;
}
break;
}
// Meter hashes/sec
static int64 nHashCounter;
if (nHPSTimerStart == 0)
{
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
}
else
{
nHashCounter += nHashesDone;
}
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
static CCriticalSection cs;
{
LOCK(cs);
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
static int64 nLogTime;
if (GetTime() - nLogTime > 30 * 60)
{
nLogTime = GetTime();
printf("%s ", DateTimeStrFormat(GetTime()).c_str());
printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
}
}
}
}
// Check for stop or if block needs to be rebuilt
if (fShutdown || (fProofOfStake && !fStaking))
return false;
if (!minedBlock && !fGenerateBitcoins)
return false;
if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
return false;
if (vNodes.empty())
break;
if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break;
if (pindexPrev != pindexBest)
break;
// Update nTime every few seconds
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - MAX_CLOCK_DRIFT);
pblock->UpdateTime(pindexPrev);
if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + MAX_CLOCK_DRIFT)
{
break; // need to update coinbase timestamp
}
}
}
return false;
}
void static ThreadBitcoinMiner(void* parg)
{
CWallet* pwallet = (CWallet*)parg;
try
{
vnThreadsRunning[THREAD_MINER]++;
BitcoinMiner(pwallet, false);
vnThreadsRunning[THREAD_MINER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(&e, "ThreadBitcoinMiner()");
} catch (...) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(NULL, "ThreadBitcoinMiner()");
}
nHPSTimerStart = 0;
if (vnThreadsRunning[THREAD_MINER] == 0)
dHashesPerSec = 0;
printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
}
void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
{
fGenerateBitcoins = fGenerate;
nLimitProcessors = GetArg("-genproclimit", -1);
if (nLimitProcessors == 0)
fGenerateBitcoins = false;
fLimitProcessors = (nLimitProcessors != -1);
if (fGenerate)
{
int nProcessors = boost::thread::hardware_concurrency();
printf("%d processors\n", nProcessors);
if (nProcessors < 1)
nProcessors = 1;
if (fLimitProcessors && nProcessors > nLimitProcessors)
nProcessors = nLimitProcessors;
int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
printf("Starting %d BitcoinMiner threads\n", nAddThreads);
for (int i = 0; i < nAddThreads; i++)
{
if (!CreateThread(ThreadBitcoinMiner, pwallet))
printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
Sleep(10);
}
}
}
| Magicking/neucoin | src/main.cpp | C++ | mit | 146,265 |
'use strict';
console.log('TESTTTT');
var mean = require('meanio');
exports.render = function (req, res) {
function isAdmin() {
return req.user && req.user.roles.indexOf('admin') !== -1;
}
// Send some basic starting info to the view
res.render('index', {
user: req.user ? {
name: req.user.name,
_id: req.user._id,
username: req.user.username,
roles: req.user.roles
} : {},
modules: 'ho',
motti: 'motti is cool',
isAdmin: 'motti',
adminEnabled: isAdmin() && mean.moduleEnabled('mean-admin')
});
};
| mottihoresh/nodarium-web | packages/custom/nodarium/server/controllers/index.js | JavaScript | mit | 627 |
/* concatenated from client/src/app/js/globals.js */
(function () {
if (!window.console) {
window.console = {};
}
var m = [
"log", "info", "warn", "error", "debug", "trace", "dir", "group",
"groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd",
"dirxml", "assert", "count", "markTimeline", "timeStamp", "clear"
];
for (var i = 0; i < m.length; i++) {
if (!window.console[m[i]]) {
window.console[m[i]] = function() {};
}
}
_.mixin({
compactObject: function(o) {
_.each(o, function(v, k) {
if(!v) {
delete o[k];
}
});
return o;
}
});
})();
/* concatenated from client/src/app/js/app.js */
const mainPages = {
HOME: "/",
WALKS: "/walks",
SOCIAL: "/social",
JOIN_US: "/join-us",
CONTACT_US: "/contact-us",
COMMITTEE: "/committee",
ADMIN: "/admin",
HOW_TO: "/how-to"
};
angular.module("ekwgApp", [
"btford.markdown",
"ngRoute",
"ngSanitize",
"ui.bootstrap",
"angularModalService",
"btford.markdown",
"mongolabResourceHttp",
"ngAnimate",
"ngCookies",
"ngFileUpload",
"ngSanitize",
"ui.bootstrap",
"ui.select",
"angular-logger",
"ezfb",
"ngCsv"])
.constant("MONGOLAB_CONFIG", {
trimErrorMessage: false,
baseUrl: "/databases/",
database: "ekwg"
})
.constant("AUDIT_CONFIG", {
auditSave: true,
})
.constant("PAGE_CONFIG", {
mainPages: mainPages
})
.config(["$compileProvider", function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|tel):/);
}])
.constant("MAILCHIMP_APP_CONSTANTS", {
allowSendCampaign: true,
apiServer: "https://us3.admin.mailchimp.com"
})
.config(["$locationProvider", function ($locationProvider) {
$locationProvider.hashPrefix("");
}])
.config(["$routeProvider", "uiSelectConfig", "uibDatepickerConfig", "uibDatepickerPopupConfig", "logEnhancerProvider", function ($routeProvider, uiSelectConfig, uibDatepickerConfig, uibDatepickerPopupConfig, logEnhancerProvider) {
uiSelectConfig.theme = "bootstrap";
uiSelectConfig.closeOnSelect = false;
$routeProvider
.when(mainPages.ADMIN + "/expenseId/:expenseId", {
controller: "AdminController",
templateUrl: "partials/admin/admin.html",
title: "expenses"
})
.when(mainPages.ADMIN + "/:area?", {
controller: "AdminController",
templateUrl: "partials/admin/admin.html",
title: "admin"
})
.when(mainPages.COMMITTEE + "/committeeFileId/:committeeFileId", {
controller: "CommitteeController", templateUrl: "partials/committee/committee.html", title: "AGM and committee"
})
.when(mainPages.COMMITTEE, {
controller: "CommitteeController", templateUrl: "partials/committee/committee.html", title: "AGM and committee"
})
.when(mainPages.HOW_TO, {
controller: "HowToController",
templateUrl: "partials/howTo/how-to.html",
title: "How-to"
})
.when("/image-editor/:imageSource", {
controller: "ImageEditController", templateUrl: "partials/imageEditor/image-editor.html", title: "image editor"
})
.when(mainPages.JOIN_US, {
controller: "HomeController", templateUrl: "partials/joinUs/join-us.html", title: "join us"
})
.when("/letterhead/:firstPart?/:secondPart", {
controller: "LetterheadController", templateUrl: "partials/letterhead/letterhead.html", title: "letterhead"
})
.when(mainPages.CONTACT_US, {
controller: "ContactUsController", templateUrl: "partials/contactUs/contact-us.html", title: "contact us"
})
.when("/links", {redirectTo: mainPages.CONTACT_US})
.when(mainPages.SOCIAL + "/socialEventId/:socialEventId", {
controller: "SocialEventsController", templateUrl: "partials/socialEvents/social.html", title: "social"
})
.when(mainPages.SOCIAL + "/:area?", {
controller: "SocialEventsController", templateUrl: "partials/socialEvents/social.html", title: "social"
})
.when(mainPages.WALKS + "/walkId/:walkId", {
controller: "WalksController", templateUrl: "partials/walks/walks.html", title: "walks"
})
.when(mainPages.WALKS + "/:area?", {
controller: "WalksController", templateUrl: "partials/walks/walks.html", title: "walks"
})
.when(mainPages.HOME, {
controller: "HomeController", templateUrl: "partials/home/home.html", title: "home"
})
.when("/set-password/:passwordResetId", {
controller: "AuthenticationModalsController",
templateUrl: "partials/home/home.html"
})
.otherwise({
controller: "AuthenticationModalsController",
templateUrl: "partials/home/home.html"
});
uibDatepickerConfig.startingDay = 1;
uibDatepickerConfig.showWeeks = false;
uibDatepickerPopupConfig.datepickerPopup = "dd-MMM-yyyy";
uibDatepickerPopupConfig.formatDay = "dd";
logEnhancerProvider.datetimePattern = "hh:mm:ss";
logEnhancerProvider.prefixPattern = "%s - %s -";
}])
.run(["$log", "$rootScope", "$route", "URLService", "CommitteeConfig", "CommitteeReferenceData", function ($log, $rootScope, $route, URLService, CommitteeConfig, CommitteeReferenceData) {
var logger = $log.getInstance("App.run");
$log.logLevels["App.run"] = $log.LEVEL.OFF;
$rootScope.$on('$locationChangeStart', function (evt, absNewUrl, absOldUrl) {
});
$rootScope.$on("$locationChangeSuccess", function (event, newUrl, absOldUrl) {
if (!$rootScope.pageHistory) $rootScope.pageHistory = [];
$rootScope.pageHistory.push(URLService.relativeUrl(newUrl));
logger.info("newUrl", newUrl, "$rootScope.pageHistory", $rootScope.pageHistory);
});
$rootScope.$on("$routeChangeSuccess", function (currentRoute, previousRoute) {
$rootScope.title = $route.current.title;
});
CommitteeConfig.getConfig()
.then(function (config) {
angular.extend(CommitteeReferenceData, config.committee);
$rootScope.$broadcast("CommitteeReferenceDataReady", CommitteeReferenceData);
});
}]);
/* concatenated from client/src/app/js/admin.js */
angular.module('ekwgApp')
.controller('AdminController',
["$rootScope", "$scope", "LoggedInMemberService", function($rootScope, $scope, LoggedInMemberService) {
function setViewPriveleges() {
$scope.loggedIn = LoggedInMemberService.memberLoggedIn();
$scope.memberAdmin = LoggedInMemberService.allowMemberAdminEdits();
LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId');
}
setViewPriveleges();
$scope.$on('memberLoginComplete', function() {
setViewPriveleges();
});
$scope.$on('memberLogoutComplete', function() {
setViewPriveleges();
});
}]
);
/* concatenated from client/src/app/js/authenticationModalsController.js */
angular.module('ekwgApp')
.controller("AuthenticationModalsController", ["$log", "$scope", "URLService", "$location", "$routeParams", "AuthenticationModalsService", "LoggedInMemberService", function ($log, $scope, URLService, $location, $routeParams, AuthenticationModalsService, LoggedInMemberService) {
var logger = $log.getInstance("AuthenticationModalsController");
$log.logLevels["AuthenticationModalsController"] = $log.LEVEL.OFF;
var urlFirstSegment = URLService.relativeUrlFirstSegment();
logger.info("URLService.relativeUrl:", urlFirstSegment, "$routeParams:", $routeParams);
switch (urlFirstSegment) {
case "/login":
return AuthenticationModalsService.showLoginDialog();
case "/logout":
return LoggedInMemberService.logout();
case "/mailing-preferences":
if (LoggedInMemberService.memberLoggedIn()) {
return AuthenticationModalsService.showMailingPreferencesDialog(LoggedInMemberService.loggedInMember().memberId);
} else {
return URLService.setRoot();
}
case "/forgot-password":
return AuthenticationModalsService.showForgotPasswordModal();
case "/set-password":
return LoggedInMemberService.getMemberByPasswordResetId($routeParams.passwordResetId)
.then(function (member) {
logger.info("for $routeParams.passwordResetId", $routeParams.passwordResetId, "member", member);
if (_.isEmpty(member)) {
return AuthenticationModalsService.showResetPasswordFailedDialog();
} else {
return AuthenticationModalsService.showResetPasswordModal(member.userName)
}
});
default:
logger.warn(URLService.relativeUrl(), "doesnt match any of the supported urls");
return URLService.setRoot();
}
}]
);
/* concatenated from client/src/app/js/authenticationModalsService.js */
angular.module('ekwgApp')
.factory("AuthenticationModalsService", ["$log", "ModalService", "URLService", function ($log, ModalService, URLService) {
var logger = $log.getInstance("AuthenticationModalsService");
$log.logLevels["AuthenticationModalsService"] = $log.LEVEL.OFF;
function showForgotPasswordModal() {
logger.info('called showForgotPasswordModal');
ModalService.closeModals(true);
ModalService.showModal({
templateUrl: "partials/index/forgotten-password-dialog.html",
controller: "ForgotPasswordController",
preClose: function (modal) {
modal.element.modal('hide');
}
}).then(function (modal) {
logger.info('modal event with modal', modal);
modal.element.modal();
modal.close.then(function (result) {
logger.info('close event with result', result);
if (!result) URLService.navigateBackToLastMainPage();
});
}).catch(function (error) {
logger.warn("error happened:", error);
})
}
function showResetPasswordModal(userName, message) {
logger.info('called showResetPasswordModal for userName', userName);
ModalService.closeModals(true);
ModalService.showModal({
templateUrl: "partials/index/reset-password-dialog.html",
controller: "ResetPasswordController",
inputs: {userName: userName, message: message},
preClose: function (modal) {
modal.element.modal('hide');
}
}).then(function (modal) {
logger.info('modal event with modal', modal);
modal.element.modal();
modal.close.then(function (result) {
logger.info('showResetPasswordModal close event with result', result);
if (!result) URLService.navigateBackToLastMainPage();
});
})
}
function showLoginDialog() {
logger.info('called showLoginDialog');
ModalService.closeModals(true);
ModalService.showModal({
templateUrl: "partials/index/login-dialog.html",
controller: "LoginController",
preClose: function (modal) {
modal.element.modal('hide');
}
}).then(function (modal) {
logger.info('modal event with modal', modal);
modal.element.modal();
modal.close.then(function (result) {
logger.info('showLoginDialog close event with result', result);
if (!result) URLService.navigateBackToLastMainPage();
});
})
}
function showResetPasswordFailedDialog() {
logger.info('called showResetPasswordFailedDialog');
ModalService.closeModals(true);
ModalService.showModal({
templateUrl: "partials/index/reset-password-failed-dialog.html",
controller: "ResetPasswordFailedController",
preClose: function (modal) {
modal.element.modal('hide');
}
}).then(function (modal) {
logger.info('showResetPasswordFailedDialog modal event with modal', modal);
modal.element.modal();
modal.close.then(function (result) {
logger.info('showResetPasswordFailedDialog close event with result', result);
if (!result) URLService.navigateBackToLastMainPage();
});
})
}
function showMailingPreferencesDialog(memberId) {
logger.info('called showMailingPreferencesDialog');
ModalService.closeModals(true);
ModalService.showModal({
templateUrl: "partials/index/mailing-preferences-dialog.html",
controller: "MailingPreferencesController",
inputs: {memberId: memberId},
preClose: function (modal) {
modal.element.modal('hide');
}
}).then(function (modal) {
logger.info('showMailingPreferencesDialog modal event with modal', modal);
modal.element.modal();
modal.close.then(function (result) {
logger.info('close event with result', result);
if (!result) URLService.navigateBackToLastMainPage();
});
})
}
return {
showResetPasswordModal: showResetPasswordModal,
showResetPasswordFailedDialog: showResetPasswordFailedDialog,
showForgotPasswordModal: showForgotPasswordModal,
showLoginDialog: showLoginDialog,
showMailingPreferencesDialog: showMailingPreferencesDialog
}
}]);
/* concatenated from client/src/app/js/awsServices.js */
angular.module('ekwgApp')
.factory('AWSConfig', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) {
function getConfig() {
return $http.get('/aws/config').then(HTTPResponseService.returnResponse);
}
function awsPolicy(fileType, objectKey) {
return $http.get('/aws/s3Policy?mimeType=' + fileType + '&objectKey=' + objectKey).then(HTTPResponseService.returnResponse);
}
return {
getConfig: getConfig,
awsPolicy: awsPolicy
}
}])
.factory('EKWGFileUpload', ["$log", "AWSConfig", "NumberUtils", "Upload", function ($log, AWSConfig, NumberUtils, Upload) {
$log.logLevels['EKWGFileUpload'] = $log.LEVEL.OFF;
var logger = $log.getInstance('EKWGFileUpload');
var awsConfig;
AWSConfig.getConfig().then(function (config) {
awsConfig = config;
});
function onFileSelect(file, notify, objectKey) {
logger.debug(file, objectKey);
function generateFileNameData() {
return {
originalFileName: file.name,
awsFileName: NumberUtils.generateUid() + '.' + _.last(file.name.split('.'))
};
}
var fileNameData = generateFileNameData(), fileUpload = file;
fileUpload.progress = parseInt(0);
logger.debug('uploading fileNameData', fileNameData);
return AWSConfig.awsPolicy(file.type, objectKey)
.then(function (response) {
var s3Params = response;
var url = 'https://' + awsConfig.bucket + '.s3.amazonaws.com/';
return Upload.upload({
url: url,
method: 'POST',
data: {
'key': objectKey + '/' + fileNameData.awsFileName,
'acl': 'public-read',
'Content-Type': file.type,
'AWSAccessKeyId': s3Params.AWSAccessKeyId,
'success_action_status': '201',
'Policy': s3Params.s3Policy,
'Signature': s3Params.s3Signature
},
file: file
}).then(function (response) {
fileUpload.progress = parseInt(100);
if (response.status === 201) {
var data = xml2json.parser(response.data),
parsedData;
parsedData = {
location: data.postresponse.location,
bucket: data.postresponse.bucket,
key: data.postresponse.key,
etag: data.postresponse.etag
};
logger.debug('parsedData', parsedData);
return fileNameData;
} else {
notify.error('Upload Failed for file ' + fileNameData);
}
}, notify.error, function (evt) {
fileUpload.progress = parseInt(100.0 * evt.loaded / evt.total);
});
});
}
return {onFileSelect: onFileSelect};
}]);
/* concatenated from client/src/app/js/batchGeoServices.js */
angular.module('ekwgApp')
.factory('BatchGeoExportService', ["StringUtils", "DateUtils", "$filter", function(StringUtils, DateUtils, $filter) {
function exportWalksFileName() {
return 'batch-geo-walks-export-' + DateUtils.asMoment().format('DD-MMMM-YYYY-HH-mm') + '.csv'
}
function exportableWalks(walks) {
return _(walks).sortBy('walkDate');
}
function exportWalks(walks) {
return _.chain(walks)
.filter(filterWalk)
.sortBy('walkDate')
.last(250)
.map(walkToCsvRecord)
.value();
}
function filterWalk(walk) {
return _.has(walk, 'briefDescriptionAndStartPoint')
&& (_.has(walk, 'gridReference') || _.has(walk, 'postcode'));
}
function exportColumnHeadings() {
return [
"Walk Date",
"Start Time",
"Postcode",
"Contact Name/Email",
"Distance",
"Description",
"Longer Description",
"Grid Ref"
];
}
function walkToCsvRecord(walk) {
return {
"walkDate": walkDate(walk),
"startTime": walkStartTime(walk),
"postcode": walkPostcode(walk),
"displayName": contactDisplayName(walk),
"distance": walkDistanceMiles(walk),
"description": walkTitle(walk),
"longerDescription": walkDescription(walk),
"gridRef": walkGridReference(walk)
};
}
function walkTitle(walk) {
var walkDescription = [];
if (walk.includeWalkDescriptionPrefix) walkDescription.push(walk.walkDescriptionPrefix);
if (walk.briefDescriptionAndStartPoint) walkDescription.push(walk.briefDescriptionAndStartPoint);
return _.chain(walkDescription).map(replaceSpecialCharacters).value().join('. ');
}
function walkDescription(walk) {
return replaceSpecialCharacters(walk.longerDescription);
}
function asString(value) {
return value ? value : '';
}
function contactDisplayName(walk) {
return walk.displayName ? replaceSpecialCharacters(_.first(walk.displayName.split(' '))) : '';
}
function replaceSpecialCharacters(value) {
return value ? StringUtils.stripLineBreaks(value
.replace("’", "'")
.replace("é", "e")
.replace("’", "'")
.replace('…', '…')
.replace('–', '–')
.replace('’', '’')
.replace('“', '“')) : '';
}
function walkDistanceMiles(walk) {
return walk.distance ? String(parseFloat(walk.distance).toFixed(1)) : '';
}
function walkStartTime(walk) {
return walk.startTime ? DateUtils.asString(walk.startTime, 'HH mm', 'HH:mm') : '';
}
function walkGridReference(walk) {
return walk.gridReference ? walk.gridReference : '';
}
function walkPostcode(walk) {
return walk.postcode ? walk.postcode : '';
}
function walkDate(walk) {
return $filter('displayDate')(walk.walkDate);
}
return {
exportWalksFileName: exportWalksFileName,
exportWalks: exportWalks,
exportableWalks: exportableWalks,
exportColumnHeadings: exportColumnHeadings
}
}]);
/* concatenated from client/src/app/js/bulkUploadServices.js */
angular.module('ekwgApp')
.factory('MemberBulkUploadService', ["$log", "$q", "$filter", "MemberService", "MemberUpdateAuditService", "MemberBulkLoadAuditService", "ErrorMessageService", "EmailSubscriptionService", "DateUtils", "DbUtils", "MemberNamingService", function ($log, $q, $filter, MemberService, MemberUpdateAuditService, MemberBulkLoadAuditService, ErrorMessageService, EmailSubscriptionService, DateUtils, DbUtils, MemberNamingService) {
var logger = $log.getInstance('MemberBulkUploadService');
var noLogger = $log.getInstance('NoLogger');
$log.logLevels['MemberBulkUploadService'] = $log.LEVEL.OFF;
$log.logLevels['NoLogger'] = $log.LEVEL.OFF;
var RESET_PASSWORD = 'changeme';
function processMembershipRecords(file, memberBulkLoadServerResponse, members, notify) {
notify.setBusy();
var today = DateUtils.momentNowNoTime().valueOf();
var promises = [];
var memberBulkLoadResponse = memberBulkLoadServerResponse.data;
logger.debug('received', memberBulkLoadResponse);
return DbUtils.auditedSaveOrUpdate(new MemberBulkLoadAuditService(memberBulkLoadResponse))
.then(function (auditResponse) {
var uploadSessionId = auditResponse.$id();
return processBulkLoadResponses(promises, uploadSessionId);
});
function updateGroupMembersPreBulkLoadProcessing(promises) {
if (memberBulkLoadResponse.members && memberBulkLoadResponse.members.length > 1) {
notify.progress('Processing ' + members.length + ' members ready for bulk load');
_.each(members, function (member) {
if (member.receivedInLastBulkLoad) {
member.receivedInLastBulkLoad = false;
promises.push(DbUtils.auditedSaveOrUpdate(member, auditUpdateCallback(member), auditErrorCallback(member)));
}
});
return $q.all(promises).then(function () {
notify.progress('Marked ' + promises.length + ' out of ' + members.length + ' in preparation for update');
return promises;
});
} else {
return $q.when(promises);
}
}
function processBulkLoadResponses(promises, uploadSessionId) {
return updateGroupMembersPreBulkLoadProcessing(promises).then(function (updatedPromises) {
_.each(memberBulkLoadResponse.members, function (ramblersMember, recordIndex) {
createOrUpdateMember(uploadSessionId, recordIndex, ramblersMember, updatedPromises);
});
return $q.all(updatedPromises).then(function () {
logger.debug('performed total of', updatedPromises.length, 'audit or member updates');
return updatedPromises;
});
});
}
function auditUpdateCallback(member) {
return function (response) {
logger.debug('auditUpdateCallback for member:', member, 'response', response);
}
}
function auditErrorCallback(member, audit) {
return function (response) {
logger.warn('member save error for member:', member, 'response:', response);
if (audit) {
audit.auditErrorMessage = response;
}
}
}
function saveAndAuditMemberUpdate(promises, uploadSessionId, rowNumber, memberAction, changes, auditMessage, member) {
var audit = new MemberUpdateAuditService({
uploadSessionId: uploadSessionId,
updateTime: DateUtils.nowAsValue(),
memberAction: memberAction,
rowNumber: rowNumber,
changes: changes,
auditMessage: auditMessage
});
var qualifier = 'for membership ' + member.membershipNumber;
member.receivedInLastBulkLoad = true;
member.lastBulkLoadDate = DateUtils.momentNow().valueOf();
return DbUtils.auditedSaveOrUpdate(member, auditUpdateCallback(member), auditErrorCallback(member, audit))
.then(function (savedMember) {
if (savedMember) {
audit.memberId = savedMember.$id();
notify.success({title: 'Bulk member load ' + qualifier + ' was successful', message: auditMessage})
} else {
audit.member = member;
audit.memberAction = 'error';
logger.warn('member was not saved, so saving it to audit:', audit);
notify.warning({title: 'Bulk member load ' + qualifier + ' failed', message: auditMessage})
}
logger.debug('saveAndAuditMemberUpdate:', audit);
promises.push(audit.$save());
return promises;
});
}
function convertMembershipExpiryDate(ramblersMember) {
var dataValue = ramblersMember.membershipExpiryDate ? DateUtils.asValueNoTime(ramblersMember.membershipExpiryDate, 'DD/MM/YYYY') : ramblersMember.membershipExpiryDate;
logger.debug('ramblersMember', ramblersMember, 'membershipExpiryDate', ramblersMember.membershipExpiryDate, '->', DateUtils.displayDate(dataValue));
return dataValue;
}
function createOrUpdateMember(uploadSessionId, recordIndex, ramblersMember, promises) {
var memberAction;
ramblersMember.membershipExpiryDate = convertMembershipExpiryDate(ramblersMember);
ramblersMember.groupMember = !ramblersMember.membershipExpiryDate || ramblersMember.membershipExpiryDate >= today;
var member = _.find(members, function (member) {
var existingUserName = MemberNamingService.createUserName(ramblersMember);
var match = member.membershipNumber && member.membershipNumber.toString() === ramblersMember.membershipNumber;
if (!match && member.userName) {
match = member.userName === existingUserName;
}
noLogger.debug('match', !!(match),
'ramblersMember.membershipNumber', ramblersMember.membershipNumber,
'ramblersMember.userName', existingUserName,
'member.membershipNumber', member.membershipNumber,
'member.userName', member.userName);
return match;
});
if (member) {
EmailSubscriptionService.resetUpdateStatusForMember(member);
} else {
memberAction = 'created';
member = new MemberService();
member.userName = MemberNamingService.createUniqueUserName(ramblersMember, members);
member.displayName = MemberNamingService.createUniqueDisplayName(ramblersMember, members);
member.password = RESET_PASSWORD;
member.expiredPassword = true;
EmailSubscriptionService.defaultMailchimpSettings(member, true);
logger.debug('new member created:', member);
}
var updateAudit = {auditMessages: [], fieldsChanged: 0, fieldsSkipped: 0};
_.each([
{fieldName: 'membershipExpiryDate', writeDataIf: 'changed', type: 'date'},
{fieldName: 'membershipNumber', writeDataIf: 'changed', type: 'string'},
{fieldName: 'mobileNumber', writeDataIf: 'empty', type: 'string'},
{fieldName: 'email', writeDataIf: 'empty', type: 'string'},
{fieldName: 'firstName', writeDataIf: 'empty', type: 'string'},
{fieldName: 'lastName', writeDataIf: 'empty', type: 'string'},
{fieldName: 'postcode', writeDataIf: 'empty', type: 'string'},
{fieldName: 'groupMember', writeDataIf: 'not-revoked', type: 'boolean'}], function (field) {
changeAndAuditMemberField(updateAudit, member, ramblersMember, field)
});
DbUtils.removeEmptyFieldsIn(member);
logger.debug('saveAndAuditMemberUpdate -> member:', member, 'updateAudit:', updateAudit);
return saveAndAuditMemberUpdate(promises, uploadSessionId, recordIndex + 1, memberAction || (updateAudit.fieldsChanged > 0 ? 'updated' : 'skipped'), updateAudit.fieldsChanged, updateAudit.auditMessages.join(', '), member);
}
function changeAndAuditMemberField(updateAudit, member, ramblersMember, field) {
function auditValueForType(field, source) {
var dataValue = source[field.fieldName];
switch (field.type) {
case 'date':
return ($filter('displayDate')(dataValue) || '(none)');
case 'boolean':
return dataValue || false;
default:
return dataValue || '(none)';
}
}
var fieldName = field.fieldName;
var performMemberUpdate = false;
var auditQualifier = ' not overwritten with ';
var auditMessage;
var oldValue = auditValueForType(field, member);
var newValue = auditValueForType(field, ramblersMember);
if (field.writeDataIf === 'changed') {
performMemberUpdate = (oldValue !== newValue) && ramblersMember[fieldName];
} else if (field.writeDataIf === 'empty') {
performMemberUpdate = !member[fieldName];
} else if (field.writeDataIf === 'not-revoked') {
performMemberUpdate = newValue && (oldValue !== newValue) && !member.revoked;
} else if (field.writeDataIf) {
performMemberUpdate = newValue;
}
if (performMemberUpdate) {
auditQualifier = ' updated to ';
member[fieldName] = ramblersMember[fieldName];
updateAudit.fieldsChanged++;
}
if (oldValue !== newValue) {
if (!performMemberUpdate) updateAudit.fieldsSkipped++;
auditMessage = fieldName + ': ' + oldValue + auditQualifier + newValue;
}
if ((performMemberUpdate || (oldValue !== newValue)) && auditMessage) {
updateAudit.auditMessages.push(auditMessage);
}
}
}
return {
processMembershipRecords: processMembershipRecords,
}
}]);
/* concatenated from client/src/app/js/clipboardService.js */
angular.module('ekwgApp')
.factory('ClipboardService', ["$compile", "$rootScope", "$document", "$log", function ($compile, $rootScope, $document, $log) {
return {
copyToClipboard: function (element) {
var logger = $log.getInstance("ClipboardService");
$log.logLevels['ClipboardService'] = $log.LEVEL.OFF;
var copyElement = angular.element('<span id="clipboard-service-copy-id">' + element + '</span>');
var body = $document.find('body').eq(0);
body.append($compile(copyElement)($rootScope));
var ClipboardServiceElement = angular.element(document.getElementById('clipboard-service-copy-id'));
logger.debug(ClipboardServiceElement);
var range = document.createRange();
range.selectNode(ClipboardServiceElement[0]);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
logger.debug('Copying text command was ' + msg);
window.getSelection().removeAllRanges();
copyElement.remove();
}
}
}]);
/* concatenated from client/src/app/js/comitteeNotifications.js */
angular.module('ekwgApp')
.controller('CommitteeNotificationsController', ["$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "CommitteeReferenceData", "CommitteeQueryService", "committeeFile", "close", function ($window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams,
$location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService,
ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService,
MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, CommitteeReferenceData, CommitteeQueryService, committeeFile, close) {
var logger = $log.getInstance('CommitteeNotificationsController');
$log.logLevels['CommitteeNotificationsController'] = $log.LEVEL.OFF;
$scope.notify = {};
var notify = Notifier($scope.notify);
notify.setBusy();
$scope.members = [];
$scope.committeeFile = committeeFile;
$scope.roles = {signoff: CommitteeReferenceData.contactUsRolesAsArray(), replyTo: []};
$scope.committeeFileBaseUrl = ContentMetaDataService.baseUrl('committeeFiles');
function loggedOnRole() {
var memberId = LoggedInMemberService.loggedInMember().memberId;
var loggedOnRoleData = _(CommitteeReferenceData.contactUsRolesAsArray()).find(function (role) {
return role.memberId === memberId
});
logger.debug('loggedOnRole for', memberId, '->', loggedOnRoleData);
return loggedOnRoleData || {};
}
$scope.fromDateCalendar = {
open: function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.fromDateCalendar.opened = true;
}
};
$scope.toDateCalendar = {
open: function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.toDateCalendar.opened = true;
}
};
$scope.populateGroupEvents = function () {
notify.setBusy();
populateGroupEvents().then(function () {
notify.clearBusy();
return true;
})
};
function populateGroupEvents() {
return CommitteeQueryService.groupEvents($scope.userEdits.groupEvents)
.then(function (events) {
$scope.userEdits.groupEvents.events = events;
logger.debug('groupEvents', events);
return events;
});
}
$scope.changeGroupEventSelection = function (groupEvent) {
groupEvent.selected = !groupEvent.selected;
};
$scope.notification = {
editable: {
text: '',
signoffText: 'If you have any questions about the above, please don\'t hesitate to contact me.\n\nBest regards,',
},
destinationType: 'committee',
includeSignoffText: true,
addresseeType: 'Hi *|FNAME|*,',
addingNewFile: false,
recipients: [],
groupEvents: function () {
return _.filter($scope.userEdits.groupEvents.events, function (groupEvent) {
logger.debug('notification.groupEvents ->', groupEvent);
return groupEvent.selected;
});
},
signoffAs: {
include: true,
value: loggedOnRole().type || 'secretary'
},
includeDownloadInformation: $scope.committeeFile,
title: 'Committee Notification',
text: function () {
return $filter('lineFeedsToBreaks')($scope.notification.editable.text);
},
signoffText: function () {
return $filter('lineFeedsToBreaks')($scope.notification.editable.signoffText);
}
};
if ($scope.committeeFile) {
$scope.notification.title = $scope.committeeFile.fileType;
$scope.notification.editable.text = 'This is just a quick note to let you know in case you are interested, that I\'ve uploaded a new file to the EKWG website. The file information is as follows:';
}
logger.debug('initialised on open: committeeFile', $scope.committeeFile, ', roles', $scope.roles);
logger.debug('initialised on open: notification ->', $scope.notification);
$scope.userEdits = {
sendInProgress: false,
cancelled: false,
groupEvents: {
events: [],
fromDate: DateUtils.momentNowNoTime().valueOf(),
toDate: DateUtils.momentNowNoTime().add(2, 'weeks').valueOf(),
includeContact: true,
includeDescription: true,
includeLocation: true,
includeWalks: true,
includeSocialEvents: true,
includeCommitteeEvents: true
},
allGeneralSubscribedList: function () {
return _.chain($scope.members)
.filter(MemberService.filterFor.GENERAL_MEMBERS_SUBSCRIBED)
.map(toSelectGeneralMember).value();
},
allWalksSubscribedList: function () {
return _.chain($scope.members)
.filter(MemberService.filterFor.WALKS_MEMBERS_SUBSCRIBED)
.map(toSelectWalksMember).value();
},
allSocialSubscribedList: function () {
return _.chain($scope.members)
.filter(MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED)
.map(toSelectSocialMember).value();
},
allCommitteeList: function () {
return _.chain($scope.members)
.filter(MemberService.filterFor.COMMITTEE_MEMBERS)
.map(toSelectGeneralMember).value();
},
replyToRole: function () {
return _($scope.roles.replyTo).find(function (role) {
return role.type === $scope.socialEvent.notification.items.replyTo.value;
});
},
notReady: function () {
return $scope.members.length === 0 || $scope.userEdits.sendInProgress || ($scope.notification.recipients.length === 0 && $scope.notification.destinationType === 'custom');
}
};
function toSelectGeneralMember(member) {
var memberGrouping;
var order;
if (member.groupMember && member.mailchimpLists.general.subscribed) {
memberGrouping = 'Subscribed to general emails';
order = 0;
} else if (member.groupMember && !member.mailchimpLists.general.subscribed) {
memberGrouping = 'Not subscribed to general emails';
order = 1;
} else if (!member.groupMember) {
memberGrouping = 'Not a group member';
order = 2;
} else {
memberGrouping = 'Unexpected state';
order = 3;
}
return {
id: member.$id(),
order: order,
memberGrouping: memberGrouping,
text: $filter('fullNameWithAlias')(member)
};
}
function toSelectWalksMember(member) {
var memberGrouping;
var order;
if (member.groupMember && member.mailchimpLists.walks.subscribed) {
memberGrouping = 'Subscribed to walks emails';
order = 0;
} else if (member.groupMember && !member.mailchimpLists.walks.subscribed) {
memberGrouping = 'Not subscribed to walks emails';
order = 1;
} else if (!member.groupMember) {
memberGrouping = 'Not a group member';
order = 2;
} else {
memberGrouping = 'Unexpected state';
order = 3;
}
return {
id: member.$id(),
order: order,
memberGrouping: memberGrouping,
text: $filter('fullNameWithAlias')(member)
};
}
function toSelectSocialMember(member) {
var memberGrouping;
var order;
if (member.groupMember && member.mailchimpLists.socialEvents.subscribed) {
memberGrouping = 'Subscribed to social emails';
order = 0;
} else if (member.groupMember && !member.mailchimpLists.socialEvents.subscribed) {
memberGrouping = 'Not subscribed to social emails';
order = 1;
} else if (!member.groupMember) {
memberGrouping = 'Not a group member';
order = 2;
} else {
memberGrouping = 'Unexpected state';
order = 3;
}
return {
id: member.$id(),
order: order,
memberGrouping: memberGrouping,
text: $filter('fullNameWithAlias')(member)
};
}
$scope.editAllEKWGRecipients = function () {
$scope.notification.destinationType = 'custom';
$scope.notification.campaignId = campaignIdFor('general');
$scope.notification.list = 'general';
$scope.notification.recipients = $scope.userEdits.allGeneralSubscribedList();
$scope.campaignIdChanged();
};
$scope.editAllWalksRecipients = function () {
$scope.notification.destinationType = 'custom';
$scope.notification.campaignId = campaignIdFor('walks');
$scope.notification.list = 'walks';
$scope.notification.recipients = $scope.userEdits.allWalksSubscribedList();
$scope.campaignIdChanged();
};
$scope.editAllSocialRecipients = function () {
$scope.notification.destinationType = 'custom';
$scope.notification.campaignId = campaignIdFor('socialEvents');
$scope.notification.list = 'socialEvents';
$scope.notification.recipients = $scope.userEdits.allSocialSubscribedList();
$scope.campaignIdChanged();
};
$scope.editCommitteeRecipients = function () {
$scope.notification.destinationType = 'custom';
$scope.notification.campaignId = campaignIdFor('committee');
$scope.notification.list = 'general';
$scope.notification.recipients = $scope.userEdits.allCommitteeList();
$scope.campaignIdChanged();
};
$scope.clearRecipientsForCampaignOfType = function (campaignType) {
$scope.notification.customCampaignType = campaignType;
$scope.notification.campaignId = campaignIdFor(campaignType);
$scope.notification.list = 'general';
$scope.notification.recipients = [];
$scope.campaignIdChanged();
};
$scope.fileUrl = function () {
return $scope.committeeFile && $scope.committeeFile.fileNameData ? URLService.baseUrl() + $scope.committeeFileBaseUrl + '/' + $scope.committeeFile.fileNameData.awsFileName : '';
};
$scope.fileTitle = function () {
return $scope.committeeFile ? DateUtils.asString($scope.committeeFile.eventDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + $scope.committeeFile.fileNameData.title : '';
};
function campaignIdFor(campaignType) {
switch (campaignType) {
case 'committee':
return $scope.config.mailchimp.campaigns.committee.campaignId;
case 'general':
return $scope.config.mailchimp.campaigns.newsletter.campaignId;
case 'socialEvents':
return $scope.config.mailchimp.campaigns.socialEvents.campaignId;
case 'walks':
return $scope.config.mailchimp.campaigns.walkNotification.campaignId;
default:
return $scope.config.mailchimp.campaigns.committee.campaignId;
}
}
function campaignInfoForCampaign(campaignId) {
return _.chain($scope.config.mailchimp.campaigns)
.map(function (data, campaignType) {
var campaignData = _.extend({campaignType: campaignType}, data);
logger.debug('campaignData for', campaignType, '->', campaignData);
return campaignData;
}).find({campaignId: campaignId})
.value();
}
$scope.campaignIdChanged = function () {
var infoForCampaign = campaignInfoForCampaign($scope.notification.campaignId);
logger.debug('for campaignId', $scope.notification.campaignId, 'infoForCampaign', infoForCampaign);
if (infoForCampaign) {
$scope.notification.title = infoForCampaign.name;
}
};
$scope.confirmSendNotification = function (dontSend) {
$scope.userEdits.sendInProgress = true;
var campaignName = $scope.notification.title;
notify.setBusy();
return $q.when(templateFor('partials/committee/committee-notification.html'))
.then(renderTemplateContent)
.then(populateContentSections)
.then(sendEmailCampaign)
.then(notifyEmailSendComplete)
.catch(handleNotificationError);
function templateFor(template) {
return $templateRequest($sce.getTrustedResourceUrl(template))
}
function handleNotificationError(errorResponse) {
$scope.userEdits.sendInProgress = false;
notify.clearBusy();
notify.error({
title: 'Your notification could not be sent',
message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '')
});
}
function renderTemplateContent(templateData) {
var task = $q.defer();
var templateFunction = $compile(templateData);
var templateElement = templateFunction($scope);
$timeout(function () {
$scope.$digest();
task.resolve(templateElement.html());
});
return task.promise;
}
function populateContentSections(notificationText) {
logger.debug('populateContentSections -> notificationText', notificationText);
return {
sections: {
notification_text: notificationText
}
};
}
function sendEmailCampaign(contentSections) {
notify.progress(dontSend ? ('Preparing to complete ' + campaignName + ' in Mailchimp') : ('Sending ' + campaignName));
return MailchimpConfig.getConfig()
.then(function (config) {
var replyToRole = $scope.notification.signoffAs.value || 'secretary';
logger.debug('replyToRole', replyToRole);
var members;
var list = $scope.notification.list;
var otherOptions = {
from_name: CommitteeReferenceData.contactUsField(replyToRole, 'fullName'),
from_email: CommitteeReferenceData.contactUsField(replyToRole, 'email'),
list_id: config.mailchimp.lists[list]
};
logger.debug('Sending ' + campaignName, 'with otherOptions', otherOptions);
var segmentId = config.mailchimp.segments[list].committeeSegmentId;
var campaignId = $scope.notification.campaignId;
switch ($scope.notification.destinationType) {
case 'custom':
members = $scope.notification.recipients;
break;
case 'committee':
members = $scope.userEdits.allCommitteeList();
break;
default:
members = [];
break;
}
logger.debug('sendCommitteeNotification:notification->', $scope.notification);
if (members.length === 0) {
logger.debug('about to replicateAndSendWithOptions to', list, 'list with campaignName', campaignName, 'campaign Id', campaignId, 'dontSend', dontSend);
return MailchimpCampaignService.replicateAndSendWithOptions({
campaignId: campaignId,
campaignName: campaignName,
contentSections: contentSections,
otherSegmentOptions: otherOptions,
dontSend: dontSend
}).then(openInMailchimpIf(dontSend));
} else {
var segmentName = MailchimpSegmentService.formatSegmentName('Committee Notification Recipients');
return MailchimpSegmentService.saveSegment(list, {segmentId: segmentId}, members, segmentName, $scope.members)
.then(function (segmentResponse) {
logger.debug('segmentResponse following save segment of segmentName:', segmentName, '->', segmentResponse);
logger.debug('about to replicateAndSendWithOptions to committee with campaignName', campaignName, 'campaign Id', campaignId, 'segmentId', segmentResponse.segment.id);
return MailchimpCampaignService.replicateAndSendWithOptions({
campaignId: campaignId,
campaignName: campaignName,
contentSections: contentSections,
segmentId: segmentResponse.segment.id,
otherSegmentOptions: otherOptions,
dontSend: dontSend
}).then(openInMailchimpIf(dontSend));
});
}
})
}
function openInMailchimpIf(dontSend) {
return function (replicateCampaignResponse) {
logger.debug('openInMailchimpIf:replicateCampaignResponse', replicateCampaignResponse, 'dontSend', dontSend);
if (dontSend) {
return $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/wizard/neapolitan?id=" + replicateCampaignResponse.web_id, '_blank');
} else {
return true;
}
}
}
function notifyEmailSendComplete() {
if (!$scope.userEdits.cancelled) {
notify.success('Sending of ' + campaignName + ' was successful.', false);
$scope.userEdits.sendInProgress = false;
$scope.cancelSendNotification();
}
notify.clearBusy();
}
};
$scope.completeInMailchimp = function () {
notify.warning({
title: 'Complete in Mailchimp',
message: 'You can close this dialog now as the message was presumably completed and sent in Mailchimp'
});
$scope.confirmSendNotification(true);
};
$scope.cancelSendNotification = function () {
if ($scope.userEdits.sendInProgress) {
$scope.userEdits.sendInProgress = false;
$scope.userEdits.cancelled = true;
notify.error({
title: 'Cancelling during send',
message: "Because notification sending was already in progress when you cancelled, campaign may have already been sent - check in Mailchimp if in doubt."
});
} else {
logger.debug('calling cancelSendNotification');
close();
}
};
var promises = [
MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) {
$scope.members = members;
logger.debug('refreshMembers -> populated ->', $scope.members.length, 'members');
$scope.selectableRecipients = _.chain(members)
.map(toSelectGeneralMember)
.sortBy(function (member) {
return member.order + member.text
})
.value();
logger.debug('refreshMembers -> populated ->', $scope.selectableRecipients.length, 'selectableRecipients');
}),
MailchimpConfig.getConfig()
.then(function (config) {
$scope.config = config;
logger.debug('retrieved config', $scope.config);
$scope.clearRecipientsForCampaignOfType('committee');
}),
MailchimpCampaignService.list({
limit: 1000,
concise: true,
status: 'save',
title: 'Master'
}).then(function (response) {
$scope.campaigns = response.data;
logger.debug('response.data', response.data);
})];
if (!$scope.committeeFile) promises.push(populateGroupEvents());
$q.all(promises).then(function () {
logger.debug('performed total of', promises.length);
notify.clearBusy();
});
}]
);
/* concatenated from client/src/app/js/committee.js */
angular.module('ekwgApp')
.controller('CommitteeController', ["$rootScope", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "EKWGFileUpload", "CommitteeQueryService", "CommitteeReferenceData", "ModalService", function ($rootScope, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $scope, $filter, $routeParams,
$location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService,
ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService,
MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, EKWGFileUpload, CommitteeQueryService, CommitteeReferenceData, ModalService) {
var logger = $log.getInstance('CommitteeController');
$log.logLevels['CommitteeController'] = $log.LEVEL.OFF;
var notify = Notifier($scope);
notify.setBusy();
$scope.emailingInProgress = false;
$scope.committeeFileBaseUrl = ContentMetaDataService.baseUrl('committeeFiles');
$scope.destinationType = '';
$scope.members = [];
$scope.committeeFiles = [];
$scope.alertMessages = [];
$scope.allowConfirmDelete = false;
$scope.latestYearOpen = true;
$scope.committeeReferenceData = CommitteeReferenceData;
$scope.selected = {
addingNewFile: false,
committeeFiles: []
};
$rootScope.$on('CommitteeReferenceDataReady', function () {
assignFileTypes();
});
function assignFileTypes() {
$scope.fileTypes = CommitteeReferenceData.fileTypes;
logger.debug('CommitteeReferenceDataReady -> fileTypes ->', $scope.fileTypes);
}
$scope.userEdits = {
saveInProgress: false
};
$scope.showAlertMessage = function () {
return ($scope.alert.class === 'alert-danger') || $scope.emailingInProgress;
};
$scope.latestYear = function () {
return CommitteeQueryService.latestYear($scope.committeeFiles)
};
$scope.committeeFilesForYear = function (year) {
return CommitteeQueryService.committeeFilesForYear(year, $scope.committeeFiles)
};
$scope.isActive = function (committeeFile) {
return committeeFile === $scope.selected.committeeFile;
};
$scope.eventDateCalendar = {
open: function ($event) {
$scope.eventDateCalendar.opened = true;
}
};
$scope.allowSend = function () {
return LoggedInMemberService.allowFileAdmin();
};
$scope.allowAddCommitteeFile = function () {
return $scope.fileTypes && LoggedInMemberService.allowFileAdmin();
};
$scope.allowEditCommitteeFile = function (committeeFile) {
return $scope.allowAddCommitteeFile() && committeeFile && committeeFile.$id();
};
$scope.allowDeleteCommitteeFile = function (committeeFile) {
return $scope.allowEditCommitteeFile(committeeFile);
};
$scope.cancelFileChange = function () {
$q.when($scope.hideCommitteeFileDialog()).then(refreshCommitteeFiles).then(notify.clearBusy);
};
$scope.saveCommitteeFile = function () {
$scope.userEdits.saveInProgress = true;
$scope.selected.committeeFile.eventDate = DateUtils.asValueNoTime($scope.selected.committeeFile.eventDate);
logger.debug('saveCommitteeFile ->', $scope.selected.committeeFile);
return $scope.selected.committeeFile.$saveOrUpdate(notify.success, notify.success, notify.error, notify.error)
.then($scope.hideCommitteeFileDialog)
.then(refreshCommitteeFiles)
.then(notify.clearBusy)
.catch(handleError);
function handleError(errorResponse) {
$scope.userEdits.saveInProgress = false;
notify.error({
title: 'Your changes could not be saved',
message: (errorResponse && errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '')
});
notify.clearBusy();
}
};
var defaultCommitteeFile = function () {
return _.clone({
"createdDate": DateUtils.nowAsValue(),
"fileType": $scope.fileTypes && $scope.fileTypes[0].description,
"fileNameData": {}
})
};
function removeDeleteOrAddOrInProgressFlags() {
$scope.allowConfirmDelete = false;
$scope.selected.addingNewFile = false;
$scope.userEdits.saveInProgress = false;
}
$scope.deleteCommitteeFile = function () {
$scope.allowConfirmDelete = true;
};
$scope.cancelDeleteCommitteeFile = function () {
removeDeleteOrAddOrInProgressFlags();
};
$scope.confirmDeleteCommitteeFile = function () {
$scope.userEdits.saveInProgress = true;
function showCommitteeFileDeleted() {
return notify.success('File was deleted successfully');
}
$scope.selected.committeeFile.$remove(showCommitteeFileDeleted, showCommitteeFileDeleted, notify.error, notify.error)
.then($scope.hideCommitteeFileDialog)
.then(refreshCommitteeFiles)
.then(removeDeleteOrAddOrInProgressFlags)
.then(notify.clearBusy);
};
$scope.selectCommitteeFile = function (committeeFile, committeeFiles) {
if (!$scope.selected.addingNewFile) {
$scope.selected.committeeFile = committeeFile;
$scope.selected.committeeFiles = committeeFiles;
}
};
$scope.editCommitteeFile = function () {
removeDeleteOrAddOrInProgressFlags();
delete $scope.uploadedFile;
$('#file-detail-dialog').modal('show');
};
$scope.openMailchimp = function () {
$window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns", '_blank');
};
$scope.openSettings = function () {
ModalService.showModal({
templateUrl: "partials/committee/notification-settings-dialog.html",
controller: "CommitteeNotificationSettingsController",
preClose: function (modal) {
logger.debug('preClose event with modal', modal);
modal.element.modal('hide');
},
}).then(function (modal) {
logger.debug('modal event with modal', modal);
modal.element.modal();
modal.close.then(function (result) {
logger.debug('close event with result', result);
});
})
};
$scope.sendNotification = function (committeeFile) {
ModalService.showModal({
templateUrl: "partials/committee/send-notification-dialog.html",
controller: "CommitteeNotificationsController",
preClose: function (modal) {
logger.debug('preClose event with modal', modal);
modal.element.modal('hide');
},
inputs: {
committeeFile: committeeFile
}
}).then(function (modal) {
logger.debug('modal event with modal', modal);
modal.element.modal();
modal.close.then(function (result) {
logger.debug('close event with result', result);
});
})
};
$scope.cancelSendNotification = function () {
$('#send-notification-dialog').modal('hide');
$scope.resubmit = false;
};
$scope.addCommitteeFile = function ($event) {
$event.stopPropagation();
$scope.selected.addingNewFile = true;
var committeeFile = new CommitteeFileService(defaultCommitteeFile());
$scope.selected.committeeFiles.push(committeeFile);
$scope.selected.committeeFile = committeeFile;
logger.debug('addCommitteeFile:', committeeFile, 'of', $scope.selected.committeeFiles.length, 'files');
$scope.editCommitteeFile();
};
$scope.hideCommitteeFileDialog = function () {
removeDeleteOrAddOrInProgressFlags();
$('#file-detail-dialog').modal('hide');
};
$scope.attachFile = function (file) {
$scope.oldTitle = $scope.selected.committeeFile.fileNameData ? $scope.selected.committeeFile.fileNameData.title : file.name;
logger.debug('then:attachFile:oldTitle', $scope.oldTitle);
$('#hidden-input').click();
};
$scope.onFileSelect = function (file) {
if (file) {
$scope.userEdits.saveInProgress = true;
logger.debug('onFileSelect:file:about to upload ->', file);
$scope.uploadedFile = file;
EKWGFileUpload.onFileSelect(file, notify, 'committeeFiles')
.then(function (fileNameData) {
logger.debug('onFileSelect:file:upload complete -> fileNameData', fileNameData);
$scope.selected.committeeFile.fileNameData = fileNameData;
$scope.selected.committeeFile.fileNameData.title = $scope.oldTitle || file.name;
$scope.userEdits.saveInProgress = false;
});
}
};
$scope.attachmentTitle = function () {
return ($scope.selected.committeeFile && _.isEmpty($scope.selected.committeeFile.fileNameData) ? 'Attach' : 'Replace') + ' File';
};
$scope.fileUrl = function (committeeFile) {
return committeeFile && committeeFile.fileNameData ? URLService.baseUrl() + $scope.committeeFileBaseUrl + '/' + committeeFile.fileNameData.awsFileName : '';
};
$scope.fileTitle = function (committeeFile) {
return committeeFile ? DateUtils.asString(committeeFile.eventDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + committeeFile.fileNameData.title : '';
};
$scope.iconFile = function (committeeFile) {
if (!committeeFile.fileNameData) return undefined;
function fileExtensionIs(fileName, extensions) {
return _.contains(extensions, fileExtension(fileName));
}
function fileExtension(fileName) {
return fileName ? _.last(fileName.split('.')).toLowerCase() : '';
}
if (fileExtensionIs(committeeFile.fileNameData.awsFileName, ['doc', 'docx', 'jpg', 'pdf', 'ppt', 'png', 'txt', 'xls', 'xlsx'])) {
return 'icon-' + fileExtension(committeeFile.fileNameData.awsFileName).substring(0, 3) + '.jpg';
} else {
return 'icon-default.jpg';
}
};
$scope.$on('memberLoginComplete', function () {
refreshAll();
});
$scope.$on('memberLogoutComplete', function () {
refreshAll();
});
function refreshMembers() {
function assignMembersToScope(members) {
$scope.members = members;
return $scope.members;
}
if (LoggedInMemberService.allowFileAdmin()) {
return MemberService.all()
.then(assignMembersToScope);
}
}
function refreshCommitteeFiles() {
CommitteeQueryService.committeeFiles(notify).then(function (files) {
logger.debug('committeeFiles', files);
if (URLService.hasRouteParameter('committeeFileId')) {
$scope.committeeFiles = _.filter(files, function (file) {
return file.$id() === $routeParams.committeeFileId;
});
} else {
$scope.committeeFiles = files;
}
$scope.committeeFileYears = CommitteeQueryService.committeeFileYears($scope.committeeFiles);
});
}
function refreshAll() {
refreshCommitteeFiles();
refreshMembers();
}
assignFileTypes();
refreshAll();
}]);
/* concatenated from client/src/app/js/committeeData.js */
angular.module('ekwgApp')
.factory('CommitteeConfig', ["Config", function (Config) {
function getConfig() {
return Config.getConfig('committee', {
committee: {
contactUs: {
chairman: {description: 'Chairman', fullName: 'Claire Mansfield', email: '[email protected]'},
secretary: {description: 'Secretary', fullName: 'Kerry O\'Grady', email: '[email protected]'},
treasurer: {description: 'Treasurer', fullName: 'Marianne Christensen', email: '[email protected]'},
membership: {description: 'Membership', fullName: 'Desiree Nel', email: '[email protected]'},
social: {description: 'Social Co-ordinator', fullName: 'Suzanne Graham Beer', email: '[email protected]'},
walks: {description: 'Walks Co-ordinator', fullName: 'Stuart Maisner', email: '[email protected]'},
support: {description: 'Technical Support', fullName: 'Nick Barrett', email: '[email protected]'}
},
fileTypes: [
{description: "AGM Agenda", public: true},
{description: "AGM Minutes", public: true},
{description: "Committee Meeting Agenda"},
{description: "Committee Meeting Minutes"},
{description: "Financial Statements", public: true}
]
}
})
}
function saveConfig(config, saveCallback, errorSaveCallback) {
return Config.saveConfig('committee', config, saveCallback, errorSaveCallback);
}
return {
getConfig: getConfig,
saveConfig: saveConfig
}
}])
.factory('CommitteeFileService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('committeeFiles');
}])
.factory('CommitteeReferenceData', ["$rootScope", function ($rootScope) {
var refData = {
contactUsRoles: function () {
var keys = _.keys(refData.contactUs);
if (keys.length > 0) {
return keys;
}
},
contactUsField: function (role, field) {
return refData.contactUs && refData.contactUs[role][field]
},
fileTypesField: function (type, field) {
return refData.fileTypes && refData.fileTypes[type][field]
},
toFileType: function (fileTypeDescription, fileTypes) {
return _.find(fileTypes, {description: fileTypeDescription});
},
contactUsRolesAsArray: function () {
return _.map(refData.contactUs, function (data, type) {
return {
type: type,
fullName: data.fullName,
memberId: data.memberId,
description: data.description + ' (' + data.fullName + ')',
email: data.email
};
});
}
};
$rootScope.$on('CommitteeReferenceDataReady', function () {
refData.ready = true;
});
return refData;
}])
.factory('CommitteeQueryService', ["$q", "$log", "$filter", "$routeParams", "URLService", "CommitteeFileService", "CommitteeReferenceData", "DateUtils", "LoggedInMemberService", "WalksService", "SocialEventsService", function ($q, $log, $filter, $routeParams, URLService, CommitteeFileService, CommitteeReferenceData, DateUtils, LoggedInMemberService, WalksService, SocialEventsService) {
var logger = $log.getInstance('CommitteeQueryService');
$log.logLevels['CommitteeQueryService'] = $log.LEVEL.OFF;
function groupEvents(groupEvents) {
logger.debug('groupEvents', groupEvents);
var fromDate = DateUtils.convertDateField(groupEvents.fromDate);
var toDate = DateUtils.convertDateField(groupEvents.toDate);
logger.debug('groupEvents:fromDate', $filter('displayDate')(fromDate), 'toDate', $filter('displayDate')(toDate));
var events = [];
var promises = [];
if (groupEvents.includeWalks) promises.push(
WalksService.query({walkDate: {$gte: fromDate, $lte: toDate}})
.then(function (walks) {
return _.map(walks, function (walk) {
return events.push({
id: walk.$id(),
selected: true,
eventType: 'Walk',
area: 'walks',
type: 'walk',
eventDate: walk.walkDate,
eventTime: walk.startTime,
distance: walk.distance,
postcode: walk.postcode,
title: walk.briefDescriptionAndStartPoint || 'Awaiting walk details',
description: walk.longerDescription,
contactName: walk.displayName || 'Awaiting walk leader',
contactPhone: walk.contactPhone,
contactEmail: walk.contactEmail
});
})
}));
if (groupEvents.includeCommitteeEvents) promises.push(
CommitteeFileService.query({eventDate: {$gte: fromDate, $lte: toDate}})
.then(function (committeeFiles) {
return _.map(committeeFiles, function (committeeFile) {
return events.push({
id: committeeFile.$id(),
selected: true,
eventType: 'AGM & Committee',
area: 'committee',
type: 'committeeFile',
eventDate: committeeFile.eventDate,
postcode: committeeFile.postcode,
description: committeeFile.fileType,
title: committeeFile.fileNameData.title
});
})
}));
if (groupEvents.includeSocialEvents) promises.push(
SocialEventsService.query({eventDate: {$gte: fromDate, $lte: toDate}})
.then(function (socialEvents) {
return _.map(socialEvents, function (socialEvent) {
return events.push({
id: socialEvent.$id(),
selected: true,
eventType: 'Social Event',
area: 'social',
type: 'socialEvent',
eventDate: socialEvent.eventDate,
eventTime: socialEvent.eventTimeStart,
postcode: socialEvent.postcode,
title: socialEvent.briefDescription,
description: socialEvent.longerDescription,
contactName: socialEvent.displayName,
contactPhone: socialEvent.contactPhone,
contactEmail: socialEvent.contactEmail
});
})
}));
return $q.all(promises).then(function () {
logger.debug('performed total of', promises.length, 'events of length', events.length);
return _.chain(events)
.sortBy('eventDate')
.value();
});
}
function committeeFilesLatestFirst(committeeFiles) {
return _.chain(committeeFiles)
.sortBy('eventDate')
.reverse()
.value();
}
function latestYear(committeeFiles) {
return _.first(
_.chain(committeeFilesLatestFirst(committeeFiles))
.pluck('eventDate')
.map(function (eventDate) {
return parseInt(DateUtils.asString(eventDate, undefined, 'YYYY'));
})
.value());
}
function committeeFilesForYear(year, committeeFiles) {
var latestYearValue = latestYear(committeeFiles);
return _.filter(committeeFilesLatestFirst(committeeFiles), function (committeeFile) {
var fileYear = extractYear(committeeFile);
return (fileYear === year) || (!fileYear && (latestYearValue === year));
});
}
function extractYear(committeeFile) {
return parseInt(DateUtils.asString(committeeFile.eventDate, undefined, 'YYYY'));
}
function committeeFileYears(committeeFiles) {
var latestYearValue = latestYear(committeeFiles);
function addLatestYearFlag(committeeFileYear) {
return {year: committeeFileYear, latestYear: latestYearValue === committeeFileYear};
}
var years = _.chain(committeeFiles)
.map(extractYear)
.unique()
.sort()
.map(addLatestYearFlag)
.reverse()
.value();
logger.debug('committeeFileYears', years);
return years.length === 0 ? [{year: latestYear(committeeFiles), latestYear: true}] : years;
}
function committeeFiles(notify) {
notify.progress('Refreshing Committee files...');
function queryCommitteeFiles() {
if (URLService.hasRouteParameter('committeeFileId')) {
return CommitteeFileService.getById($routeParams.committeeFileId)
.then(function (committeeFile) {
if (!committeeFile) notify.error('Committee file could not be found. Try opening again from the link in the notification email');
return [committeeFile];
});
} else {
return CommitteeFileService.all().then(function (files) {
return filterCommitteeFiles(files);
});
}
}
return queryCommitteeFiles()
.then(function (committeeFiles) {
notify.progress('Found ' + committeeFiles.length + ' committee file(s)');
notify.setReady();
return _.chain(committeeFiles)
.sortBy('fileDate')
.reverse()
.sortBy('createdDate')
.value();
}, notify.error);
}
function filterCommitteeFiles(files) {
logger.debug('filterCommitteeFiles files ->', files);
var filteredFiles = _.filter(files, function (file) {
return CommitteeReferenceData.fileTypes && CommitteeReferenceData.toFileType(file.fileType, CommitteeReferenceData.fileTypes).public || LoggedInMemberService.allowCommittee() || LoggedInMemberService.allowFileAdmin();
});
logger.debug('filterCommitteeFiles in ->', files && files.length, 'out ->', filteredFiles.length, 'CommitteeReferenceData.fileTypes', CommitteeReferenceData.fileTypes);
return filteredFiles
}
return {
groupEvents: groupEvents,
committeeFiles: committeeFiles,
latestYear: latestYear,
committeeFileYears: committeeFileYears,
committeeFilesForYear: committeeFilesForYear
}
}]
);
/* concatenated from client/src/app/js/committeeNotificationSettingsController.js */
angular.module('ekwgApp')
.controller('CommitteeNotificationSettingsController', ["$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MAILCHIMP_APP_CONSTANTS", "MailchimpConfig", "Notifier", "close", function ($window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams,
$location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService,
ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService,
MAILCHIMP_APP_CONSTANTS, MailchimpConfig, Notifier, close) {
var logger = $log.getInstance('CommitteeNotificationSettingsController');
$log.logLevels['CommitteeNotificationSettingsController'] = $log.LEVEL.OFF;
$scope.notify = {};
$scope.campaigns = [];
var notify = Notifier($scope.notify);
var campaignSearchTerm = 'Master';
notify.setBusy();
notify.progress({
title: 'Mailchimp Campaigns',
message: 'Getting campaign information matching "' + campaignSearchTerm + '"'
});
$scope.notReady = function () {
return $scope.campaigns.length === 0;
};
MailchimpConfig.getConfig()
.then(function (config) {
$scope.config = config;
logger.debug('retrieved config', $scope.config);
});
MailchimpCampaignService.list({
limit: 1000,
concise: true,
status: 'save',
title: campaignSearchTerm
}).then(function (response) {
$scope.campaigns = response.data;
logger.debug('response.data', response.data);
notify.success({
title: 'Mailchimp Campaigns',
message: 'Found ' + $scope.campaigns.length + ' draft campaigns matching "' + campaignSearchTerm + '"'
});
notify.clearBusy();
});
$scope.editCampaign = function (campaignId) {
if (!campaignId) {
notify.error({
title: 'Edit Mailchimp Campaign',
message: 'Please select a campaign from the drop-down before choosing edit'
});
} else {
notify.hide();
var webId = _.find($scope.campaigns, function (campaign) {
return campaign.id === campaignId;
}).web_id;
logger.debug('editCampaign:campaignId', campaignId, 'web_id', webId);
$window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/edit?id=" + webId, '_blank');
}
};
$scope.save = function () {
logger.debug('saving config', $scope.config);
MailchimpConfig.saveConfig($scope.config).then(close).catch(notify.error);
};
$scope.cancel = function () {
close();
};
}]
);
/* concatenated from client/src/app/js/contentMetaServices.js */
angular.module('ekwgApp')
.factory('ContentMetaDataService', ["ContentMetaData", "$q", function (ContentMetaData, $q) {
var baseUrl = function (metaDataPathSegment) {
return '/aws/s3/' + metaDataPathSegment;
};
var createNewMetaData = function (withDefaults) {
if (withDefaults) {
return {image: '/(select file)', text: '(Enter title here)'};
} else {
return {};
}
};
var getMetaData = function (contentMetaDataType) {
var task = $q.defer();
ContentMetaData.query({contentMetaDataType: contentMetaDataType}, {limit: 1})
.then(function (results) {
if (results && results.length > 0) {
task.resolve(results[0]);
} else {
task.resolve(new ContentMetaData({
contentMetaDataType: contentMetaDataType,
baseUrl: baseUrl(contentMetaDataType),
files: [createNewMetaData(true)]
}));
}
}, function (response) {
task.reject('Query of contentMetaDataType for ' + contentMetaDataType + ' failed: ' + response);
});
return task.promise;
};
var saveMetaData = function (metaData, saveCallback, errorSaveCallback) {
return metaData.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback, errorSaveCallback);
};
return {
baseUrl: baseUrl,
getMetaData: getMetaData,
createNewMetaData: createNewMetaData,
saveMetaData: saveMetaData
}
}])
.factory('ContentMetaData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('contentMetaData');
}])
.factory('ContentTextService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('contentText');
}])
.factory('ContentText', ["ContentTextService", function (ContentTextService) {
function forName(name) {
return ContentTextService.all().then(function (contentDocuments) {
return _.findWhere(contentDocuments, {name: name}) || new ContentTextService({name: name});
});
}
return {forName: forName}
}]);
/* concatenated from client/src/app/js/directives.js */
angular.module('ekwgApp')
.directive('contactUs', ["$log", "$compile", "URLService", "CommitteeReferenceData", function ($log, $compile, URLService, CommitteeReferenceData) {
var logger = $log.getInstance('contactUs');
$log.logLevels['contactUs'] = $log.LEVEL.OFF;
function email(role) {
return CommitteeReferenceData.contactUsField(role, 'email');
}
function description(role) {
return CommitteeReferenceData.contactUsField(role, 'description');
}
function fullName(role) {
return CommitteeReferenceData.contactUsField(role, 'fullName');
}
function createHref(scope, role) {
return '<a href="mailto:' + email(role) + '">' + (scope.text || email(role)) + '</a>';
}
function createListItem(scope, role) {
return '<li ' +
'style="' +
'font-weight: normal;' +
'padding: 4px 0px 4px 21px;' +
'list-style: none;' +
'background-image: url(' + URLService.baseUrl() + '/assets/images/ramblers/bull-green.png);' +
'background-position: 0px 9px;' +
'background-repeat: no-repeat no-repeat">' +
fullName(role) + ' - ' + description(role) + ' - ' +
'<a href="mailto:' + email(role) + '"' +
'style="' +
'background-color: transparent;' +
'color: rgb(120, 35, 39);' +
'text-decoration: none; ' +
'font-weight: bold; ' +
'background-position: initial; ' +
'background-repeat: initial;">' +
(scope.text || email(role)) + '</a>' +
'</li>';
}
function expandRoles(scope) {
var roles = scope.role ? scope.role.split(',') : CommitteeReferenceData.contactUsRoles();
logger.debug('role ->', scope.role, ' roles ->', roles);
return _(roles).map(function (role) {
if (scope.format === 'list') {
return createListItem(scope, role);
} else {
return createHref(scope, role);
}
}).join('\n');
}
function wrapInUL(scope) {
if (scope.format === 'list') {
return '<ul style="'
+ 'margin: 10px 0 0;'
+ 'padding: 0 0 10px 10px;'
+ 'font-weight: bold;'
+ 'background-image: url(' + URLService.baseUrl() + '/assets/images/ramblers/dot-darkgrey-hor.png);'
+ 'background-position: 0% 100%;'
+ 'background-repeat: repeat no-repeat;'
+ 'margin-bottom: 20px;"> '
+ (scope.heading || '')
+ expandRoles(scope)
+ '</ul>';
} else {
return expandRoles(scope);
}
}
return {
restrict: 'EA',
replace: true,
link: function (scope, element) {
scope.$watch('name', function () {
if (CommitteeReferenceData.ready) {
var html = wrapInUL(scope);
logger.debug('html before compile ->', html);
element.html($compile(html)(scope));
}
});
},
scope: {
format: '@',
text: '@',
role: '@',
heading: '@'
}
};
}]);
/* concatenated from client/src/app/js/emailerService.js */
angular.module('ekwgApp')
.factory('EmailSubscriptionService', ["$rootScope", "$log", "$http", "$q", "MemberService", "DateUtils", "MailchimpErrorParserService", function ($rootScope, $log, $http, $q, MemberService, DateUtils, MailchimpErrorParserService) {
var logger = $log.getInstance('EmailSubscriptionService');
$log.logLevels['EmailSubscriptionService'] = $log.LEVEL.OFF;
var resetAllBatchSubscriptions = function (members, subscribedState) {
var deferredTask = $q.defer();
var savePromises = [];
deferredTask.notify('Resetting Mailchimp subscriptions for ' + members.length + ' members');
_.each(members, function (member) {
defaultMailchimpSettings(member, subscribedState);
savePromises.push(member.$saveOrUpdate());
});
$q.all(savePromises).then(function () {
deferredTask.notify('Reset of Mailchimp subscriptions completed. Next member save will resend all lists to Mailchimp');
MemberService.all().then(function (refreshedMembers) {
deferredTask.resolve(refreshedMembers);
})
});
};
function defaultMailchimpSettings(member, subscribedState) {
member.mailchimpLists = {
"walks": {"subscribed": subscribedState},
"socialEvents": {"subscribed": subscribedState},
"general": {"subscribed": subscribedState}
}
}
function booleanToString(value) {
return String(value || false);
}
function addMailchimpIdentifiersToRequest(member, listType, request) {
var mailchimpIdentifiers = {email: {}};
mailchimpIdentifiers.email.email = member.email;
if (member.mailchimpLists[listType].leid) {
mailchimpIdentifiers.email.leid = member.mailchimpLists[listType].leid;
}
if (request) {
return angular.extend(request, mailchimpIdentifiers);
} else {
return mailchimpIdentifiers.email;
}
}
var createBatchSubscriptionForList = function (listType, members) {
var deferredTask = $q.defer();
var progress = 'Sending ' + listType + ' member data to Mailchimp';
deferredTask.notify(progress);
var batchedMembers = [];
var subscriptionEntries = _.chain(members)
.filter(function (member) {
return includeMemberInSubscription(listType, member);
})
.map(function (member) {
batchedMembers.push(member);
var request = {
"merge_vars": {
"FNAME": member.firstName,
"LNAME": member.lastName,
"MEMBER_NUM": member.membershipNumber,
"MEMBER_EXP": DateUtils.displayDate(member.membershipExpiryDate),
"USERNAME": member.userName,
"PW_RESET": member.passwordResetId || ''
}
};
return addMailchimpIdentifiersToRequest(member, listType, request);
}).value();
if (subscriptionEntries.length > 0) {
var url = '/mailchimp/lists/' + listType + '/batchSubscribe';
logger.debug('sending', subscriptionEntries.length, listType, 'subscriptions to mailchimp', subscriptionEntries);
$http({method: 'POST', url: url, data: subscriptionEntries})
.then(function (response) {
var responseData = response.data;
logger.debug('received response', responseData);
var errorObject = MailchimpErrorParserService.extractError(responseData);
if (errorObject.error) {
var errorResponse = {
message: 'Sending of ' + listType + ' list subscription to Mailchimp was not successful',
error: errorObject.error
};
deferredTask.reject(errorResponse);
} else {
var totalResponseCount = responseData.updates.concat(responseData.adds).concat(responseData.errors).length;
deferredTask.notify('Send of ' + subscriptionEntries.length + ' ' + listType + ' members completed - processing ' + totalResponseCount + ' Mailchimp response(s)');
var savePromises = [];
processValidResponses(listType, responseData.updates.concat(responseData.adds), batchedMembers, savePromises, deferredTask);
processErrorResponses(listType, responseData.errors, batchedMembers, savePromises, deferredTask);
$q.all(savePromises).then(function () {
MemberService.all().then(function (refreshedMembers) {
deferredTask.notify('Send of ' + subscriptionEntries.length + ' members to ' + listType + ' list completed with ' + responseData.add_count + ' member(s) added, ' + responseData.update_count + ' updated and ' + responseData.error_count + ' error(s)');
deferredTask.resolve(refreshedMembers);
})
});
}
}).catch(function (response) {
var data = response.data;
var errorMessage = 'Sending of ' + listType + ' member data to Mailchimp was not successful due to response: ' + data.trim();
logger.error(errorMessage);
deferredTask.reject(errorMessage);
})
} else {
deferredTask.notify('No ' + listType + ' updates to send Mailchimp');
MemberService.all().then(function (refreshedMembers) {
deferredTask.resolve(refreshedMembers);
});
}
return deferredTask.promise;
};
function includeMemberInEmailList(listType, member) {
if (member.email && member.mailchimpLists[listType].subscribed) {
if (listType === 'socialEvents') {
return member.groupMember && member.socialMember;
} else {
return member.groupMember;
}
} else {
return false;
}
}
function includeMemberInSubscription(listType, member) {
return includeMemberInEmailList(listType, member) && !member.mailchimpLists[listType].updated;
}
function includeMemberInUnsubscription(listType, member) {
if (!member || !member.groupMember) {
return true;
} else if (member.mailchimpLists) {
if (listType === 'socialEvents') {
return (!member.socialMember && member.mailchimpLists[listType].subscribed);
} else {
return (!member.mailchimpLists[listType].subscribed);
}
} else {
return false;
}
}
function includeSubscriberInUnsubscription(listType, allMembers, subscriber) {
return includeMemberInUnsubscription(listType, responseToMember(listType, allMembers, subscriber));
}
function resetUpdateStatusForMember(member) {
// updated == false means not up to date with mail e.g. next list update will send this data to mailchimo
member.mailchimpLists.walks.updated = false;
member.mailchimpLists.socialEvents.updated = false;
member.mailchimpLists.general.updated = false;
}
function responseToMember(listType, allMembers, mailchimpResponse) {
return _(allMembers).find(function (member) {
var matchedOnListSubscriberId = mailchimpResponse.leid && member.mailchimpLists[listType].leid && (mailchimpResponse.leid.toString() === member.mailchimpLists[listType].leid.toString());
var matchedOnLastReturnedEmail = member.mailchimpLists[listType].email && (mailchimpResponse.email.toLowerCase() === member.mailchimpLists[listType].email.toLowerCase());
var matchedOnCurrentEmail = member.email && mailchimpResponse.email.toLowerCase() === member.email.toLowerCase();
return (matchedOnListSubscriberId || matchedOnLastReturnedEmail || matchedOnCurrentEmail);
});
}
function findMemberAndMarkAsUpdated(listType, batchedMembers, response, deferredTask) {
var member = responseToMember(listType, batchedMembers, response);
if (member) {
member.mailchimpLists[listType].leid = response.leid;
member.mailchimpLists[listType].updated = true; // updated == true means up to date e.g. nothing to send to mailchimo
member.mailchimpLists[listType].lastUpdated = DateUtils.nowAsValue();
member.mailchimpLists[listType].email = member.email;
} else {
deferredTask.notify('From ' + batchedMembers.length + ' members, could not find any member related to response ' + JSON.stringify(response));
}
return member;
}
function processValidResponses(listType, validResponses, batchedMembers, savePromises, deferredTask) {
_.each(validResponses, function (response) {
var member = findMemberAndMarkAsUpdated(listType, batchedMembers, response, deferredTask);
if (member) {
delete member.mailchimpLists[listType].code;
delete member.mailchimpLists[listType].error;
deferredTask.notify('processing valid response for member ' + member.email);
savePromises.push(member.$saveOrUpdate());
}
});
}
function processErrorResponses(listType, errorResponses, batchedMembers, savePromises, deferredTask) {
_.each(errorResponses, function (response) {
var member = findMemberAndMarkAsUpdated(listType, batchedMembers, response.email, deferredTask);
if (member) {
deferredTask.notify('processing error response for member ' + member.email);
member.mailchimpLists[listType].code = response.code;
member.mailchimpLists[listType].error = response.error;
if (_.contains([210, 211, 212, 213, 214, 215, 220, 250], response.code)) member.mailchimpLists[listType].subscribed = false;
savePromises.push(member.$saveOrUpdate());
}
});
}
return {
responseToMember: responseToMember,
defaultMailchimpSettings: defaultMailchimpSettings,
createBatchSubscriptionForList: createBatchSubscriptionForList,
resetAllBatchSubscriptions: resetAllBatchSubscriptions,
resetUpdateStatusForMember: resetUpdateStatusForMember,
addMailchimpIdentifiersToRequest: addMailchimpIdentifiersToRequest,
includeMemberInSubscription: includeMemberInSubscription,
includeMemberInEmailList: includeMemberInEmailList,
includeSubscriberInUnsubscription: includeSubscriberInUnsubscription
}
}]);
/* concatenated from client/src/app/js/expenses.js */
angular.module('ekwgApp')
.controller('ExpensesController', ["$compile", "$log", "$timeout", "$sce", "$templateRequest", "$q", "$rootScope", "$location", "$routeParams", "$scope", "$filter", "DateUtils", "NumberUtils", "URLService", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "ExpenseClaimsService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "EKWGFileUpload", function ($compile, $log, $timeout, $sce, $templateRequest, $q, $rootScope, $location, $routeParams,
$scope, $filter, DateUtils, NumberUtils, URLService, LoggedInMemberService, MemberService, ContentMetaDataService,
ExpenseClaimsService, MailchimpSegmentService, MailchimpCampaignService, MailchimpConfig, Notifier, EKWGFileUpload) {
var logger = $log.getInstance('ExpensesController');
var noLogger = $log.getInstance('ExpensesControllerNoLogger');
$log.logLevels['ExpensesControllerNoLogger'] = $log.LEVEL.OFF;
$log.logLevels['ExpensesController'] = $log.LEVEL.OFF;
const SELECTED_EXPENSE = 'Expense from last email link';
$scope.receiptBaseUrl = ContentMetaDataService.baseUrl('expenseClaims');
$scope.dataError = false;
$scope.members = [];
$scope.expenseClaims = [];
$scope.unfilteredExpenseClaims = [];
$scope.expensesOpen = URLService.hasRouteParameter('expenseId') || URLService.isArea('expenses');
$scope.alertMessages = [];
$scope.filterTypes = [{
disabled: !$routeParams.expenseId,
description: SELECTED_EXPENSE,
filter: function (expenseClaim) {
if ($routeParams.expenseId) {
return expenseClaim && expenseClaim.$id() === $routeParams.expenseId;
}
else {
return false;
}
}
}, {
description: 'Unpaid expenses',
filter: function (expenseClaim) {
return !$scope.expenseClaimStatus(expenseClaim).atEndpoint;
}
}, {
description: 'Paid expenses',
filter: function (expenseClaim) {
return $scope.expenseClaimStatus(expenseClaim).atEndpoint;
}
}, {
description: 'Expenses awaiting action from me',
filter: function (expenseClaim) {
return LoggedInMemberService.allowFinanceAdmin() ? editable(expenseClaim) : editableAndOwned(expenseClaim);
}
}, {
description: 'All expenses',
filter: function () {
return true;
}
}];
$scope.selected = {
showOnlyMine: !allowAdminFunctions(),
saveInProgress: false,
expenseClaimIndex: 0,
expenseItemIndex: 0,
expenseFilter: $scope.filterTypes[$routeParams.expenseId ? 0 : 1]
};
$scope.itemAlert = {};
var notify = Notifier($scope);
var notifyItem = Notifier($scope.itemAlert);
notify.setBusy();
var notificationsBaseUrl = 'partials/expenses/notifications';
LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId');
$scope.showArea = function (area) {
URLService.navigateTo('admin', area)
};
$scope.selected.expenseClaim = function () {
try {
return $scope.expenseClaims[$scope.selected.expenseClaimIndex];
} catch (e) {
console.error(e);
}
};
$scope.isInactive = function (expenseClaim) {
return expenseClaim !== $scope.selected.expenseClaim();
};
$scope.selected.expenseItem = function () {
try {
var expenseClaim = $scope.expenseClaims[$scope.selected.expenseClaimIndex];
return expenseClaim ? expenseClaim.expenseItems[$scope.selected.expenseItemIndex] : undefined;
} catch (e) {
console.error(e);
}
};
$scope.expenseTypes = [
{value: "travel-reccie", name: "Travel (walk reccie)", travel: true},
{value: "travel-committee", name: "Travel (attend committee meeting)", travel: true},
{value: "other", name: "Other"}];
var eventTypes = {
created: {description: "Created", editable: true},
submitted: {description: "Submitted", actionable: true, notifyCreator: true, notifyApprover: true},
'first-approval': {description: "First Approval", actionable: true, notifyApprover: true},
'second-approval': {
description: "Second Approval",
actionable: true,
notifyCreator: true,
notifyApprover: true,
notifyTreasurer: true
},
returned: {description: "Returned", atEndpoint: false, editable: true, notifyCreator: true, notifyApprover: true},
paid: {description: "Paid", atEndpoint: true, notifyCreator: true, notifyApprover: true, notifyTreasurer: true}
};
var defaultExpenseClaim = function () {
return _.clone({
"cost": 0,
"expenseItems": [],
"expenseEvents": []
})
};
var defaultExpenseItem = function () {
return _.clone({
expenseType: $scope.expenseTypes[0],
"travel": {
"costPerMile": 0.28,
"miles": 0,
"from": '',
"to": '',
"returnJourney": true
}
});
};
function editable(expenseClaim) {
return memberCanEditClaim(expenseClaim) && $scope.expenseClaimStatus(expenseClaim).editable;
}
function editableAndOwned(expenseClaim) {
return memberOwnsClaim(expenseClaim) && $scope.expenseClaimStatus(expenseClaim).editable;
}
$scope.editable = function () {
return editable($scope.selected.expenseClaim());
};
$scope.allowClearError = function () {
return URLService.hasRouteParameter('expenseId') && $scope.dataError;
};
$scope.allowAddExpenseClaim = function () {
return !$scope.dataError && !_.find($scope.unfilteredExpenseClaims, editableAndOwned);
};
$scope.allowFinanceAdmin = function () {
return LoggedInMemberService.allowFinanceAdmin();
};
$scope.allowEditExpenseItem = function () {
return $scope.allowAddExpenseItem() && $scope.selected.expenseItem() && $scope.selected.expenseClaim().$id();
};
$scope.allowAddExpenseItem = function () {
return $scope.editable();
};
$scope.allowDeleteExpenseItem = function () {
return $scope.allowEditExpenseItem();
};
$scope.allowDeleteExpenseClaim = function () {
return !$scope.allowDeleteExpenseItem() && $scope.allowAddExpenseItem();
};
$scope.allowSubmitExpenseClaim = function () {
return $scope.allowEditExpenseItem() && !$scope.allowResubmitExpenseClaim();
};
function allowAdminFunctions() {
return LoggedInMemberService.allowTreasuryAdmin() || LoggedInMemberService.allowFinanceAdmin();
}
$scope.allowAdminFunctions = function () {
return allowAdminFunctions();
};
$scope.allowReturnExpenseClaim = function () {
return $scope.allowAdminFunctions()
&& $scope.selected.expenseClaim()
&& expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.submitted)
&& !expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.returned)
&& $scope.expenseClaimStatus($scope.selected.expenseClaim()).actionable;
};
$scope.allowResubmitExpenseClaim = function () {
return $scope.editable() && expenseClaimHasEventType($scope.selected.expenseClaim(), eventTypes.returned);
};
$scope.allowPaidExpenseClaim = function () {
return LoggedInMemberService.allowTreasuryAdmin() && _.contains(
[eventTypes.submitted.description, eventTypes['second-approval'].description, eventTypes['first-approval'].description],
$scope.expenseClaimLatestEvent().eventType.description);
};
function activeEvents(optionalEvents) {
var events = optionalEvents || $scope.selected.expenseClaim().expenseEvents;
var latestReturnedEvent = _.find(events.reverse(), function (event) {
return _.isEqual(event.eventType, $scope.expenseClaimStatus.returned);
});
return latestReturnedEvent ? events.slice(events.indexOf(latestReturnedEvent + 1)) : events;
}
function expenseClaimHasEventType(expenseClaim, eventType) {
if (!expenseClaim) return false;
return eventForEventType(expenseClaim, eventType);
}
function eventForEventType(expenseClaim, eventType) {
if (expenseClaim) return _.find(expenseClaim.expenseEvents, function (event) {
return _.isEqual(event.eventType, eventType);
});
}
$scope.allowApproveExpenseClaim = function () {
return false;
};
$scope.lastApprovedByMe = function () {
var approvalEvents = $scope.approvalEvents();
return approvalEvents.length > 0 && _.last(approvalEvents).memberId === LoggedInMemberService.loggedInMember().memberId;
};
$scope.approvalEvents = function () {
if (!$scope.selected.expenseClaim()) return [];
return _.filter($scope.selected.expenseClaim().expenseEvents, function (event) {
return _.isEqual(event.eventType, eventTypes['first-approval']) || _.isEqual(event.eventType, eventTypes['second-approval']);
});
};
$scope.expenseClaimStatus = function (optionalExpenseClaim) {
var expenseClaim = optionalExpenseClaim || $scope.selected.expenseClaim();
return $scope.expenseClaimLatestEvent(expenseClaim).eventType;
};
$scope.expenseClaimLatestEvent = function (optionalExpenseClaim) {
var expenseClaim = optionalExpenseClaim || $scope.selected.expenseClaim();
return expenseClaim ? _.last(expenseClaim.expenseEvents) : {};
};
$scope.nextApprovalStage = function () {
var approvals = $scope.approvalEvents();
if (approvals.length === 0) {
return 'First Approval';
}
else if (approvals.length === 1) {
return 'Second Approval'
}
else {
return 'Already has ' + approvals.length + ' approvals!';
}
};
$scope.confirmApproveExpenseClaim = function () {
var approvals = $scope.approvalEvents();
notifyItem.hide();
if (approvals.length === 0) {
createEventAndSendNotifications(eventTypes['first-approval']);
}
else if (approvals.length === 1) {
createEventAndSendNotifications(eventTypes['second-approval']);
}
else {
notify.error('This expense claim already has ' + approvals.length + ' approvals!');
}
};
$scope.showAllExpenseClaims = function () {
$scope.dataError = false;
$location.path('/admin/expenses')
};
$scope.addExpenseClaim = function () {
$scope.expenseClaims.unshift(new ExpenseClaimsService(defaultExpenseClaim()));
$scope.selectExpenseClaim(0);
createEvent(eventTypes.created);
$scope.addExpenseItem();
};
$scope.selectExpenseItem = function (index) {
if ($scope.selected.saveInProgress) {
noLogger.info('selectExpenseItem - selected.saveInProgress - not changing to index', index);
} else {
noLogger.info('selectExpenseItem:', index);
$scope.selected.expenseItemIndex = index;
}
};
$scope.selectExpenseClaim = function (index) {
if ($scope.selected.saveInProgress) {
noLogger.info('selectExpenseClaim - selected.saveInProgress - not changing to index', index);
} else {
$scope.selected.expenseClaimIndex = index;
var expenseClaim = $scope.selected.expenseClaim();
noLogger.info('selectExpenseClaim:', index, expenseClaim);
}
};
$scope.editExpenseItem = function () {
$scope.removeConfirm();
delete $scope.uploadedFile;
$('#expense-detail-dialog').modal('show');
};
$scope.hideExpenseClaim = function () {
$scope.removeConfirm();
$('#expense-detail-dialog').modal('hide');
};
$scope.addReceipt = function () {
$('#hidden-input').click();
};
$scope.removeReceipt = function () {
delete $scope.selected.expenseItem().receipt;
delete $scope.uploadedFile;
};
$scope.receiptTitle = function (expenseItem) {
return expenseItem && expenseItem.receipt ? (expenseItem.receipt.title || expenseItem.receipt.originalFileName) : '';
};
function baseUrl() {
return _.first($location.absUrl().split('/#'));
}
$scope.receiptUrl = function (expenseItem) {
return expenseItem && expenseItem.receipt ? baseUrl() + $scope.receiptBaseUrl + '/' + expenseItem.receipt.awsFileName : '';
};
$scope.onFileSelect = function (file) {
if (file) {
$scope.uploadedFile = file;
EKWGFileUpload.onFileSelect(file, notify, 'expenseClaims')
.then(function (fileNameData) {
var expenseItem = $scope.selected.expenseItem();
var oldTitle = (expenseItem.receipt && expenseItem.receipt.title) ? receipt.title : undefined;
expenseItem.receipt = fileNameData;
expenseItem.receipt.title = oldTitle;
});
}
};
function createEvent(eventType, reason) {
var expenseClaim = $scope.selected.expenseClaim();
if (!expenseClaim.expenseEvents) expenseClaim.expenseEvents = [];
var event = {
"date": DateUtils.nowAsValue(),
"memberId": LoggedInMemberService.loggedInMember().memberId,
"eventType": eventType
};
if (reason) event.reason = reason;
expenseClaim.expenseEvents.push(event);
}
$scope.addExpenseItem = function () {
$scope.removeConfirm();
var newExpenseItem = defaultExpenseItem();
$scope.selected.expenseClaim().expenseItems.push(newExpenseItem);
var index = $scope.selected.expenseClaim().expenseItems.indexOf(newExpenseItem);
if (index > -1) {
$scope.selectExpenseItem(index);
$scope.editExpenseItem();
} else {
showExpenseErrorAlert('Could not display new expense item')
}
};
$scope.expenseTypeChange = function () {
logger.debug('$scope.selected.expenseItem().expenseType', $scope.selected.expenseItem().expenseType);
if ($scope.selected.expenseItem().expenseType.travel) {
if (!$scope.selected.expenseItem().travel) $scope.selected.expenseItem().travel = defaultExpenseItem().travel;
} else {
delete $scope.selected.expenseItem().travel;
}
$scope.setExpenseItemFields();
};
$scope.expenseDateCalendar = {
open: function ($event) {
$scope.expenseDateCalendar.opened = true;
}
};
function recalculateClaimCost() {
$scope.selected.expenseClaim().cost = $filter('sumValues')($scope.selected.expenseClaim().expenseItems, 'cost');
}
$scope.cancelExpenseChange = function () {
$scope.refreshExpenses().then($scope.hideExpenseClaim).then(notify.clearBusy);
};
function showExpenseErrorAlert(message) {
var messageDefaulted = message || 'Please try this again.';
notify.error('Your expense claim could not be saved. ' + messageDefaulted);
$scope.selected.saveInProgress = false;
}
function showExpenseEmailErrorAlert(message) {
$scope.selected.saveInProgress = false;
notify.error('Your expense claim email processing failed. ' + message);
}
function showExpenseProgressAlert(message, busy) {
notify.progress(message, busy);
}
function showExpenseSuccessAlert(message, busy) {
notify.success(message, busy);
}
$scope.saveExpenseClaim = function (optionalExpenseClaim) {
$scope.selected.saveInProgress = true;
function showExpenseSaved(data) {
$scope.expenseClaims[$scope.selected.expenseClaimIndex] = data;
$scope.selected.saveInProgress = false;
return notify.success('Expense was saved successfully');
}
showExpenseProgressAlert('Saving expense claim', true);
$scope.setExpenseItemFields();
return (optionalExpenseClaim || $scope.selected.expenseClaim()).$saveOrUpdate(showExpenseSaved, showExpenseSaved, showExpenseErrorAlert, showExpenseErrorAlert)
.then($scope.hideExpenseClaim)
.then(notify.clearBusy);
};
$scope.approveExpenseClaim = function () {
$scope.confirmAction = {approve: true};
if ($scope.lastApprovedByMe()) notifyItem.warning({
title: 'Duplicate approval warning',
message: 'You were the previous approver, therefore ' + $scope.nextApprovalStage() + ' ought to be carried out by someone else. Are you sure you want to do this?'
});
};
$scope.deleteExpenseClaim = function () {
$scope.confirmAction = {delete: true};
};
$scope.deleteExpenseItem = function () {
$scope.confirmAction = {delete: true};
};
$scope.confirmDeleteExpenseItem = function () {
$scope.selected.saveInProgress = true;
showExpenseProgressAlert('Deleting expense item', true);
var expenseItem = $scope.selected.expenseItem();
logger.debug('removing', expenseItem);
var index = $scope.selected.expenseClaim().expenseItems.indexOf(expenseItem);
if (index > -1) {
$scope.selected.expenseClaim().expenseItems.splice(index, 1);
} else {
showExpenseErrorAlert('Could not delete expense item')
}
$scope.selectExpenseItem(0);
recalculateClaimCost();
$scope.saveExpenseClaim()
.then($scope.removeConfirm)
.then(notify.clearBusy);
};
$scope.removeConfirm = function () {
delete $scope.confirmAction;
showExpenseSuccessAlert();
};
$scope.confirmDeleteExpenseClaim = function () {
showExpenseProgressAlert('Deleting expense claim', true);
function showExpenseDeleted() {
return showExpenseSuccessAlert('Expense was deleted successfully');
}
$scope.selected.expenseClaim().$remove(showExpenseDeleted, showExpenseDeleted, showExpenseErrorAlert, showExpenseErrorAlert)
.then($scope.hideExpenseClaim)
.then(showExpenseDeleted)
.then($scope.refreshExpenses)
.then($scope.removeConfirm)
.then(notify.clearBusy);
};
$scope.submitExpenseClaim = function (state) {
$scope.resubmit = state;
$('#submit-dialog').modal('show');
};
function hideSubmitDialog() {
$('#submit-dialog').modal('hide');
$scope.resubmit = false;
}
$scope.cancelSubmitExpenseClaim = function () {
hideSubmitDialog();
};
$scope.returnExpenseClaim = function () {
$('#return-dialog').modal('show');
};
$scope.confirmReturnExpenseClaim = function (reason) {
hideReturnDialog();
return createEventAndSendNotifications(eventTypes.returned, reason);
};
function hideReturnDialog() {
$('#return-dialog').modal('hide');
}
$scope.cancelReturnExpenseClaim = function () {
hideReturnDialog();
};
$scope.paidExpenseClaim = function () {
$('#paid-dialog').modal('show');
};
$scope.confirmPaidExpenseClaim = function () {
createEventAndSendNotifications(eventTypes.paid)
.then(hidePaidDialog);
};
function hidePaidDialog() {
$('#paid-dialog').modal('hide');
}
$scope.cancelPaidExpenseClaim = function () {
hidePaidDialog();
};
$scope.confirmSubmitExpenseClaim = function () {
if ($scope.resubmit) $scope.selected.expenseClaim().expenseEvents = [eventForEventType($scope.selected.expenseClaim(), eventTypes.created)];
createEventAndSendNotifications(eventTypes.submitted);
};
$scope.resubmitExpenseClaim = function () {
$scope.submitExpenseClaim(true);
};
$scope.expenseClaimCreatedEvent = function (optionalExpenseClaim) {
return eventForEventType(optionalExpenseClaim || $scope.selected.expenseClaim(), eventTypes.created);
};
function createEventAndSendNotifications(eventType, reason) {
notify.setBusy();
$scope.selected.saveInProgress = true;
var expenseClaim = $scope.selected.expenseClaim();
var expenseClaimCreatedEvent = $scope.expenseClaimCreatedEvent(expenseClaim);
return $q.when(createEvent(eventType, reason))
.then(sendNotificationsToAllRoles, showExpenseEmailErrorAlert)
.then($scope.saveExpenseClaim, showExpenseEmailErrorAlert, showExpenseProgressAlert);
function renderTemplateContent(templateData) {
var task = $q.defer();
var templateFunction = $compile(templateData);
var templateElement = templateFunction($scope);
$timeout(function () {
$scope.$digest();
task.resolve(templateElement.html());
});
return task.promise;
}
function sendNotificationsToAllRoles() {
return LoggedInMemberService.getMemberForMemberId(expenseClaimCreatedEvent.memberId)
.then(function (member) {
logger.debug('sendNotification:', 'memberId', expenseClaimCreatedEvent.memberId, 'member', member);
var memberFullName = $filter('fullNameWithAlias')(member);
return $q.when(showExpenseProgressAlert('Preparing to email ' + memberFullName))
.then(hideSubmitDialog, showExpenseEmailErrorAlert, showExpenseProgressAlert)
.then(sendCreatorNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert)
.then(sendApproverNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert)
.then(sendTreasurerNotifications, showExpenseEmailErrorAlert, showExpenseProgressAlert);
function sendCreatorNotifications() {
if (eventType.notifyCreator) return sendNotificationsTo({
templateUrl: templateForEvent('creator', eventType),
memberIds: [expenseClaimCreatedEvent.memberId],
segmentType: 'directMail',
segmentNameSuffix: '',
destination: 'creator'
});
return false;
}
function sendApproverNotifications() {
if (eventType.notifyApprover) return sendNotificationsTo({
templateUrl: templateForEvent('approver', eventType),
memberIds: MemberService.allMemberIdsWithPrivilege('financeAdmin', $scope.members),
segmentType: 'expenseApprover',
segmentNameSuffix: 'approval ',
destination: 'approvers'
});
return false;
}
function sendTreasurerNotifications() {
if (eventType.notifyTreasurer) return sendNotificationsTo({
templateUrl: templateForEvent('treasurer', eventType),
memberIds: MemberService.allMemberIdsWithPrivilege('treasuryAdmin', $scope.members),
segmentType: 'expenseTreasurer',
segmentNameSuffix: 'payment ',
destination: 'treasurer'
});
return false;
}
function templateForEvent(role, eventType) {
return notificationsBaseUrl + '/' + role + '/' + eventType.description.toLowerCase().replace(' ', '-') + '-notification.html';
}
function sendNotificationsTo(templateAndNotificationMembers) {
logger.debug('sendNotificationsTo:', templateAndNotificationMembers);
var campaignName = 'Expense ' + eventType.description + ' notification (to ' + templateAndNotificationMembers.destination + ')';
var campaignNameAndMember = campaignName + ' (' + memberFullName + ')';
var segmentName = 'Expense notification ' + templateAndNotificationMembers.segmentNameSuffix + '(' + memberFullName + ')';
if (templateAndNotificationMembers.memberIds.length === 0) throw new Error('No members have been configured as ' + templateAndNotificationMembers.destination + ' therefore notifications for this step will fail!!');
return $templateRequest($sce.getTrustedResourceUrl(templateAndNotificationMembers.templateUrl))
.then(renderTemplateContent)
.then(populateContentSections)
.then(sendNotification(templateAndNotificationMembers))
.catch(showExpenseEmailErrorAlert);
function populateContentSections(expenseNotificationText) {
return {
sections: {
expense_id_url: 'Please click <a href="' + baseUrl() + '/#/admin/expenseId/' + expenseClaim.$id() + '" target="_blank">this link</a> to see the details of the above expense claim, or to make changes to it.',
expense_notification_text: expenseNotificationText
}
};
}
function sendNotification(templateAndNotificationMembers) {
return function (contentSections) {
return createOrSaveMailchimpSegment()
.then(saveSegmentDataToMember, showExpenseEmailErrorAlert, showExpenseProgressAlert)
.then(sendEmailCampaign, showExpenseEmailErrorAlert, showExpenseProgressAlert)
.then(notifyEmailSendComplete, showExpenseEmailErrorAlert, showExpenseSuccessAlert);
function createOrSaveMailchimpSegment() {
return MailchimpSegmentService.saveSegment('general', {segmentId: MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType)}, templateAndNotificationMembers.memberIds, segmentName, $scope.members);
}
function saveSegmentDataToMember(segmentResponse) {
MailchimpSegmentService.setMemberSegmentId(member, templateAndNotificationMembers.segmentType, segmentResponse.segment.id);
return LoggedInMemberService.saveMember(member);
}
function sendEmailCampaign() {
showExpenseProgressAlert('Sending ' + campaignNameAndMember);
return MailchimpConfig.getConfig()
.then(function (config) {
var campaignId = config.mailchimp.campaigns.expenseNotification.campaignId;
var segmentId = MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType);
logger.debug('about to replicateAndSendWithOptions with campaignName', campaignNameAndMember, 'campaign Id', campaignId, 'segmentId', segmentId);
return MailchimpCampaignService.replicateAndSendWithOptions({
campaignId: campaignId,
campaignName: campaignNameAndMember,
contentSections: contentSections,
segmentId: segmentId
});
})
.then(function () {
showExpenseProgressAlert('Sending of ' + campaignNameAndMember + ' was successful', true);
});
}
function notifyEmailSendComplete() {
showExpenseSuccessAlert('Sending of ' + campaignName + ' was successful. Check your inbox for progress.');
}
}
}
}
});
}
}
$scope.setExpenseItemFields = function () {
var expenseItem = $scope.selected.expenseItem();
if (expenseItem) {
expenseItem.expenseDate = DateUtils.asValueNoTime(expenseItem.expenseDate);
if (expenseItem.travel) expenseItem.travel.miles = NumberUtils.asNumber(expenseItem.travel.miles);
expenseItem.description = expenseItemDescription(expenseItem);
expenseItem.cost = expenseItemCost(expenseItem);
}
recalculateClaimCost();
};
$scope.prefixedExpenseItemDescription = function (expenseItem) {
if (!expenseItem) return '';
var prefix = expenseItem.expenseType && expenseItem.expenseType.travel ? expenseItem.expenseType.name + ' - ' : '';
return prefix + expenseItem.description;
};
function expenseItemDescription(expenseItem) {
var description;
if (!expenseItem) return '';
if (expenseItem.travel && expenseItem.expenseType.travel) {
description = [
expenseItem.travel.from,
'to',
expenseItem.travel.to,
expenseItem.travel.returnJourney ? 'return trip' : 'single trip',
'(' + expenseItem.travel.miles,
'miles',
expenseItem.travel.returnJourney ? 'x 2' : '',
'x',
parseInt(expenseItem.travel.costPerMile * 100) + 'p per mile)'
].join(' ');
} else {
description = expenseItem.description;
}
return description;
}
function expenseItemCost(expenseItem) {
var cost;
if (!expenseItem) return 0;
if (expenseItem.travel && expenseItem.expenseType.travel) {
cost = (NumberUtils.asNumber(expenseItem.travel.miles) *
(expenseItem.travel.returnJourney ? 2 : 1) *
NumberUtils.asNumber(expenseItem.travel.costPerMile));
}
else {
cost = expenseItem.cost;
}
noLogger.info(cost, 'from expenseItem=', expenseItem);
return NumberUtils.asNumber(cost, 2);
}
function refreshMembers() {
if (LoggedInMemberService.memberLoggedIn()) {
notify.progress('Refreshing member data...');
return MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) {
logger.debug('refreshMembers: found', members.length, 'members');
return $scope.members = members;
});
}
}
function memberCanEditClaim(expenseClaim) {
if (!expenseClaim) return false;
return memberOwnsClaim(expenseClaim) || LoggedInMemberService.allowFinanceAdmin();
}
function memberOwnsClaim(expenseClaim) {
if (!expenseClaim) return false;
return (LoggedInMemberService.loggedInMember().memberId === $scope.expenseClaimCreatedEvent(expenseClaim).memberId);
}
$scope.refreshExpenses = function () {
$scope.dataError = false;
logger.debug('refreshExpenses started');
notify.setBusy();
notify.progress('Filtering for ' + $scope.selected.expenseFilter.description + '...');
logger.debug('refreshing expenseFilter', $scope.selected.expenseFilter);
let noExpenseFound = function () {
$scope.dataError = true;
return notify.warning({
title: 'Expense claim could not be found',
message: 'Try opening again from the link in the notification email, or click Show All Expense Claims'
})
};
function query() {
if ($scope.selected.expenseFilter.description === SELECTED_EXPENSE && $routeParams.expenseId) {
return ExpenseClaimsService.getById($routeParams.expenseId)
.then(function (expense) {
if (!expense) {
return noExpenseFound();
} else {
return [expense];
}
})
.catch(noExpenseFound);
} else {
return ExpenseClaimsService.all();
}
}
return query()
.then(function (expenseClaims) {
$scope.unfilteredExpenseClaims = [];
$scope.expenseClaims = _.chain(expenseClaims).filter(function (expenseClaim) {
return $scope.allowAdminFunctions() ? ($scope.selected.showOnlyMine ? memberOwnsClaim(expenseClaim) : true) : memberCanEditClaim(expenseClaim);
}).filter(function (expenseClaim) {
$scope.unfilteredExpenseClaims.push(expenseClaim);
return $scope.selected.expenseFilter.filter(expenseClaim);
}).sortBy(function (expenseClaim) {
var expenseClaimLatestEvent = $scope.expenseClaimLatestEvent(expenseClaim);
return expenseClaimLatestEvent ? expenseClaimLatestEvent.date : true;
}).reverse().value();
let outcome = 'Found ' + $scope.expenseClaims.length + ' expense claim(s)';
notify.progress(outcome);
logger.debug('refreshExpenses finished', outcome);
notify.clearBusy();
return $scope.expenseClaims;
}, notify.error)
.catch(notify.error);
};
$q.when(refreshMembers())
.then($scope.refreshExpenses)
.then(notify.setReady)
.catch(notify.error);
}]
);
/* concatenated from client/src/app/js/filters.js */
angular.module('ekwgApp')
.factory('FilterUtils', function () {
return {
nameFilter: function (alias) {
return alias ? 'fullNameWithAlias' : 'fullName';
}
};
})
.filter('keepLineFeeds', function () {
return function (input) {
if (!input) return input;
return input
.replace(/(\r\n|\r|\n)/g, '<br/>')
.replace(/\t/g, ' ')
.replace(/ /g, ' ');
}
})
.filter('lineFeedsToBreaks', function () {
return function (input) {
if (!input) return input;
return input
.replace(/(\r\n|\r|\n)/g, '<br/>')
}
})
.filter('displayName', function () {
return function (member) {
return member === undefined ? null : (member.firstName + ' ' + (member.hideSurname ? '' : member.lastName)).trim();
}
})
.filter('fullName', function () {
return function (member, defaultValue) {
return member === undefined ? defaultValue || '(deleted member)' : (member.firstName + ' ' + member.lastName).trim();
}
})
.filter('fullNameWithAlias', ["$filter", function ($filter) {
return function (member, defaultValue) {
return member ? ($filter('fullName')(member, defaultValue)) + (member.nameAlias ? ' (' + member.nameAlias + ')' : '') : defaultValue;
}
}])
.filter('fullNameWithAliasOrMe', ["$filter", "LoggedInMemberService", function ($filter, LoggedInMemberService) {
return function (member, defaultValue, memberId) {
return member ? (LoggedInMemberService.loggedInMember().memberId === member.$id() && member.$id() === memberId ? "Me" : ($filter('fullName')(member, defaultValue)) + (member.nameAlias ? ' (' + member.nameAlias + ')' : '')) : defaultValue;
}
}])
.filter('firstName', ["$filter", function ($filter) {
return function (member, defaultValue) {
return s.words($filter('fullName')(member, defaultValue))[0];
}
}])
.filter('memberIdsToFullNames', ["$filter", function ($filter) {
return function (memberIds, members, defaultValue) {
return _(memberIds).map(function (memberId) {
return $filter('memberIdToFullName')(memberId, members, defaultValue);
}).join(', ');
}
}])
.filter('memberIdToFullName', ["$filter", "MemberService", "FilterUtils", function ($filter, MemberService, FilterUtils) {
return function (memberId, members, defaultValue, alias) {
return $filter(FilterUtils.nameFilter(alias))(MemberService.toMember(memberId, members), defaultValue);
}
}])
.filter('memberIdToFirstName', ["$filter", "MemberService", function ($filter, MemberService) {
return function (memberId, members, defaultValue) {
return $filter('firstName')(MemberService.toMember(memberId, members), defaultValue);
}
}])
.filter('asMoney', ["NumberUtils", function (NumberUtils) {
return function (number) {
return isNaN(number) ? '' : '£' + NumberUtils.asNumber(number).toFixed(2);
}
}])
.filter('humanize', function () {
return function (string) {
return s.humanize(string);
}
})
.filter('sumValues', ["NumberUtils", function (NumberUtils) {
return function (items, propertyName) {
return NumberUtils.sumValues(items, propertyName);
}
}])
.filter('walkSummary', ["$filter", function ($filter) {
return function (walk) {
return walk === undefined ? null : $filter('displayDate')(walk.walkDate) + " led by " + (walk.displayName || walk.contactName || "unknown") + " (" + (walk.briefDescriptionAndStartPoint || 'no description') + ')';
}
}])
.filter('meetupEventSummary', ["$filter", function ($filter) {
return function (meetupEvent) {
return meetupEvent ? $filter('displayDate')(meetupEvent.startTime) + " (" + meetupEvent.title + ')' : null;
}
}])
.filter('asWalkEventType', ["WalksReferenceService", function (WalksReferenceService) {
return function (eventTypeString, field) {
var eventType = WalksReferenceService.toEventType(eventTypeString);
return eventType && field ? eventType[field] : eventType;
}
}])
.filter('asEventNote', function () {
return function (event) {
return _.compact([event.description, event.reason]).join(', ');
}
})
.filter('asChangedItemsTooltip', ["$filter", function ($filter) {
return function (event, members) {
return _(event.data).map(function (value, key) {
return s.humanize(key) + ': ' + $filter('toAuditDeltaValue')(value, key, members);
}).join(', ');
}
}])
.filter('valueOrDefault', function () {
return function (value, defaultValue) {
return value || defaultValue || '(none)';
}
})
.filter('toAuditDeltaValue', ["$filter", function ($filter) {
return function (value, fieldName, members, defaultValue) {
switch (fieldName) {
case 'walkDate':
return $filter('displayDate')(value);
case 'walkLeaderMemberId':
return $filter('memberIdToFullName')(value, members, defaultValue);
default:
return $filter('valueOrDefault')(value, defaultValue);
}
}
}])
.filter('toAuditDeltaChangedItems', function () {
return function (dataAuditDeltaInfoItems) {
return _(dataAuditDeltaInfoItems).pluck('fieldName').map(s.humanize).join(', ');
}
})
.filter('asWalkValidationsList', function () {
return function (walkValidations) {
var lastItem = _.last(walkValidations);
var firstItems = _.without(walkValidations, lastItem);
var joiner = firstItems.length > 0 ? ' and ' : '';
return firstItems.join(', ') + joiner + lastItem;
}
})
.filter('idFromRecord', function () {
return function (mongoRecord) {
return mongoRecord.$id;
}
})
.filter('eventTimes', function () {
return function (socialEvent) {
var eventTimes = socialEvent.eventTimeStart;
if (socialEvent.eventTimeEnd) eventTimes += ' - ' + socialEvent.eventTimeEnd;
return eventTimes;
}
})
.filter('displayDate', ["DateUtils", function (DateUtils) {
return function (dateValue) {
return DateUtils.displayDate(dateValue);
}
}])
.filter('displayDay', ["DateUtils", function (DateUtils) {
return function (dateValue) {
return DateUtils.displayDay(dateValue);
}
}])
.filter('displayDates', ["$filter", function ($filter) {
return function (dateValues) {
return _(dateValues).map(function (dateValue) {
return $filter('displayDate')(dateValue);
}).join(', ');
}
}])
.filter('displayDateAndTime', ["DateUtils", function (DateUtils) {
return function (dateValue) {
return DateUtils.displayDateAndTime(dateValue);
}
}])
.filter('fromExcelDate', ["DateUtils", function (DateUtils) {
return function (dateValue) {
return DateUtils.displayDate(dateValue);
}
}])
.filter('lastLoggedInDateDisplayed', ["DateUtils", function (DateUtils) {
return function (dateValue) {
return DateUtils.displayDateAndTime(dateValue);
}
}])
.filter('lastConfirmedDateDisplayed', ["DateUtils", function (DateUtils) {
return function (member) {
return member && member.profileSettingsConfirmedAt ? 'by ' + (member.profileSettingsConfirmedBy || 'member') + ' at ' + DateUtils.displayDateAndTime(member.profileSettingsConfirmedAt) : 'not confirmed yet';
}
}])
.filter('createdAudit', ["StringUtils", function (StringUtils) {
return function (resource, members) {
return StringUtils.formatAudit(resource.createdBy, resource.createdDate, members)
}
}])
.filter('updatedAudit', ["StringUtils", function (StringUtils) {
return function (resource, members) {
return StringUtils.formatAudit(resource.updatedBy, resource.updatedDate, members)
}
}]);
/* concatenated from client/src/app/js/forgotPasswordController.js */
angular.module("ekwgApp")
.controller("ForgotPasswordController", ["$q", "$log", "$scope", "$rootScope", "$location", "$routeParams", "EmailSubscriptionService", "MemberService", "LoggedInMemberService", "URLService", "MailchimpConfig", "MailchimpSegmentService", "MailchimpCampaignService", "Notifier", "ValidationUtils", "close", function ($q, $log, $scope, $rootScope, $location, $routeParams, EmailSubscriptionService,
MemberService, LoggedInMemberService, URLService, MailchimpConfig, MailchimpSegmentService,
MailchimpCampaignService, Notifier, ValidationUtils, close) {
var logger = $log.getInstance("ForgotPasswordController");
$log.logLevels["ForgotPasswordController"] = $log.LEVEL.OFF;
$scope.notify = {};
var notify = Notifier($scope.notify);
$scope.showSubmit = true;
$scope.FORGOTTEN_PASSWORD_SEGMENT = "Forgotten Password";
$scope.forgottenPasswordCredentials = {};
$scope.actions = {
close: function () {
close();
},
submittable: function () {
var onePopulated = ValidationUtils.fieldPopulated($scope.forgottenPasswordCredentials, "credentialOne");
var twoPopulated = ValidationUtils.fieldPopulated($scope.forgottenPasswordCredentials, "credentialTwo");
logger.info("notSubmittable: onePopulated", onePopulated, "twoPopulated", twoPopulated);
return twoPopulated && onePopulated;
},
submit: function () {
var userDetails = "User Name " + $scope.forgottenPasswordCredentials.credentialOne + " and Membership Number " + $scope.forgottenPasswordCredentials.credentialTwo;
notify.setBusy();
$scope.showSubmit = false;
notify.success("Checking our records for " + userDetails, true);
if ($scope.forgottenPasswordCredentials.credentialOne.length === 0 || $scope.forgottenPasswordCredentials.credentialTwo.length === 0) {
$scope.showSubmit = true;
notify.error({
title: "Incorrect information entered",
message: "Please enter both a User Name and a Membership Number"
});
} else {
var forgotPasswordData = {loginResponse: {memberLoggedIn: false}};
var message;
LoggedInMemberService.getMemberForResetPassword($scope.forgottenPasswordCredentials.credentialOne, $scope.forgottenPasswordCredentials.credentialTwo)
.then(function (member) {
if (_.isEmpty(member)) {
message = "No member was found with " + userDetails;
forgotPasswordData.loginResponse.alertMessage = message;
$scope.showSubmit = true;
return {
forgotPasswordData: forgotPasswordData, notifyObject: {
title: "Incorrect information entered", message: message
}
};
} else if (!member.mailchimpLists.general.subscribed) {
message = "Sorry, " + userDetails + " is not setup in our system to receive emails";
forgotPasswordData.member = member;
forgotPasswordData.loginResponse.alertMessage = message;
$scope.showSubmit = true;
return {
forgotPasswordData: forgotPasswordData, notifyObject: {
title: "Message cannot be sent", message: message
}
};
} else {
LoggedInMemberService.setPasswordResetId(member);
EmailSubscriptionService.resetUpdateStatusForMember(member);
logger.debug("saving member", member);
$scope.forgottenPasswordMember = member;
member.$saveOrUpdate(sendForgottenPasswordEmailToMember, sendForgottenPasswordEmailToMember, saveFailed, saveFailed);
forgotPasswordData.member = member;
forgotPasswordData.loginResponse.alertMessage = "New password requested from login screen";
return {forgotPasswordData: forgotPasswordData};
}
}).then(function (response) {
return LoggedInMemberService.auditMemberLogin($scope.forgottenPasswordCredentials.credentialOne, "", response.forgotPasswordData.member, response.forgotPasswordData.loginResponse)
.then(function () {
if (response.notifyObject) {
notify.error(response.notifyObject)
}
});
});
}
}
};
function saveFailed(error) {
notify.error({title: "The password reset failed", message: error});
}
function getMailchimpConfig() {
return MailchimpConfig.getConfig()
.then(function (config) {
$scope.mailchimpConfig = config.mailchimp;
});
}
function createOrSaveForgottenPasswordSegment() {
return MailchimpSegmentService.saveSegment("general", {segmentId: $scope.mailchimpConfig.segments.general.forgottenPasswordSegmentId}, [{id: $scope.forgottenPasswordMember.$id()}], $scope.FORGOTTEN_PASSWORD_SEGMENT, [$scope.forgottenPasswordMember]);
}
function saveSegmentDataToMailchimpConfig(segmentResponse) {
return MailchimpConfig.getConfig()
.then(function (config) {
config.mailchimp.segments.general.forgottenPasswordSegmentId = segmentResponse.segment.id;
MailchimpConfig.saveConfig(config);
});
}
function sendForgottenPasswordCampaign() {
var member = $scope.forgottenPasswordMember.firstName + " " + $scope.forgottenPasswordMember.lastName;
return MailchimpConfig.getConfig()
.then(function (config) {
logger.debug("config.mailchimp.campaigns.forgottenPassword.campaignId", config.mailchimp.campaigns.forgottenPassword.campaignId);
logger.debug("config.mailchimp.segments.general.forgottenPasswordSegmentId", config.mailchimp.segments.general.forgottenPasswordSegmentId);
return MailchimpCampaignService.replicateAndSendWithOptions({
campaignId: config.mailchimp.campaigns.forgottenPassword.campaignId,
campaignName: "EKWG website password reset instructions (" + member + ")",
segmentId: config.mailchimp.segments.general.forgottenPasswordSegmentId
});
});
}
function updateGeneralList() {
return EmailSubscriptionService.createBatchSubscriptionForList("general", [$scope.forgottenPasswordMember]);
}
function sendForgottenPasswordEmailToMember() {
$q.when(notify.success("Sending forgotten password email"))
.then(updateGeneralList)
.then(getMailchimpConfig)
.then(createOrSaveForgottenPasswordSegment)
.then(saveSegmentDataToMailchimpConfig)
.then(sendForgottenPasswordCampaign)
.then(finalMessage)
.then(notify.clearBusy)
.catch(handleSendError);
}
function handleSendError(errorResponse) {
notify.error({
title: "Your email could not be sent",
message: (errorResponse.message || errorResponse) + (errorResponse.error ? (". Error was: " + ErrorMessageService.stringify(errorResponse.error)) : "")
});
}
function finalMessage() {
return notify.success({
title: "Message sent",
message: "We've sent a message to the email address we have for you. Please check your inbox and follow the instructions in the message."
})
}
}]
);
/* concatenated from client/src/app/js/googleMapsServices.js */
angular.module('ekwgApp')
.factory('GoogleMapsConfig', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) {
function getConfig() {
return $http.get('/googleMaps/config').then(function (response) {
return HTTPResponseService.returnResponse(response);
});
}
return {
getConfig: getConfig,
}
}]);
/* concatenated from client/src/app/js/homeController.js */
angular.module('ekwgApp')
.controller('HomeController', ["$log", "$scope", "$routeParams", "LoggedInMemberService", "ContentMetaDataService", "CommitteeReferenceData", "InstagramService", "SiteEditService", function ($log, $scope, $routeParams, LoggedInMemberService, ContentMetaDataService, CommitteeReferenceData, InstagramService, SiteEditService) {
var logger = $log.getInstance('HomeController');
$log.logLevels['HomeController'] = $log.LEVEL.OFF;
$scope.feeds = {instagram: {recentMedia: []}, facebook: {}};
ContentMetaDataService.getMetaData('imagesHome')
.then(function (contentMetaData) {
$scope.interval = 5000;
$scope.slides = contentMetaData.files;
});
InstagramService.recentMedia()
.then(function (recentMediaResponse) {
$scope.feeds.instagram.recentMedia = _.take(recentMediaResponse.instagram, 14);
logger.debug("Refreshed social media", $scope.feeds.instagram.recentMedia, 'count =', $scope.feeds.instagram.recentMedia.length);
});
$scope.mediaUrlFor = function (media) {
logger.debug('mediaUrlFor:media', media);
return (media && media.images) ? media.images.standard_resolution.url : "";
};
$scope.mediaCaptionFor = function (media) {
logger.debug('mediaCaptionFor:media', media);
return media ? media.caption.text : "";
};
$scope.allowEdits = function () {
return SiteEditService.active() && LoggedInMemberService.allowContentEdits();
};
}]);
/* concatenated from client/src/app/js/howTo.js */
angular.module('ekwgApp')
.controller("HowToDialogController", ["$rootScope", "$log", "$q", "$scope", "$filter", "FileUtils", "DateUtils", "EKWGFileUpload", "DbUtils", "LoggedInMemberService", "ErrorMessageService", "MailchimpLinkService", "MailchimpCampaignService", "Notifier", "MemberResourcesReferenceData", "memberResource", "close", function ($rootScope, $log, $q, $scope, $filter, FileUtils, DateUtils, EKWGFileUpload, DbUtils, LoggedInMemberService, ErrorMessageService,
MailchimpLinkService, MailchimpCampaignService, Notifier, MemberResourcesReferenceData, memberResource, close) {
var logger = $log.getInstance("HowToDialogController");
$log.logLevels["HowToDialogController"] = $log.LEVEL.OFF;
$scope.notify = {};
var notify = Notifier($scope.notify);
notify.setBusy();
$scope.fileUtils = FileUtils;
$scope.mailchimpLinkService = MailchimpLinkService;
$scope.memberResourcesReferenceData = MemberResourcesReferenceData;
$scope.memberResource = memberResource;
logger.debug("memberResourcesReferenceData:", $scope.memberResourcesReferenceData, "memberResource:", memberResource);
$scope.resourceDateCalendar = {
open: function () {
$scope.resourceDateCalendar.opened = true;
}
};
$scope.cancel = function () {
close();
};
$scope.onSelect = function (file) {
if (file) {
logger.debug("onSelect:file:about to upload ->", file);
$scope.uploadedFile = file;
EKWGFileUpload.onFileSelect(file, notify, "memberResources")
.then(function (fileNameData) {
logger.debug("onSelect:file:upload complete -> fileNameData", fileNameData);
$scope.memberResource.data.fileNameData = fileNameData;
$scope.memberResource.data.fileNameData.title = $scope.oldTitle || file.name;
});
}
};
$scope.attach = function (file) {
$("#hidden-input").click();
};
$scope.save = function () {
notify.setBusy();
logger.debug("save ->", $scope.memberResource);
return $scope.memberResource.$saveOrUpdate(notify.success, notify.success, notify.error, notify.error)
.then($scope.hideDialog)
.then(notify.clearBusy)
.catch(handleError);
function handleError(errorResponse) {
notify.error({
title: "Your changes could not be saved",
message: (errorResponse && errorResponse.error ? (". Error was: " + JSON.stringify(errorResponse.error)) : "")
});
notify.clearBusy();
}
};
$scope.cancelChange = function () {
$q.when($scope.hideDialog()).then(notify.clearBusy);
};
$scope.campaignDate = function (campaign) {
return DateUtils.asValueNoTime(campaign.send_time || campaign.create_time);
};
$scope.campaignTitle = function (campaign) {
return campaign.title + " (" + $filter("displayDate")($scope.campaignDate(campaign)) + ")";
};
$scope.campaignChange = function () {
logger.debug("campaignChange:memberResource.data.campaign", $scope.memberResource.data.campaign);
if ($scope.memberResource.data.campaign) {
$scope.memberResource.title = $scope.memberResource.data.campaign.title;
$scope.memberResource.resourceDate = $scope.campaignDate($scope.memberResource.data.campaign);
}
};
$scope.performCampaignSearch = function (selectFirst) {
var campaignSearchTerm = $scope.memberResource.data.campaignSearchTerm;
if (campaignSearchTerm) {
notify.setBusy();
notify.progress({
title: "Email search",
message: "searching for campaigns matching '" + campaignSearchTerm + "'"
});
var options = {
limit: $scope.memberResource.data.campaignSearchLimit,
concise: true,
status: "sent",
campaignSearchTerm: campaignSearchTerm
};
options[$scope.memberResource.data.campaignSearchField] = campaignSearchTerm;
return MailchimpCampaignService.list(options).then(function (response) {
$scope.campaigns = response.data;
if (selectFirst) {
$scope.memberResource.data.campaign = _.first($scope.campaigns);
$scope.campaignChange();
} else {
logger.debug("$scope.memberResource.data.campaign", $scope.memberResource.data.campaign, "first campaign=", _.first($scope.campaigns))
}
logger.debug("response.data", response.data);
notify.success({
title: "Email search",
message: "Found " + $scope.campaigns.length + " campaigns matching '" + campaignSearchTerm + "'"
});
notify.clearBusy();
return true;
});
} else {
return $q.when(true);
}
};
$scope.hideDialog = function () {
$rootScope.$broadcast("memberResourcesChanged");
close();
};
$scope.editMode = $scope.memberResource.$id() ? "Edit" : "Add";
logger.debug("editMode:", $scope.editMode);
if ($scope.memberResource.resourceType === "email" && $scope.memberResource.$id()) {
$scope.performCampaignSearch(false).then(notify.clearBusy)
} else {
notify.clearBusy();
}
}])
.controller("HowToController", ["$rootScope", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "MailchimpLinkService", "FileUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "MailchimpSegmentService", "MailchimpCampaignService", "MemberResourcesReferenceData", "MailchimpConfig", "Notifier", "MemberResourcesService", "CommitteeReferenceData", "ModalService", "SiteEditService", function ($rootScope, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $scope, $filter, $routeParams,
$location, URLService, DateUtils, MailchimpLinkService, FileUtils, NumberUtils, LoggedInMemberService, MemberService,
ContentMetaDataService, MailchimpSegmentService, MailchimpCampaignService, MemberResourcesReferenceData,
MailchimpConfig, Notifier, MemberResourcesService, CommitteeReferenceData, ModalService, SiteEditService) {
var logger = $log.getInstance("HowToController");
$log.logLevels["HowToController"] = $log.LEVEL.OFF;
$scope.notify = {};
var notify = Notifier($scope.notify);
notify.setBusy();
$scope.fileUtils = FileUtils;
$scope.memberResourcesReferenceData = MemberResourcesReferenceData;
$scope.mailchimpLinkService = MailchimpLinkService;
$scope.destinationType = "";
$scope.members = [];
$scope.memberResources = [];
$scope.alertMessages = [];
$scope.allowConfirmDelete = false;
$scope.selected = {
addingNew: false,
};
$scope.isActive = function (memberResource) {
var active = SiteEditService.active() && LoggedInMemberService.memberLoggedIn() && memberResource === $scope.selected.memberResource;
logger.debug("isActive =", active, "with memberResource", memberResource);
return active;
};
$scope.allowAdd = function () {
return SiteEditService.active() && LoggedInMemberService.allowFileAdmin();
};
$scope.allowEdit = function (memberResource) {
return $scope.allowAdd() && memberResource && memberResource.$id();
};
$scope.allowDelete = function (memberResource) {
return $scope.allowEdit(memberResource);
};
var defaultMemberResource = function () {
return new MemberResourcesService({
data: {campaignSearchLimit: "1000", campaignSearchField: "title"},
resourceType: "email",
accessLevel: "hidden",
createdDate: DateUtils.nowAsValue(),
createdBy: LoggedInMemberService.loggedInMember().memberId
})
};
function removeDeleteOrAddOrInProgressFlags() {
$scope.allowConfirmDelete = false;
$scope.selected.addingNew = false;
}
$scope.delete = function () {
$scope.allowConfirmDelete = true;
};
$scope.cancelDelete = function () {
removeDeleteOrAddOrInProgressFlags();
};
$scope.confirmDelete = function () {
notify.setBusy();
function showDeleted() {
return notify.success("member resource was deleted successfully");
}
$scope.selected.memberResource.$remove(showDeleted, showDeleted, notify.error, notify.error)
.then($scope.hideDialog)
.then(refreshMemberResources)
.then(removeDeleteOrAddOrInProgressFlags)
.then(notify.clearBusy);
};
$scope.selectMemberResource = function (memberResource) {
logger.debug("selectMemberResource with memberResource", memberResource, "$scope.selected.addingNew", $scope.selected.addingNew);
if (!$scope.selected.addingNew) {
$scope.selected.memberResource = memberResource;
}
};
$scope.edit = function () {
ModalService.showModal({
templateUrl: "partials/howTo/how-to-dialog.html",
controller: "HowToDialogController",
preClose: function (modal) {
logger.debug("preClose event with modal", modal);
modal.element.modal("hide");
},
inputs: {
memberResource: $scope.selected.memberResource
}
}).then(function (modal) {
logger.debug("modal event with modal", modal);
modal.element.modal();
modal.close.then(function (result) {
logger.debug("close event with result", result);
});
})
};
$scope.add = function () {
$scope.selected.addingNew = true;
var memberResource = defaultMemberResource();
$scope.selected.memberResource = memberResource;
logger.debug("add:", memberResource);
$scope.edit();
};
$scope.hideDialog = function () {
removeDeleteOrAddOrInProgressFlags();
};
$scope.$on("memberResourcesChanged", function () {
refreshAll();
});
$scope.$on("memberResourcesChanged", function () {
refreshAll();
});
$scope.$on("memberLoginComplete", function () {
refreshAll();
});
$scope.$on("memberLogoutComplete", function () {
refreshAll();
});
$scope.$on("editSite", function (event, data) {
logger.debug("editSite:", data);
refreshAll();
});
function refreshMemberResources() {
MemberResourcesService.all()
.then(function (memberResources) {
if (URLService.hasRouteParameter("memberResourceId")) {
$scope.memberResources = _.filter(memberResources, function (memberResource) {
return memberResource.$id() === $routeParams.memberResourceId;
});
} else {
$scope.memberResources = _.chain(memberResources)
.filter(function (memberResource) {
return $scope.memberResourcesReferenceData.accessLevelFor(memberResource.accessLevel).filter();
}).sortBy("resourceDate")
.value()
.reverse();
logger.debug(memberResources.length, "memberResources", $scope.memberResources.length, "filtered memberResources");
}
});
}
function refreshAll() {
refreshMemberResources();
}
refreshAll();
}]);
/* concatenated from client/src/app/js/httpServices.js */
angular.module('ekwgApp')
.factory('HTTPResponseService', ["$log", function ($log) {
var logger = $log.getInstance('HTTPResponseService');
$log.logLevels['HTTPResponseService'] = $log.LEVEL.OFF;
function returnResponse(response) {
logger.debug('response.data=', response.data);
var returnObject = (typeof response.data === 'object') || !response.data ? response.data : JSON.parse(response.data);
logger.debug('returned ', typeof response.data, 'response status =', response.status, returnObject.length, 'response items:', returnObject);
return returnObject;
}
return {
returnResponse: returnResponse
}
}]);
/* concatenated from client/src/app/js/imageEditor.js */
angular.module('ekwgApp')
.controller('ImageEditController', ["$scope", "$location", "Upload", "$http", "$q", "$routeParams", "$window", "LoggedInMemberService", "ContentMetaDataService", "Notifier", "EKWGFileUpload", function($scope, $location, Upload, $http, $q, $routeParams, $window, LoggedInMemberService, ContentMetaDataService, Notifier, EKWGFileUpload) {
var notify = Notifier($scope);
$scope.imageSource = $routeParams.imageSource;
applyAllowEdits();
$scope.onFileSelect = function(file) {
if (file) {
$scope.uploadedFile = file;
EKWGFileUpload.onFileSelect(file, notify, $scope.imageSource).then(function(fileNameData) {
$scope.currentImageMetaDataItem.image = $scope.imageMetaData.baseUrl + '/' + fileNameData.awsFileName;
console.log(' $scope.currentImageMetaDataItem.image', $scope.currentImageMetaDataItem.image);
});
}
};
$scope.refreshImageMetaData = function(imageSource) {
notify.setBusy();
$scope.imageSource = imageSource;
ContentMetaDataService.getMetaData(imageSource).then(function(contentMetaData) {
$scope.imageMetaData = contentMetaData;
notify.clearBusy();
}, function(response) {
notify.error(response);
});
};
$scope.refreshImageMetaData($scope.imageSource);
$scope.$on('memberLoginComplete', function() {
applyAllowEdits();
});
$scope.$on('memberLogoutComplete', function() {
applyAllowEdits();
});
$scope.exitBackToPreviousWindow = function() {
$window.history.back();
};
$scope.reverseSortOrder = function() {
$scope.imageMetaData.files = $scope.imageMetaData.files.reverse();
};
$scope.imageTitleLength = function() {
if ($scope.imageSource === 'imagesHome') {
return 50;
} else {
return 20
}
};
$scope.replace = function(imageMetaDataItem) {
$scope.files = [];
$scope.currentImageMetaDataItem = imageMetaDataItem;
$('#hidden-input').click();
};
$scope.moveUp = function(imageMetaDataItem) {
var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem);
if (currentIndex > 0) {
$scope.delete(imageMetaDataItem);
$scope.imageMetaData.files.splice(currentIndex - 1, 0, imageMetaDataItem);
}
};
$scope.moveDown = function(imageMetaDataItem) {
var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem);
if (currentIndex < $scope.imageMetaData.files.length) {
$scope.delete(imageMetaDataItem);
$scope.imageMetaData.files.splice(currentIndex + 1, 0, imageMetaDataItem);
}
};
$scope.delete = function(imageMetaDataItem) {
$scope.imageMetaData.files = _.without($scope.imageMetaData.files, imageMetaDataItem);
};
$scope.insertHere = function(imageMetaDataItem) {
var insertedImageMetaDataItem = new ContentMetaDataService.createNewMetaData(true);
var currentIndex = $scope.imageMetaData.files.indexOf(imageMetaDataItem);
$scope.imageMetaData.files.splice(currentIndex, 0, insertedImageMetaDataItem);
$scope.replace(insertedImageMetaDataItem);
};
$scope.currentImageMetaDataItemBeingUploaded = function(imageMetaDataItem) {
return ($scope.currentImageMetaDataItem && $scope.currentImageMetaDataItem.$$hashKey === imageMetaDataItem.$$hashKey);
};
$scope.saveAll = function() {
ContentMetaDataService.saveMetaData($scope.imageMetaData, saveOrUpdateSuccessful, notify.error)
.then(function(contentMetaData) {
$scope.exitBackToPreviousWindow();
}, function(response) {
notify.error(response);
});
};
function applyAllowEdits() {
$scope.allowEdits = LoggedInMemberService.allowContentEdits();
}
function saveOrUpdateSuccessful() {
notify.success('data for ' + $scope.imageMetaData.files.length + ' images was saved successfully.');
}
}]);
/* concatenated from client/src/app/js/indexController.js */
angular.module('ekwgApp')
.controller("IndexController", ["$q", "$cookieStore", "$log", "$scope", "$rootScope", "URLService", "LoggedInMemberService", "ProfileConfirmationService", "AuthenticationModalsService", "Notifier", "DateUtils", function ($q, $cookieStore, $log, $scope, $rootScope, URLService, LoggedInMemberService, ProfileConfirmationService, AuthenticationModalsService, Notifier, DateUtils) {
var logger = $log.getInstance("IndexController");
$log.logLevels["IndexController"] = $log.LEVEL.OFF;
$scope.notify = {};
var notify = Notifier($scope.notify);
logger.info('called IndexController');
$scope.ready = false;
$scope.year = DateUtils.asString(DateUtils.momentNow().valueOf(), undefined, "YYYY");
$scope.actions = {
forgotPassword: function () {
URLService.navigateTo("forgot-password");
},
loginOrLogout: function () {
if (LoggedInMemberService.memberLoggedIn()) {
LoggedInMemberService.logout();
} else {
URLService.navigateTo("login");
}
}
};
$scope.memberLoggedIn = function () {
return LoggedInMemberService.memberLoggedIn()
};
$scope.memberLoginStatus = function () {
if (LoggedInMemberService.memberLoggedIn()) {
var loggedInMember = LoggedInMemberService.loggedInMember();
return "Logout " + loggedInMember.firstName + " " + loggedInMember.lastName;
} else {
return "Login to EWKG Site";
}
};
$scope.allowEdits = function () {
return LoggedInMemberService.allowContentEdits();
};
$scope.isHome = function () {
return URLService.relativeUrlFirstSegment() === "/";
};
$scope.isOnPage = function (data) {
var matchedUrl = s.endsWith(URLService.relativeUrlFirstSegment(), data);
logger.debug("isOnPage", matchedUrl, "data=", data);
return matchedUrl;
};
$scope.isProfileOrAdmin = function () {
return $scope.isOnPage("profile") || $scope.isOnPage("admin");
};
}]);
/* concatenated from client/src/app/js/instagramServices.js */
angular.module('ekwgApp')
.factory('InstagramService', ["$http", "HTTPResponseService", function ($http, HTTPResponseService) {
function recentMedia() {
return $http.get('/instagram/recentMedia').then(HTTPResponseService.returnResponse);
}
return {
recentMedia: recentMedia,
}
}]);
/* concatenated from client/src/app/js/letterheadController.js */
angular.module('ekwgApp')
.controller('LetterheadController', ["$scope", "$location", function ($scope, $location) {
var pathParts = $location.path().replace('/letterhead/', '').split('/');
$scope.firstPart = _.first(pathParts);
$scope.lastPart = _.last(pathParts);
}]);
/* concatenated from client/src/app/js/links.js */
angular.module('ekwgApp')
.factory('ContactUsAmendService', ["$filter", "LoggedInMemberService", "DateUtils", function ($filter, LoggedInMemberService, DateUtils) {
}])
.controller('ContactUsController', ["$log", "$rootScope", "$routeParams", "$scope", "CommitteeReferenceData", "LoggedInMemberService", function ($log, $rootScope, $routeParams, $scope, CommitteeReferenceData, LoggedInMemberService) {
var logger = $log.getInstance('ContactUsController');
$log.logLevels['ContactUsController'] = $log.LEVEL.OFF;
$scope.contactUs = {
ready: function () {
return CommitteeReferenceData.ready;
}
};
$scope.allowEdits = function () {
return LoggedInMemberService.allowMemberAdminEdits();
}
}]);
/* concatenated from client/src/app/js/loggedInMemberService.js */
angular.module('ekwgApp')
.factory('LoggedInMemberService', ["$rootScope", "$q", "$routeParams", "$cookieStore", "URLService", "MemberService", "MemberAuditService", "DateUtils", "NumberUtils", "$log", function ($rootScope, $q, $routeParams, $cookieStore, URLService, MemberService, MemberAuditService, DateUtils, NumberUtils, $log) {
var logger = $log.getInstance('LoggedInMemberService');
var noLogger = $log.getInstance('NoLogger');
$log.logLevels['NoLogger'] = $log.LEVEL.OFF;
$log.logLevels['LoggedInMemberService'] = $log.LEVEL.OFF;
function loggedInMember() {
if (!getCookie('loggedInMember')) setCookie('loggedInMember', {});
return getCookie('loggedInMember');
}
function loginResponse() {
if (!getCookie('loginResponse')) setCookie('loginResponse', {memberLoggedIn: false});
return getCookie('loginResponse');
}
function showResetPassword() {
return getCookie('showResetPassword');
}
function allowContentEdits() {
return memberLoggedIn() ? loggedInMember().contentAdmin : false;
}
function allowMemberAdminEdits() {
return loginResponse().memberLoggedIn ? loggedInMember().memberAdmin : false;
}
function allowFinanceAdmin() {
return loginResponse().memberLoggedIn ? loggedInMember().financeAdmin : false;
}
function allowCommittee() {
return loginResponse().memberLoggedIn ? loggedInMember().committee : false;
}
function allowTreasuryAdmin() {
return loginResponse().memberLoggedIn ? loggedInMember().treasuryAdmin : false;
}
function allowFileAdmin() {
return loginResponse().memberLoggedIn ? loggedInMember().fileAdmin : false;
}
function memberLoggedIn() {
return !_.isEmpty(loggedInMember()) && loginResponse().memberLoggedIn;
}
function showLoginPromptWithRouteParameter(routeParameter) {
if (URLService.hasRouteParameter(routeParameter) && !memberLoggedIn()) $('#login-dialog').modal();
}
function allowWalkAdminEdits() {
return memberLoggedIn() ? loggedInMember().walkAdmin : false;
}
function allowSocialAdminEdits() {
return memberLoggedIn() ? loggedInMember().socialAdmin : false;
}
function allowSocialDetailView() {
return memberLoggedIn() ? loggedInMember().socialMember : false;
}
function logout() {
var member = loggedInMember();
var loginResponseValue = loginResponse();
if (!_.isEmpty(member)) {
loginResponseValue.alertMessage = 'The member ' + member.userName + ' logged out successfully';
auditMemberLogin(member.userName, undefined, member, loginResponseValue)
}
removeCookie('loginResponse');
removeCookie('loggedInMember');
removeCookie('showResetPassword');
removeCookie('editSite');
$rootScope.$broadcast('memberLogoutComplete');
}
function auditMemberLogin(userName, password, member, loginResponse) {
var audit = new MemberAuditService({
userName: userName,
password: password,
loginTime: DateUtils.nowAsValue(),
loginResponse: loginResponse
});
if (!_.isEmpty(member)) audit.member = member;
return audit.$save();
}
function setCookie(key, value) {
noLogger.debug('setting cookie ' + key + ' with value ', value);
$cookieStore.put(key, value);
}
function removeCookie(key) {
logger.info('removing cookie ' + key);
$cookieStore.remove(key);
}
function getCookie(key) {
var object = $cookieStore.get(key);
noLogger.debug('getting cookie ' + key + ' with value', object);
return object;
}
function login(userName, password) {
return getMemberForUserName(userName)
.then(function (member) {
removeCookie('showResetPassword');
var loginResponse = {};
if (!_.isEmpty(member)) {
loginResponse.memberLoggedIn = false;
if (!member.groupMember) {
loginResponse.alertMessage = 'Logins for member ' + userName + ' have been disabled. Please';
} else if (member.password !== password) {
loginResponse.alertMessage = 'The password was incorrectly entered for ' + userName + '. Please try again or';
} else if (member.expiredPassword) {
setCookie('showResetPassword', true);
loginResponse.alertMessage = 'The password for ' + userName + ' has expired. You must enter a new password before continuing. Alternatively';
} else {
loginResponse.memberLoggedIn = true;
loginResponse.alertMessage = 'The member ' + userName + ' logged in successfully';
setLoggedInMemberCookie(member);
}
} else {
removeCookie('loggedInMember');
loginResponse.alertMessage = 'The member ' + userName + ' was not recognised. Please try again or';
}
return {loginResponse: loginResponse, member: member};
})
.then(function (loginData) {
setCookie('loginResponse', loginData.loginResponse);
return auditMemberLogin(userName, password, loginData.member, loginData.loginResponse)
.then(function () {
logger.debug('loginResponse =', loginData.loginResponse);
return $rootScope.$broadcast('memberLoginComplete');
}
);
}, function (response) {
throw new Error('Something went wrong...' + response);
})
}
function setLoggedInMemberCookie(member) {
var memberId = member.$id();
var cookie = getCookie('loggedInMember');
if (_.isEmpty(cookie) || (cookie.memberId === memberId)) {
var newCookie = angular.extend(member, {memberId: memberId});
logger.debug('saving loggedInMember ->', newCookie);
setCookie('loggedInMember', newCookie);
} else {
logger.debug('not saving member (' + memberId + ') to cookie as not currently logged in member (' + cookie.memberId + ')', member);
}
}
function saveMember(memberToSave, saveCallback, errorSaveCallback) {
memberToSave.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback, errorSaveCallback)
.then(function () {
setLoggedInMemberCookie(memberToSave);
})
.then(function () {
$rootScope.$broadcast('memberSaveComplete');
});
}
function resetPassword(userName, newPassword, newPasswordConfirm) {
return getMemberForUserName(userName)
.then(validateNewPassword)
.then(saveSuccessfulPasswordReset)
.then(broadcastMemberLoginComplete)
.then(auditPasswordChange);
function validateNewPassword(member) {
var loginResponse = {memberLoggedIn: false};
var showResetPassword = true;
if (member.password === newPassword) {
loginResponse.alertMessage = 'The new password was the same as the old one for ' + member.userName + '. Please try again or';
} else if (!newPassword || newPassword.length < 6) {
loginResponse.alertMessage = 'The new password needs to be at least 6 characters long. Please try again or';
} else if (newPassword !== newPasswordConfirm) {
loginResponse.alertMessage = 'The new password was not confirmed correctly for ' + member.userName + '. Please try again or';
} else {
showResetPassword = false;
logger.debug('Saving new password for ' + member.userName + ' and removing expired status');
delete member.expiredPassword;
delete member.passwordResetId;
member.password = newPassword;
loginResponse.memberLoggedIn = true;
loginResponse.alertMessage = 'The password for ' + member.userName + ' was changed successfully';
}
return {loginResponse: loginResponse, member: member, showResetPassword: showResetPassword};
}
function saveSuccessfulPasswordReset(resetPasswordData) {
logger.debug('saveNewPassword.resetPasswordData:', resetPasswordData);
setCookie('loginResponse', resetPasswordData.loginResponse);
setCookie('showResetPassword', resetPasswordData.showResetPassword);
if (!resetPasswordData.showResetPassword) {
return resetPasswordData.member.$update().then(function () {
setLoggedInMemberCookie(resetPasswordData.member);
return resetPasswordData;
})
} else {
return resetPasswordData;
}
}
function auditPasswordChange(resetPasswordData) {
return auditMemberLogin(userName, resetPasswordData.member.password, resetPasswordData.member, resetPasswordData.loginResponse)
}
function broadcastMemberLoginComplete(resetPasswordData) {
$rootScope.$broadcast('memberLoginComplete');
return resetPasswordData
}
}
function getMemberForUserName(userName) {
return MemberService.query({userName: userName.toLowerCase()}, {limit: 1})
.then(function (queryResults) {
return (queryResults && queryResults.length > 0) ? queryResults[0] : {};
});
}
function getMemberForResetPassword(credentialOne, credentialTwo) {
var credentialOneCleaned = credentialOne.toLowerCase().trim();
var credentialTwoCleaned = credentialTwo.toUpperCase().trim();
var orOne = {$or: [{userName: {$eq: credentialOneCleaned}}, {email: {$eq: credentialOneCleaned}}]};
var orTwo = {$or: [{membershipNumber: {$eq: credentialTwoCleaned}}, {postcode: {$eq: credentialTwoCleaned}}]};
var criteria = {$and: [orOne, orTwo]};
logger.info("querying member using", criteria);
return MemberService.query(criteria, {limit: 1})
.then(function (queryResults) {
logger.info("queryResults:", queryResults);
return (queryResults && queryResults.length > 0) ? queryResults[0] : {};
});
}
function getMemberForMemberId(memberId) {
return MemberService.getById(memberId)
}
function getMemberByPasswordResetId(passwordResetId) {
return MemberService.query({passwordResetId: passwordResetId}, {limit: 1})
.then(function (queryResults) {
return (queryResults && queryResults.length > 0) ? queryResults[0] : {};
});
}
function setPasswordResetId(member) {
member.passwordResetId = NumberUtils.generateUid();
logger.debug('member.userName', member.userName, 'member.passwordResetId', member.passwordResetId);
return member;
}
return {
auditMemberLogin: auditMemberLogin,
setPasswordResetId: setPasswordResetId,
getMemberByPasswordResetId: getMemberByPasswordResetId,
getMemberForResetPassword: getMemberForResetPassword,
getMemberForUserName: getMemberForUserName,
getMemberForMemberId: getMemberForMemberId,
loggedInMember: loggedInMember,
loginResponse: loginResponse,
logout: logout,
login: login,
saveMember: saveMember,
resetPassword: resetPassword,
memberLoggedIn: memberLoggedIn,
allowContentEdits: allowContentEdits,
allowMemberAdminEdits: allowMemberAdminEdits,
allowWalkAdminEdits: allowWalkAdminEdits,
allowSocialAdminEdits: allowSocialAdminEdits,
allowSocialDetailView: allowSocialDetailView,
allowCommittee: allowCommittee,
allowFinanceAdmin: allowFinanceAdmin,
allowTreasuryAdmin: allowTreasuryAdmin,
allowFileAdmin: allowFileAdmin,
showResetPassword: showResetPassword,
showLoginPromptWithRouteParameter: showLoginPromptWithRouteParameter
};
}]
);
/* concatenated from client/src/app/js/loginController.js */
angular.module('ekwgApp')
.controller('LoginController', ["$log", "$scope", "$routeParams", "LoggedInMemberService", "AuthenticationModalsService", "Notifier", "URLService", "ValidationUtils", "close", function ($log, $scope, $routeParams, LoggedInMemberService, AuthenticationModalsService, Notifier, URLService, ValidationUtils, close) {
$scope.notify = {};
var logger = $log.getInstance('LoginController');
$log.logLevels['LoginController'] = $log.LEVEL.OFF;
var notify = Notifier($scope.notify);
LoggedInMemberService.logout();
$scope.actions = {
submittable: function () {
var userNamePopulated = ValidationUtils.fieldPopulated($scope.enteredMemberCredentials, "userName");
var passwordPopulated = ValidationUtils.fieldPopulated($scope.enteredMemberCredentials, "password");
logger.info("submittable: userNamePopulated", userNamePopulated, "passwordPopulated", passwordPopulated);
return passwordPopulated && userNamePopulated;
},
forgotPassword: function () {
URLService.navigateTo("forgot-password");
},
close: function () {
close()
},
login: function () {
notify.showContactUs(false);
notify.setBusy();
notify.progress({
busy: true,
title: "Logging in",
message: "using credentials for " + $scope.enteredMemberCredentials.userName + " - please wait"
});
LoggedInMemberService.login($scope.enteredMemberCredentials.userName, $scope.enteredMemberCredentials.password).then(function () {
var loginResponse = LoggedInMemberService.loginResponse();
if (LoggedInMemberService.memberLoggedIn()) {
close();
if (!LoggedInMemberService.loggedInMember().profileSettingsConfirmed) {
return URLService.navigateTo("mailing-preferences");
}
return true;
}
else if (LoggedInMemberService.showResetPassword()) {
return AuthenticationModalsService.showResetPasswordModal($scope.enteredMemberCredentials.userName, "Your password has expired, therefore you need to reset it to a new one before continuing.");
} else {
notify.showContactUs(true);
notify.error({
title: "Login failed",
message: loginResponse.alertMessage
});
}
});
},
}
}]
);
/* concatenated from client/src/app/js/mailChimpServices.js */
angular.module('ekwgApp')
.factory('MailchimpConfig', ["Config", function (Config) {
function getConfig() {
return Config.getConfig('mailchimp', {
mailchimp: {
interestGroups: {
walks: {interestGroupingId: undefined},
socialEvents: {interestGroupingId: undefined},
general: {interestGroupingId: undefined}
},
segments: {
walks: {segmentId: undefined},
socialEvents: {segmentId: undefined},
general: {
passwordResetSegmentId: undefined,
forgottenPasswordSegmentId: undefined,
committeeSegmentId: undefined
}
}
}
})
}
function saveConfig(config, key, saveCallback, errorSaveCallback) {
return Config.saveConfig('mailchimp', config, key, saveCallback, errorSaveCallback);
}
return {
getConfig: getConfig,
saveConfig: saveConfig
}
}])
.factory('MailchimpHttpService', ["$log", "$q", "$http", "MailchimpErrorParserService", function ($log, $q, $http, MailchimpErrorParserService) {
var logger = $log.getInstance('MailchimpHttpService');
$log.logLevels['MailchimpHttpService'] = $log.LEVEL.OFF;
function call(serviceCallType, method, url, data, params) {
var deferredTask = $q.defer();
deferredTask.notify(serviceCallType);
logger.debug(serviceCallType);
$http({
method: method,
data: data,
params: params,
url: url
}).then(function (response) {
var responseData = response.data;
var errorObject = MailchimpErrorParserService.extractError(responseData);
if (errorObject.error) {
var errorResponse = {message: serviceCallType + ' was not successful', error: errorObject.error};
logger.debug(errorResponse);
deferredTask.reject(errorResponse);
} else {
logger.debug('success', responseData);
deferredTask.resolve(responseData);
return responseData;
}
}).catch(function (response) {
var responseData = response.data;
var errorObject = MailchimpErrorParserService.extractError(responseData);
var errorResponse = {message: serviceCallType + ' was not successful', error: errorObject.error};
logger.debug(errorResponse);
deferredTask.reject(errorResponse);
});
return deferredTask.promise;
}
return {
call: call
}
}])
.factory('MailchimpErrorParserService', ["$log", function ($log) {
var logger = $log.getInstance('MailchimpErrorParserService');
$log.logLevels['MailchimpErrorParserService'] = $log.LEVEL.OFF;
function extractError(responseData) {
var error;
if (responseData && (responseData.error || responseData.errno)) {
error = {error: responseData}
} else if (responseData && responseData.errors && responseData.errors.length > 0) {
error = {
error: _.map(responseData.errors, function (error) {
var response = error.error;
if (error.email && error.email.email) {
response += (': ' + error.email.email);
}
return response;
}).join(', ')
}
} else {
error = {error: undefined}
}
logger.debug('responseData:', responseData, 'error:', error)
return error;
}
return {
extractError: extractError
}
}])
.factory('MailchimpLinkService', ["$log", "MAILCHIMP_APP_CONSTANTS", function ($log, MAILCHIMP_APP_CONSTANTS) {
var logger = $log.getInstance('MailchimpLinkService');
$log.logLevels['MailchimpLinkService'] = $log.LEVEL.OFF;
function campaignPreview(webId) {
return MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/preview-content-html?id=" + webId;
}
function campaignEdit(webId) {
return MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/preview-content-html?id=" + webId;
}
return {
campaignPreview: campaignPreview
}
}])
.factory('MailchimpGroupService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService) {
var logger = $log.getInstance('MailchimpGroupService');
$log.logLevels['MailchimpGroupService'] = $log.LEVEL.OFF;
var addInterestGroup = function (listType, interestGroupName, interestGroupingId) {
return MailchimpHttpService.call('Adding Mailchimp Interest Group for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/interestGroupAdd', {
interestGroupingId: interestGroupingId,
interestGroupName: interestGroupName
});
};
var deleteInterestGroup = function (listType, interestGroupName, interestGroupingId) {
return MailchimpHttpService.call('Deleting Mailchimp Interest Group for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/interestGroupDel', {
interestGroupingId: interestGroupingId,
interestGroupName: interestGroupName
});
};
var addInterestGrouping = function (listType, interestGroupingName, groups) {
return MailchimpHttpService.call('Adding Mailchimp Interest Grouping for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/interestGroupingAdd', {
groups: groups,
interestGroupingName: interestGroupingName
});
};
var deleteInterestGrouping = function (listType, interestGroupingId) {
return MailchimpHttpService.call('Deleting Mailchimp Interest Grouping for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/interestGroupingDel', {interestGroupingId: interestGroupingId});
};
var listInterestGroupings = function (listType) {
return MailchimpHttpService.call('Listing Mailchimp Interest Groupings for ' + listType, 'GET', 'mailchimp/lists/' + listType + '/interestGroupings');
};
var updateInterestGrouping = function (listType, interestGroupingId, interestGroupingName, interestGroupingValue) {
return MailchimpHttpService.call('Updating Mailchimp Interest Groupings for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/interestGroupingUpdate',
{
interestGroupingId: interestGroupingId,
interestGroupingName: interestGroupingName,
interestGroupingValue: interestGroupingValue
});
};
var updateInterestGroup = function (listType, oldName, newName) {
return function (config) {
var interestGroupingId = config.mailchimp.interestGroups[listType].interestGroupingId;
return MailchimpHttpService.call('Updating Mailchimp Interest Group for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/interestGroupUpdate',
{
interestGroupingId: interestGroupingId,
oldName: oldName,
newName: newName
})
.then(returnInterestGroupingId(interestGroupingId));
}
};
var saveInterestGroup = function (listType, oldName, newName) {
oldName = oldName.substring(0, 60);
newName = newName.substring(0, 60);
return MailchimpConfig.getConfig()
.then(updateInterestGroup(listType, oldName, newName))
.then(findInterestGroup(listType, newName));
};
var createInterestGroup = function (listType, interestGroupName) {
return MailchimpConfig.getConfig()
.then(createOrUpdateInterestGroup(listType, interestGroupName))
.then(findInterestGroup(listType, interestGroupName));
};
var createOrUpdateInterestGroup = function (listType, interestGroupName) {
return function (config) {
logger.debug('createOrUpdateInterestGroup using config', config);
var interestGroupingName = s.titleize(s.humanize(listType));
var interestGroupingId = config.mailchimp.interestGroups[listType].interestGroupingId;
if (interestGroupingId) {
return addInterestGroup(listType, interestGroupName, interestGroupingId)
.then(returnInterestGroupingId(interestGroupingId));
} else {
return addInterestGrouping(listType, interestGroupingName + ' Interest Groups', [interestGroupName])
.then(saveInterestGroupConfigAndReturnInterestGroupingId(listType, config));
}
}
};
var returnInterestGroupingId = function (interestGroupingId) {
return function (response) {
logger.debug('received', response, 'returning', interestGroupingId);
return interestGroupingId;
}
};
var saveInterestGroupConfigAndReturnInterestGroupingId = function (listType, config) {
return function (response) {
config.mailchimp.interestGroups[listType].interestGroupingId = response.id;
logger.debug('saving config', config);
return MailchimpConfig.saveConfig(config, function () {
logger.debug('config save was successful');
return response.id;
}, function (error) {
throw Error('config save was not successful. ' + error)
});
}
};
var findInterestGroup = function (listType, interestGroupName) {
return function (interestGroupingId) {
logger.debug('finding findInterestGroup ', interestGroupingId);
return listInterestGroupings(listType)
.then(filterInterestGroupings(interestGroupingId, interestGroupName));
}
};
var filterInterestGroupings = function (interestGroupingId, interestGroupName) {
return function (interestGroupings) {
logger.debug('filterInterestGroupings: interestGroupings passed in ', interestGroupings, 'for interestGroupingId', interestGroupingId);
var interestGrouping = _.find(interestGroupings, function (interestGrouping) {
return interestGrouping.id === interestGroupingId;
});
logger.debug('filterInterestGroupings: interestGrouping returned ', interestGrouping);
var interestGroup = _.find(interestGrouping.groups, function (group) {
return group.name === interestGroupName;
});
logger.debug('filterInterestGroupings: interestGroup returned', interestGroup);
return interestGroup;
}
};
return {
createInterestGroup: createInterestGroup,
saveInterestGroup: saveInterestGroup
}
}])
.factory('MailchimpSegmentService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", "EmailSubscriptionService", "MemberService", "StringUtils", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService, EmailSubscriptionService, MemberService, StringUtils) {
var logger = $log.getInstance('MailchimpSegmentService');
$log.logLevels['MailchimpSegmentService'] = $log.LEVEL.OFF;
function addSegment(listType, segmentName) {
return MailchimpHttpService.call('Adding Mailchimp segment for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentAdd', {segmentName: segmentName});
}
function resetSegment(listType, segmentId) {
return MailchimpHttpService.call('Resetting Mailchimp segment for ' + listType, 'PUT', 'mailchimp/lists/' + listType + '/segmentReset', {segmentId: segmentId});
}
function deleteSegment(listType, segmentId) {
return MailchimpHttpService.call('Deleting Mailchimp segment for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/segmentDel/' + segmentId);
}
function callRenameSegment(listType, segmentId, segmentName) {
return function () {
return renameSegment(listType, segmentId, segmentName);
}
}
function renameSegment(listType, segmentId, segmentNameInput) {
var segmentName = StringUtils.stripLineBreaks(StringUtils.left(segmentNameInput, 99), true);
logger.debug('renaming segment with name=\'' + segmentName + '\' length=' + segmentName.length);
return MailchimpHttpService.call('Renaming Mailchimp segment for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentRename', {
segmentId: segmentId,
segmentName: segmentName
});
}
function callAddSegmentMembers(listType, segmentId, segmentMembers) {
return function () {
return addSegmentMembers(listType, segmentId, segmentMembers);
}
}
function addSegmentMembers(listType, segmentId, segmentMembers) {
return MailchimpHttpService.call('Adding Mailchimp segment members ' + JSON.stringify(segmentMembers) + ' for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/segmentMembersAdd', {
segmentId: segmentId,
segmentMembers: segmentMembers
});
}
function callDeleteSegmentMembers(listType, segmentId, segmentMembers) {
return function () {
return deleteSegmentMembers(listType, segmentId, segmentMembers);
}
}
function deleteSegmentMembers(listType, segmentId, segmentMembers) {
return MailchimpHttpService.call('Deleting Mailchimp segment members ' + segmentMembers + ' for ' + listType, 'DELETE', 'mailchimp/lists/' + listType + '/segmentMembersDel', {
segmentId: segmentId,
segmentMembers: segmentMembers
});
}
function listSegments(listType) {
return MailchimpHttpService.call('Listing Mailchimp segments for ' + listType, 'GET', 'mailchimp/lists/' + listType + '/segments');
}
function buildSegmentMemberData(listType, memberIds, members) {
var segmentMembers = _.chain(memberIds)
.map(function (memberId) {
return MemberService.toMember(memberId, members)
})
.filter(function (member) {
return member && member.email;
})
.map(function (member) {
return EmailSubscriptionService.addMailchimpIdentifiersToRequest(member, listType);
})
.value();
if (!segmentMembers || segmentMembers.length === 0) throw new Error('No members were added to the ' + listType + ' email segment from the ' + memberIds.length + ' supplied members. Please check that they have a valid email address and are subscribed to ' + listType);
return segmentMembers;
}
function saveSegment(listType, mailchimpConfig, memberIds, segmentName, members) {
var segmentMembers = buildSegmentMemberData(listType, memberIds, members);
logger.debug('saveSegment:buildSegmentMemberData:', listType, memberIds, segmentMembers);
if (mailchimpConfig && mailchimpConfig.segmentId) {
var segmentId = mailchimpConfig.segmentId;
logger.debug('saveSegment:segmentId', mailchimpConfig);
return resetSegment(listType, segmentId)
.then(callRenameSegment(listType, segmentId, segmentName))
.then(addSegmentMembersDuringUpdate(listType, segmentId, segmentMembers))
.then(returnAddSegmentResponse({id: segmentId}));
} else {
return addSegment(listType, segmentName)
.then(addSegmentMembersDuringAdd(listType, segmentMembers))
}
}
function returnAddSegmentResponse(addSegmentResponse) {
return function (addSegmentMembersResponse) {
return {members: addSegmentMembersResponse.members, segment: addSegmentResponse};
};
}
function returnAddSegmentAndMemberResponse(addSegmentResponse) {
return function (addMemberResponse) {
return ({segment: addSegmentResponse, members: addMemberResponse});
};
}
function addSegmentMembersDuringUpdate(listType, segmentId, segmentMembers) {
return function (renameSegmentResponse) {
if (segmentMembers.length > 0) {
return addSegmentMembers(listType, segmentId, segmentMembers)
.then(returnAddSegmentAndMemberResponse(renameSegmentResponse));
} else {
return {segment: renameSegmentResponse.id, members: {}};
}
}
}
function addSegmentMembersDuringAdd(listType, segmentMembers) {
return function (addSegmentResponse) {
if (segmentMembers.length > 0) {
return addSegmentMembers(listType, addSegmentResponse.id, segmentMembers)
.then(returnAddSegmentAndMemberResponse(addSegmentResponse));
} else {
return {segment: addSegmentResponse, members: {}};
}
}
}
function getMemberSegmentId(member, segmentType) {
if (member.mailchimpSegmentIds) return member.mailchimpSegmentIds[segmentType];
}
function setMemberSegmentId(member, segmentType, segmentId) {
if (!member.mailchimpSegmentIds) member.mailchimpSegmentIds = {};
member.mailchimpSegmentIds[segmentType] = segmentId;
}
function formatSegmentName(prefix) {
var date = ' (' + DateUtils.nowAsValue() + ')';
var segmentName = prefix.substring(0, 99 - date.length) + date;
logger.debug('segmentName', segmentName, 'length', segmentName.length);
return segmentName;
}
return {
formatSegmentName: formatSegmentName,
saveSegment: saveSegment,
deleteSegment: deleteSegment,
getMemberSegmentId: getMemberSegmentId,
setMemberSegmentId: setMemberSegmentId
}
}])
.factory('MailchimpListService', ["$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", "EmailSubscriptionService", "MemberService", function ($log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService, EmailSubscriptionService, MemberService) {
var logger = $log.getInstance('MailchimpListService');
$log.logLevels['MailchimpListService'] = $log.LEVEL.OFF;
var listSubscribers = function (listType) {
return MailchimpHttpService.call('Listing Mailchimp subscribers for ' + listType, 'GET', 'mailchimp/lists/' + listType);
};
var batchUnsubscribe = function (listType, subscribers) {
return MailchimpHttpService.call('Batch unsubscribing members from Mailchimp List for ' + listType, 'POST', 'mailchimp/lists/' + listType + '/batchUnsubscribe', subscribers);
};
var batchUnsubscribeMembers = function (listType, allMembers, notificationCallback) {
return listSubscribers(listType)
.then(filterSubscriberResponsesForUnsubscriptions(listType, allMembers))
.then(batchUnsubscribeForListType(listType, allMembers, notificationCallback))
.then(returnUpdatedMembers);
};
function returnUpdatedMembers() {
return MemberService.all();
}
function batchUnsubscribeForListType(listType, allMembers, notificationCallback) {
return function (subscribers) {
if (subscribers.length > 0) {
return batchUnsubscribe(listType, subscribers)
.then(removeSubscriberDetailsFromMembers(listType, allMembers, subscribers, notificationCallback));
} else {
notificationCallback('No members needed to be unsubscribed from ' + listType + ' list');
}
}
}
function removeSubscriberDetailsFromMembers(listType, allMembers, subscribers, notificationCallback) {
return function () {
var updatedMembers = _.chain(subscribers)
.map(function (subscriber) {
var member = EmailSubscriptionService.responseToMember(listType, allMembers, subscriber);
if (member) {
member.mailchimpLists[listType] = {subscribed: false, updated: true};
member.$saveOrUpdate();
} else {
notificationCallback('Could not find member from ' + listType + ' response containing data ' + JSON.stringify(subscriber));
}
return member;
})
.filter(function (member) {
return member;
})
.value();
$q.all(updatedMembers).then(function () {
notificationCallback('Successfully unsubscribed ' + updatedMembers.length + ' member(s) from ' + listType + ' list');
return updatedMembers;
})
}
}
function filterSubscriberResponsesForUnsubscriptions(listType, allMembers) {
return function (listResponse) {
return _.chain(listResponse.data)
.filter(function (subscriber) {
return EmailSubscriptionService.includeSubscriberInUnsubscription(listType, allMembers, subscriber);
})
.map(function (subscriber) {
return {
email: subscriber.email,
euid: subscriber.euid,
leid: subscriber.leid
};
})
.value();
}
}
return {
batchUnsubscribeMembers: batchUnsubscribeMembers
}
}])
.factory('MailchimpCampaignService', ["MAILCHIMP_APP_CONSTANTS", "$log", "$rootScope", "$q", "$filter", "DateUtils", "MailchimpConfig", "MailchimpHttpService", function (MAILCHIMP_APP_CONSTANTS, $log, $rootScope, $q, $filter, DateUtils, MailchimpConfig, MailchimpHttpService) {
var logger = $log.getInstance('MailchimpCampaignService');
$log.logLevels['MailchimpCampaignService'] = $log.LEVEL.OFF;
function addCampaign(campaignId, campaignName) {
return MailchimpHttpService.call('Adding Mailchimp campaign ' + campaignId + ' with name ' + campaignName, 'POST', 'mailchimp/campaigns/' + campaignId + '/campaignAdd', {campaignName: campaignName});
}
function deleteCampaign(campaignId) {
return MailchimpHttpService.call('Deleting Mailchimp campaign ' + campaignId, 'DELETE', 'mailchimp/campaigns/' + campaignId + '/delete');
}
function getContent(campaignId) {
return MailchimpHttpService.call('Getting Mailchimp content for campaign ' + campaignId, 'GET', 'mailchimp/campaigns/' + campaignId + '/content');
}
function list(options) {
return MailchimpHttpService.call('Listing Mailchimp campaigns', 'GET', 'mailchimp/campaigns/list', {}, options);
}
function setContent(campaignId, contentSections) {
return contentSections ? MailchimpHttpService.call('Setting Mailchimp content for campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/update', {
updates: {
name: "content",
value: contentSections
}
}) : $q.when({
result: "success",
campaignId: campaignId,
message: "setContent skipped as no content provided"
})
}
function setOrClearSegment(replicatedCampaignId, optionalSegmentId) {
if (optionalSegmentId) {
return setSegmentId(replicatedCampaignId, optionalSegmentId);
} else {
return clearSegment(replicatedCampaignId)
}
}
function setSegmentId(campaignId, segmentId) {
return setSegmentOpts(campaignId, {saved_segment_id: segmentId});
}
function clearSegment(campaignId) {
return setSegmentOpts(campaignId, []);
}
function setSegmentOpts(campaignId, value) {
return MailchimpHttpService.call('Setting Mailchimp segment opts for campaign ' + campaignId + ' with value ' + JSON.stringify(value), 'POST', 'mailchimp/campaigns/' + campaignId + '/update', {
updates: {
name: "segment_opts",
value: value
}
});
}
function setCampaignOptions(campaignId, campaignName, otherOptions) {
var value = angular.extend({}, {
title: campaignName.substring(0, 99),
subject: campaignName
}, otherOptions);
return MailchimpHttpService.call('Setting Mailchimp campaign options for id ' + campaignId + ' with ' + JSON.stringify(value), 'POST', 'mailchimp/campaigns/' + campaignId + '/update', {
updates: {
name: "options",
value: value
}
});
}
function replicateCampaign(campaignId) {
return MailchimpHttpService.call('Replicating Mailchimp campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/replicate');
}
function sendCampaign(campaignId) {
if (!MAILCHIMP_APP_CONSTANTS.allowSendCampaign) throw new Error('You cannot send campaign ' + campaignId + ' as sending has been disabled');
return MailchimpHttpService.call('Sending Mailchimp campaign ' + campaignId, 'POST', 'mailchimp/campaigns/' + campaignId + '/send');
}
function listCampaigns() {
return MailchimpHttpService.call('Listing Mailchimp campaigns', 'GET', 'mailchimp/campaigns/list');
}
function replicateAndSendWithOptions(options) {
logger.debug('replicateAndSendWithOptions:options', options);
return replicateCampaign(options.campaignId)
.then(function (replicateCampaignResponse) {
logger.debug('replicateCampaignResponse', replicateCampaignResponse);
var replicatedCampaignId = replicateCampaignResponse.id;
return setCampaignOptions(replicatedCampaignId, options.campaignName, options.otherSegmentOptions)
.then(function (renameResponse) {
logger.debug('renameResponse', renameResponse);
return setContent(replicatedCampaignId, options.contentSections)
.then(function (setContentResponse) {
logger.debug('setContentResponse', setContentResponse);
return setOrClearSegment(replicatedCampaignId, options.segmentId)
.then(function (setSegmentResponse) {
logger.debug('setSegmentResponse', setSegmentResponse);
return options.dontSend ? replicateCampaignResponse : sendCampaign(replicatedCampaignId)
})
})
})
});
}
return {
replicateAndSendWithOptions: replicateAndSendWithOptions,
list: list
}
}]);
/* concatenated from client/src/app/js/mailingPreferencesController.js */
angular.module('ekwgApp')
.controller('MailingPreferencesController', ["$log", "$scope", "ProfileConfirmationService", "Notifier", "URLService", "LoggedInMemberService", "memberId", "close", function ($log, $scope, ProfileConfirmationService, Notifier, URLService, LoggedInMemberService, memberId, close) {
var logger = $log.getInstance("MailingPreferencesController");
$log.logLevels["MailingPreferencesController"] = $log.LEVEL.OFF;
$scope.notify = {};
var notify = Notifier($scope.notify);
LoggedInMemberService.getMemberForMemberId(memberId)
.then(function (member) {
logger.info('memberId ->', memberId, 'member ->', member);
$scope.member = member;
});
function saveOrUpdateUnsuccessful(message) {
notify.showContactUs(true);
notify.error({
continue: true,
title: "Error in saving mailing preferences",
message: "Changes to your mailing preferences could not be saved. " + (message || "Please try again later.")
});
}
$scope.actions = {
save: function () {
ProfileConfirmationService.confirmProfile($scope.member);
LoggedInMemberService.saveMember($scope.member, $scope.actions.close, saveOrUpdateUnsuccessful);
},
close: function () {
close();
}
};
}]);
/* concatenated from client/src/app/js/markdownEditor.js */
angular.module('ekwgApp')
.component('markdownEditor', {
templateUrl: 'partials/components/markdown-editor.html',
controller: ["$cookieStore", "$log", "$rootScope", "$scope", "$element", "$attrs", "ContentText", function ($cookieStore, $log, $rootScope, $scope, $element, $attrs, ContentText) {
var logger = $log.getInstance('MarkdownEditorController');
$log.logLevels['MarkdownEditorController'] = $log.LEVEL.OFF;
var ctrl = this;
ctrl.userEdits = {preview: true, saveInProgress: false, revertInProgress: false};
function assignData(data) {
ctrl.data = data;
ctrl.originalData = _.clone(data);
logger.debug(ctrl.name, 'content retrieved:', data);
return data;
}
function populateContent(type) {
if (type) ctrl.userEdits[type + 'InProgress'] = true;
return ContentText.forName(ctrl.name).then(function (data) {
data = assignData(data);
if (type) ctrl.userEdits[type + 'InProgress'] = false;
return data;
});
}
ctrl.edit = function () {
ctrl.userEdits.preview = false;
};
ctrl.revert = function () {
logger.debug('reverting ' + ctrl.name, 'content');
ctrl.data = _.clone(ctrl.originalData);
};
ctrl.dirty = function () {
var dirty = ctrl.data && ctrl.originalData && (ctrl.data.text !== ctrl.originalData.text);
logger.debug(ctrl.name, 'dirty ->', dirty);
return dirty;
};
ctrl.revertGlyph = function () {
return ctrl.userEdits.revertInProgress ? "fa fa-spinner fa-spin" : "glyphicon glyphicon-remove markdown-preview-icon"
};
ctrl.saveGlyph = function () {
return ctrl.userEdits.saveInProgress ? "fa fa-spinner fa-spin" : "glyphicon glyphicon-ok markdown-preview-icon"
};
ctrl.save = function () {
ctrl.userEdits.saveInProgress = true;
logger.info('saving', ctrl.name, 'content', ctrl.data, $element, $attrs);
ctrl.data.$saveOrUpdate().then(function (data) {
ctrl.userEdits.saveInProgress = false;
assignData(data);
})
};
ctrl.editSite = function () {
return $cookieStore.get('editSite');
};
ctrl.rows = function () {
var text = _.property(["data", "text"])(ctrl);
var rows = text ? text.split(/\r*\n/).length + 1 : 1;
logger.info('number of rows in text ', text, '->', rows);
return rows;
};
ctrl.preview = function () {
logger.info('previewing ' + ctrl.name, 'content', $element, $attrs);
ctrl.userEdits.preview = true;
};
ctrl.$onInit = function () {
logger.debug('initialising:', ctrl.name, 'content, editSite:', ctrl.editSite());
if (!ctrl.description) {
ctrl.description = ctrl.name;
}
populateContent();
};
}],
bindings: {
name: '@',
description: '@',
}
});
/* concatenated from client/src/app/js/meetupServices.js */
angular.module('ekwgApp')
.factory('MeetupService', ["$log", "$http", "HTTPResponseService", function ($log, $http, HTTPResponseService) {
var logger = $log.getInstance('MeetupService');
$log.logLevels['MeetupService'] = $log.LEVEL.OFF;
return {
config: function () {
return $http.get('/meetup/config').then(HTTPResponseService.returnResponse);
},
eventUrlFor: function (meetupEventUrl) {
return $http.get('/meetup/config').then(HTTPResponseService.returnResponse).then(function (meetupConfig) {
return meetupConfig.url + '/' + meetupConfig.group + '/events/' + meetupEventUrl;
});
},
eventsForStatus: function (status) {
var queriedStatus = status || 'upcoming';
return $http({
method: 'get',
params: {
status: queriedStatus,
},
url: '/meetup/events'
}).then(function (response) {
var returnValue = HTTPResponseService.returnResponse(response);
logger.debug('eventsForStatus', queriedStatus, returnValue);
return returnValue;
})
}
}
}]);
/* concatenated from client/src/app/js/memberAdmin.js */
angular.module('ekwgApp')
.controller('MemberAdminController',
["$timeout", "$location", "$window", "$log", "$q", "$rootScope", "$routeParams", "$scope", "ModalService", "Upload", "StringUtils", "DbUtils", "URLService", "LoggedInMemberService", "MemberService", "MemberAuditService", "MemberBulkLoadAuditService", "MemberUpdateAuditService", "ProfileConfirmationService", "EmailSubscriptionService", "DateUtils", "MailchimpConfig", "MailchimpSegmentService", "MemberNamingService", "MailchimpCampaignService", "MailchimpListService", "Notifier", "ErrorMessageService", "MemberBulkUploadService", "ContentMetaDataService", "MONGOLAB_CONFIG", "MAILCHIMP_APP_CONSTANTS", function ($timeout, $location, $window, $log, $q, $rootScope, $routeParams, $scope, ModalService, Upload, StringUtils, DbUtils, URLService, LoggedInMemberService, MemberService, MemberAuditService,
MemberBulkLoadAuditService, MemberUpdateAuditService, ProfileConfirmationService, EmailSubscriptionService, DateUtils, MailchimpConfig, MailchimpSegmentService, MemberNamingService,
MailchimpCampaignService, MailchimpListService, Notifier, ErrorMessageService, MemberBulkUploadService, ContentMetaDataService, MONGOLAB_CONFIG, MAILCHIMP_APP_CONSTANTS) {
var logger = $log.getInstance('MemberAdminController');
var noLogger = $log.getInstance('MemberAdminControllerNoLogger');
$log.logLevels['MemberAdminController'] = $log.LEVEL.OFF;
$log.logLevels['MemberAdminControllerNoLogger'] = $log.LEVEL.OFF;
$scope.memberAdminBaseUrl = ContentMetaDataService.baseUrl('memberAdmin');
$scope.notify = {};
var notify = Notifier($scope.notify);
notify.setBusy();
var DESCENDING = '▼';
var ASCENDING = '▲';
$scope.today = DateUtils.momentNowNoTime().valueOf();
$scope.currentMember = {};
$scope.display = {
saveInProgress: false
};
$scope.calculateMemberFilterDate = function () {
$scope.display.memberFilterDate = DateUtils.momentNowNoTime().subtract($scope.display && $scope.display.emailType.monthsInPast, 'months').valueOf();
};
$scope.showArea = function (area) {
URLService.navigateTo('admin', area)
};
$scope.display.emailTypes = [$scope.display.emailType];
$scope.dropSupported = true;
$scope.memberAdminOpen = !URLService.hasRouteParameter('expenseId') && (URLService.isArea('member-admin') || URLService.noArea());
$scope.memberBulkLoadOpen = URLService.isArea('member-bulk-load');
$scope.memberAuditOpen = URLService.isArea('member-audit');
LoggedInMemberService.showLoginPromptWithRouteParameter('expenseId');
if (LoggedInMemberService.memberLoggedIn()) {
refreshMembers()
.then(refreshMemberAudit)
.then(refreshMemberBulkLoadAudit)
.then(refreshMemberUpdateAudit)
.then(notify.clearBusy);
} else {
notify.clearBusy();
}
$scope.currentMemberBulkLoadDisplayDate = function () {
return DateUtils.currentMemberBulkLoadDisplayDate();
};
$scope.viewMailchimpListEntry = function (item) {
$window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/lists/members/view?id=" + item, '_blank');
};
$scope.showSendEmailsDialog = function () {
$scope.alertTypeResetPassword = false;
$scope.display.emailMembers = [];
ModalService.showModal({
templateUrl: "partials/admin/send-emails-dialog.html",
controller: "MemberAdminSendEmailsController",
preClose: function (modal) {
logger.debug('preClose event with modal', modal);
modal.element.modal('hide');
},
inputs: {
members: $scope.members
}
}).then(function (modal) {
logger.debug('modal event with modal', modal);
modal.element.modal();
modal.close.then(function (result) {
logger.debug('close event with result', result);
});
})
};
function handleSaveError(errorResponse) {
$scope.display.saveInProgress = false;
applyAllowEdits();
var message = ErrorMessageService.stringify(errorResponse);
var duplicate = s.include(message, 'duplicate');
logger.debug('errorResponse', errorResponse, 'duplicate', duplicate);
if (duplicate) {
message = 'Duplicate data was detected. A member record must have a unique Email Address, Display Name, Ramblers Membership Number and combination of First Name, Last Name and Alias. Please amend the current member and try again.';
$scope.display.duplicate = true;
}
notify.clearBusy();
notify.error({
title: 'Member could not be saved',
message: message
});
}
function resetSendFlags() {
logger.debug('resetSendFlags');
$scope.display.saveInProgress = false;
return applyAllowEdits();
}
$scope.showPasswordResetAlert = function () {
return $scope.notify.showAlert && $scope.alertTypeResetPassword;
};
$scope.uploadSessionStatuses = [
{title: "All"},
{status: "created", title: "Created"},
{status: "summary", title: "Summary"},
{status: "skipped", title: "Skipped"},
{status: "updated", title: "Updated"},
{status: "error", title: "Error"}];
$scope.filters = {
uploadSession: {selected: undefined},
memberUpdateAudit: {
query: $scope.uploadSessionStatuses[0],
orderByField: 'updateTime',
reverseSort: true,
sortDirection: DESCENDING
},
membersUploaded: {
query: '',
orderByField: 'email',
reverseSort: true,
sortDirection: DESCENDING
}
};
function applySortTo(field, filterSource) {
logger.debug('sorting by field', field, 'current value of filterSource', filterSource);
if (field === 'member') {
filterSource.orderByField = 'memberId | memberIdToFullName : members : "" : true';
} else {
filterSource.orderByField = field;
}
filterSource.reverseSort = !filterSource.reverseSort;
filterSource.sortDirection = filterSource.reverseSort ? DESCENDING : ASCENDING;
logger.debug('sorting by field', field, 'new value of filterSource', filterSource);
}
$scope.uploadSessionChanged = function () {
notify.setBusy();
notify.hide();
refreshMemberUpdateAudit().then(notify.clearBusy);
};
$scope.sortMembersUploadedBy = function (field) {
applySortTo(field, $scope.filters.membersUploaded);
};
$scope.sortMemberUpdateAuditBy = function (field) {
applySortTo(field, $scope.filters.memberUpdateAudit);
};
$scope.showMemberUpdateAuditColumn = function (field) {
return s.startsWith($scope.filters.memberUpdateAudit.orderByField, field);
};
$scope.showMembersUploadedColumn = function (field) {
return $scope.filters.membersUploaded.orderByField === field;
};
$scope.sortMembersBy = function (field) {
applySortTo(field, $scope.filters.members);
};
$scope.showMembersColumn = function (field) {
return s.startsWith($scope.filters.members.orderByField, field);
};
$scope.toGlyphicon = function (status) {
if (status === 'created') return "glyphicon glyphicon-plus green-icon";
if (status === 'complete' || status === 'summary') return "glyphicon-ok green-icon";
if (status === 'success') return "glyphicon-ok-circle green-icon";
if (status === 'info') return "glyphicon-info-sign blue-icon";
if (status === 'updated') return "glyphicon glyphicon-pencil green-icon";
if (status === 'error') return "glyphicon-remove-circle red-icon";
if (status === 'skipped') return "glyphicon glyphicon-thumbs-up green-icon";
};
$scope.filters.members = {
query: '',
orderByField: 'firstName',
reverseSort: false,
sortDirection: ASCENDING,
filterBy: [
{
title: "Active Group Member", group: 'Group Settings', filter: function (member) {
return member.groupMember;
}
},
{
title: "All Members", filter: function () {
return true;
}
},
{
title: "Active Social Member", group: 'Group Settings', filter: MemberService.filterFor.SOCIAL_MEMBERS
},
{
title: "Membership Date Active/Not set", group: 'From Ramblers Supplied Datas', filter: function (member) {
return !member.membershipExpiryDate || (member.membershipExpiryDate >= $scope.today);
}
},
{
title: "Membership Date Expired", group: 'From Ramblers Supplied Data', filter: function (member) {
return member.membershipExpiryDate < $scope.today;
}
},
{
title: "Not received in last Ramblers Bulk Load",
group: 'From Ramblers Supplied Data',
filter: function (member) {
return !member.receivedInLastBulkLoad;
}
},
{
title: "Was received in last Ramblers Bulk Load",
group: 'From Ramblers Supplied Data',
filter: function (member) {
return member.receivedInLastBulkLoad;
}
},
{
title: "Password Expired", group: 'Other Settings', filter: function (member) {
return member.expiredPassword;
}
},
{
title: "Walk Admin", group: 'Administrators', filter: function (member) {
return member.walkAdmin;
}
},
{
title: "Walk Change Notifications", group: 'Administrators', filter: function (member) {
return member.walkChangeNotifications;
}
},
{
title: "Social Admin", group: 'Administrators', filter: function (member) {
return member.socialAdmin;
}
},
{
title: "Member Admin", group: 'Administrators', filter: function (member) {
return member.memberAdmin;
}
},
{
title: "Finance Admin", group: 'Administrators', filter: function (member) {
return member.financeAdmin;
}
},
{
title: "File Admin", group: 'Administrators', filter: function (member) {
return member.fileAdmin;
}
},
{
title: "Treasury Admin", group: 'Administrators', filter: function (member) {
return member.treasuryAdmin;
}
},
{
title: "Content Admin", group: 'Administrators', filter: function (member) {
return member.contentAdmin;
}
},
{
title: "Committee Member", group: 'Administrators', filter: function (member) {
return member.committee;
}
},
{
title: "Subscribed to the General emails list",
group: 'Email Subscriptions',
filter: MemberService.filterFor.GENERAL_MEMBERS_SUBSCRIBED
},
{
title: "Subscribed to the Walks email list",
group: 'Email Subscriptions',
filter: MemberService.filterFor.WALKS_MEMBERS_SUBSCRIBED
},
{
title: "Subscribed to the Social email list",
group: 'Email Subscriptions',
filter: MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED
}
]
};
$scope.filters.members.filterSelection = $scope.filters.members.filterBy[0].filter;
$scope.memberAuditTabs = [
{title: "All Member Logins", active: true}
];
applyAllowEdits();
$scope.allowConfirmDelete = false;
$scope.open = function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.members = [];
$scope.memberAudit = [];
$scope.memberUpdateAudit = [];
$scope.membersUploaded = [];
$scope.resetAllBatchSubscriptions = function () {
// careful with calling this - it resets all batch subscriptions to default values
return EmailSubscriptionService.resetAllBatchSubscriptions($scope.members, false);
};
function updateWalksList(members) {
return EmailSubscriptionService.createBatchSubscriptionForList('walks', members);
}
function updateSocialEventsList(members) {
return EmailSubscriptionService.createBatchSubscriptionForList('socialEvents', members);
}
function updateGeneralList(members) {
return EmailSubscriptionService.createBatchSubscriptionForList('general', members);
}
function notifyUpdatesComplete(members) {
notify.success({title: 'Mailchimp updates', message: 'Mailchimp lists were updated successfully'});
$scope.members = members;
notify.clearBusy();
}
$scope.deleteMemberAudit = function (filteredMemberAudit) {
removeAllRecordsAndRefresh(filteredMemberAudit, refreshMemberAudit, 'member audit');
};
$scope.deleteMemberUpdateAudit = function (filteredMemberUpdateAudit) {
removeAllRecordsAndRefresh(filteredMemberUpdateAudit, refreshMemberUpdateAudit, 'member update audit');
};
function removeAllRecordsAndRefresh(records, refreshFunction, type) {
notify.success('Deleting ' + records.length + ' ' + type + ' record(s)');
var removePromises = [];
angular.forEach(records, function (record) {
removePromises.push(record.$remove())
});
$q.all(removePromises).then(function () {
notify.success('Deleted ' + records.length + ' ' + type + ' record(s)');
refreshFunction.apply();
});
}
$scope.$on('memberLoginComplete', function () {
applyAllowEdits('memberLoginComplete');
refreshMembers();
refreshMemberAudit();
refreshMemberBulkLoadAudit()
.then(refreshMemberUpdateAudit);
});
$scope.$on('memberSaveComplete', function () {
refreshMembers();
});
$scope.$on('memberLogoutComplete', function () {
applyAllowEdits('memberLogoutComplete');
});
$scope.createMemberFromAudit = function (memberFromAudit) {
var member = new MemberService(memberFromAudit);
EmailSubscriptionService.defaultMailchimpSettings(member, true);
member.groupMember = true;
showMemberDialog(member, 'Add New');
notify.warning({
title: 'Recreating Member',
message: "Note that clicking Save immediately on this member is likely to cause the same error to occur as was originally logged in the audit. Therefore make the necessary changes here to allow the member record to be saved successfully"
})
};
$scope.addMember = function () {
var member = new MemberService();
EmailSubscriptionService.defaultMailchimpSettings(member, true);
member.groupMember = true;
showMemberDialog(member, 'Add New');
};
$scope.viewMember = function (member) {
showMemberDialog(member, 'View');
};
$scope.editMember = function (member) {
showMemberDialog(member, 'Edit Existing');
};
$scope.deleteMemberDetails = function () {
$scope.allowDelete = false;
$scope.allowConfirmDelete = true;
};
function unsubscribeWalksList() {
return MailchimpListService.batchUnsubscribeMembers('walks', $scope.members, notify.success);
}
function unsubscribeSocialEventsList(members) {
return MailchimpListService.batchUnsubscribeMembers('socialEvents', members, notify.success);
}
function unsubscribeGeneralList(members) {
return MailchimpListService.batchUnsubscribeMembers('general', members, notify.success);
}
$scope.updateMailchimpLists = function () {
$scope.display.saveInProgress = true;
return $q.when(notify.success('Sending updates to Mailchimp lists', true))
.then(refreshMembers, notify.error, notify.success)
.then(updateWalksList, notify.error, notify.success)
.then(updateSocialEventsList, notify.error, notify.success)
.then(updateGeneralList, notify.error, notify.success)
.then(unsubscribeWalksList, notify.error, notify.success)
.then(unsubscribeSocialEventsList, notify.error, notify.success)
.then(unsubscribeGeneralList, notify.error, notify.success)
.then(notifyUpdatesComplete, notify.error, notify.success)
.then(resetSendFlags)
.catch(mailchimpError);
};
function mailchimpError(errorResponse) {
resetSendFlags();
notify.error({
title: 'Mailchimp updates failed',
message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + ErrorMessageService.stringify(errorResponse.error)) : '')
});
notify.clearBusy();
}
$scope.confirmDeleteMemberDetails = function () {
$scope.currentMember.$remove(hideMemberDialogAndRefreshMembers);
};
$scope.cancelMemberDetails = function () {
hideMemberDialogAndRefreshMembers();
};
$scope.profileSettingsConfirmedChecked = function () {
ProfileConfirmationService.processMember($scope.currentMember);
};
$scope.refreshMemberAudit = refreshMemberAudit;
$scope.memberUrl = function () {
return $scope.currentMember && $scope.currentMember.$id && (MONGOLAB_CONFIG.baseUrl + MONGOLAB_CONFIG.database + '/collections/members/' + $scope.currentMember.$id());
};
$scope.saveMemberDetails = function () {
var member = DateUtils.convertDateFieldInObject($scope.currentMember, 'membershipExpiryDate');
$scope.display.saveInProgress = true;
if (!member.userName) {
member.userName = MemberNamingService.createUniqueUserName(member, $scope.members);
logger.debug('creating username', member.userName);
}
if (!member.displayName) {
member.displayName = MemberNamingService.createUniqueDisplayName(member, $scope.members);
logger.debug('creating displayName', member.displayName);
}
function preProcessMemberBeforeSave() {
DbUtils.removeEmptyFieldsIn(member);
return EmailSubscriptionService.resetUpdateStatusForMember(member);
}
function removeEmptyFieldsIn(obj) {
_.each(obj, function (value, field) {
logger.debug('processing', typeof(field), 'field', field, 'value', value);
if (_.contains([null, undefined, ""], value)) {
logger.debug('removing non-populated', typeof(field), 'field', field);
delete obj[field];
}
});
}
function saveAndHide() {
return DbUtils.auditedSaveOrUpdate(member, hideMemberDialogAndRefreshMembers, notify.error)
}
$q.when(notify.success('Saving member', true))
.then(preProcessMemberBeforeSave, notify.error, notify.success)
.then(saveAndHide, notify.error, notify.success)
.then(resetSendFlags)
.then(function () {
return notify.success('Member saved successfully');
})
.catch(handleSaveError)
};
$scope.copyDetailsToNewMember = function () {
var copiedMember = new MemberService($scope.currentMember);
delete copiedMember._id;
EmailSubscriptionService.defaultMailchimpSettings(copiedMember, true);
ProfileConfirmationService.unconfirmProfile(copiedMember);
showMemberDialog(copiedMember, 'Copy Existing');
notify.success('Existing Member copied! Make changes here and save to create new member.')
};
function applyAllowEdits() {
$scope.allowEdits = LoggedInMemberService.allowMemberAdminEdits();
$scope.allowCopy = LoggedInMemberService.allowMemberAdminEdits();
return true;
}
function findLastLoginTimeForMember(member) {
var memberAudit = _.chain($scope.memberAudit)
.filter(function (memberAudit) {
return memberAudit.userName === member.userName;
})
.sortBy(function (memberAudit) {
return memberAudit.lastLoggedIn;
})
.last()
.value();
return memberAudit === undefined ? undefined : memberAudit.loginTime;
}
$scope.bulkUploadRamblersDataStart = function () {
$('#select-bulk-load-file').click();
};
$scope.resetSendFlagsAndNotifyError = function (error) {
logger.error('resetSendFlagsAndNotifyError', error);
resetSendFlags();
return notify.error(error);
};
$scope.bulkUploadRamblersDataOpenFile = function (file) {
if (file) {
var fileUpload = file;
$scope.display.saveInProgress = true;
function bulkUploadRamblersResponse(memberBulkLoadServerResponse) {
return MemberBulkUploadService.processMembershipRecords(file, memberBulkLoadServerResponse, $scope.members, notify)
}
function bulkUploadRamblersProgress(evt) {
fileUpload.progress = parseInt(100.0 * evt.loaded / evt.total);
logger.debug("bulkUploadRamblersProgress:progress event", evt);
}
$scope.uploadedFile = Upload.upload({
url: 'uploadRamblersData',
method: 'POST',
file: file
}).then(bulkUploadRamblersResponse, $scope.resetSendFlagsAndNotifyError, bulkUploadRamblersProgress)
.then(refreshMemberBulkLoadAudit)
.then(refreshMemberUpdateAudit)
.then(validateBulkUploadProcessingBeforeMailchimpUpdates)
.catch($scope.resetSendFlagsAndNotifyError);
}
};
function showMemberDialog(member, memberEditMode) {
logger.debug('showMemberDialog:', memberEditMode, member);
$scope.alertTypeResetPassword = false;
var existingRecordEditEnabled = $scope.allowEdits && s.startsWith(memberEditMode, 'Edit');
$scope.allowConfirmDelete = false;
$scope.allowCopy = existingRecordEditEnabled;
$scope.allowDelete = existingRecordEditEnabled;
$scope.memberEditMode = memberEditMode;
$scope.currentMember = member;
$scope.currentMemberUpdateAudit = [];
if ($scope.currentMember.$id()) {
logger.debug('querying MemberUpdateAuditService for memberId', $scope.currentMember.$id());
MemberUpdateAuditService.query({memberId: $scope.currentMember.$id()}, {sort: {updateTime: -1}})
.then(function (data) {
logger.debug('MemberUpdateAuditService:', data.length, 'events', data);
$scope.currentMemberUpdateAudit = data;
});
$scope.lastLoggedIn = findLastLoginTimeForMember(member);
} else {
logger.debug('new member with default values', $scope.currentMember);
}
$('#member-admin-dialog').modal();
}
function hideMemberDialogAndRefreshMembers() {
$q.when($('#member-admin-dialog').modal('hide'))
.then(refreshMembers)
.then(notify.clearBusy)
.then(notify.hide)
}
function refreshMembers() {
if (LoggedInMemberService.allowMemberAdminEdits()) {
return MemberService.all()
.then(function (refreshedMembers) {
$scope.members = refreshedMembers;
return $scope.members;
});
}
}
function refreshMemberAudit() {
if (LoggedInMemberService.allowMemberAdminEdits()) {
MemberAuditService.all({limit: 100, sort: {loginTime: -1}}).then(function (memberAudit) {
logger.debug('refreshed', memberAudit && memberAudit.length, 'member audit records');
$scope.memberAudit = memberAudit;
});
}
return true;
}
function refreshMemberBulkLoadAudit() {
if (LoggedInMemberService.allowMemberAdminEdits()) {
return MemberBulkLoadAuditService.all({limit: 100, sort: {createdDate: -1}}).then(function (uploadSessions) {
logger.debug('refreshed', uploadSessions && uploadSessions.length, 'upload sessions');
$scope.uploadSessions = uploadSessions;
$scope.filters.uploadSession.selected = _.first(uploadSessions);
return $scope.filters.uploadSession.selected;
});
} else {
return true;
}
}
function migrateAudits() {
// temp - remove this!
MemberUpdateAuditService.all({
limit: 10000,
sort: {updateTime: -1}
}).then(function (allMemberUpdateAudit) {
logger.debug('temp queried all', allMemberUpdateAudit && allMemberUpdateAudit.length, 'member audit records');
var keys = [];
var memberUpdateAuditServicePromises = [];
var memberBulkLoadAuditServicePromises = [];
var bulkAudits = _.chain(allMemberUpdateAudit)
// .filter(function (audit) {
// return !audit.uploadSessionId;
// })
.map(function (audit) {
var auditLog = {
fileName: audit.fileName,
createdDate: DateUtils.asValueNoTime(audit.updateTime),
auditLog: [
{
"status": "complete",
"message": "Migrated audit log for upload of file " + audit.fileName
}
]
};
return auditLog;
})
.uniq(JSON.stringify)
.map(function (auditLog) {
return new MemberBulkLoadAuditService(auditLog).$save()
.then(function (auditResponse) {
memberBulkLoadAuditServicePromises.push(auditResponse);
logger.debug('saved bulk load session id', auditResponse.$id(), 'number', memberBulkLoadAuditServicePromises.length);
return auditResponse;
});
})
.value();
function saveAudit(audit) {
memberUpdateAuditServicePromises.push(audit.$saveOrUpdate());
logger.debug('saved', audit.uploadSessionId, 'to audit number', memberUpdateAuditServicePromises.length);
}
$q.all(bulkAudits).then(function (savedBulkAuditRecords) {
logger.debug('saved bulk load sessions', savedBulkAuditRecords);
_.each(allMemberUpdateAudit, function (audit) {
var parentBulkAudit = _.findWhere(savedBulkAuditRecords, {
fileName: audit.fileName,
createdDate: DateUtils.asValueNoTime(audit.updateTime)
});
if (parentBulkAudit) {
audit.uploadSessionId = parentBulkAudit.$id();
saveAudit(audit);
} else {
logger.error('no match for audit record', audit);
}
});
$q.all(memberUpdateAuditServicePromises).then(function (values) {
logger.debug('saved', values.length, 'audit records');
});
});
});
}
function refreshMemberUpdateAudit() {
if (LoggedInMemberService.allowMemberAdminEdits()) {
// migrateAudits();
if ($scope.filters.uploadSession.selected && $scope.filters.uploadSession.selected.$id) {
var uploadSessionId = $scope.filters.uploadSession.selected.$id();
var query = {uploadSessionId: uploadSessionId};
if ($scope.filters.memberUpdateAudit.query.status) {
angular.extend(query, {memberAction: $scope.filters.memberUpdateAudit.query.status})
}
logger.debug('querying member audit records with', query);
return MemberUpdateAuditService.query(query, {sort: {updateTime: -1}}).then(function (memberUpdateAudit) {
$scope.memberUpdateAudit = memberUpdateAudit;
logger.debug('refreshed', memberUpdateAudit && memberUpdateAudit.length, 'member audit records');
return $scope.memberUpdateAudit;
});
} else {
$scope.memberUpdateAudit = [];
logger.debug('no member audit records');
return $q.when($scope.memberUpdateAudit);
}
}
}
function auditSummary() {
return _.groupBy($scope.memberUpdateAudit, function (auditItem) {
return auditItem.memberAction || 'unknown';
});
}
function auditSummaryFormatted(auditSummary) {
var total = _.reduce(auditSummary, function (memo, value) {
return memo + value.length;
}, 0);
var summary = _.map(auditSummary, function (items, key) {
return items.length + ':' + key;
}).join(', ');
return total + " Member audits " + (total ? '(' + summary + ')' : '');
}
$scope.memberUpdateAuditSummary = function () {
return auditSummaryFormatted(auditSummary());
};
function validateBulkUploadProcessingBeforeMailchimpUpdates() {
logger.debug('validateBulkUploadProcessing:$scope.filters.uploadSession', $scope.filters.uploadSession);
if ($scope.filters.uploadSession.selected.error) {
notify.error({title: 'Bulk upload failed', message: $scope.filters.uploadSession.selected.error});
} else {
var summary = auditSummary();
var summaryFormatted = auditSummaryFormatted(summary);
logger.debug('summary', summary, 'summaryFormatted', summaryFormatted);
if (summary.error) {
notify.error({
title: "Bulk upload was not successful",
message: "One or more errors occurred - " + summaryFormatted
});
return false;
} else return $scope.updateMailchimpLists();
}
}
}]
)
;
/* concatenated from client/src/app/js/memberAdminSendEmailsController.js */
angular.module('ekwgApp')
.controller('MemberAdminSendEmailsController', ["$log", "$q", "$scope", "$filter", "DateUtils", "DbUtils", "LoggedInMemberService", "ErrorMessageService", "EmailSubscriptionService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "members", "close", function ($log, $q, $scope, $filter, DateUtils, DbUtils, LoggedInMemberService, ErrorMessageService,
EmailSubscriptionService, MailchimpSegmentService, MailchimpCampaignService,
MailchimpConfig, Notifier, members, close) {
var logger = $log.getInstance('MemberAdminSendEmailsController');
$log.logLevels['MemberAdminSendEmailsController'] = $log.LEVEL.OFF;
var notify = Notifier($scope);
notify.setBusy();
var CAMPAIGN_TYPE_WELCOME = "welcome";
var CAMPAIGN_TYPE_PASSWORD_RESET = "passwordReset";
var CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING = "expiredMembersWarning";
var CAMPAIGN_TYPE_EXPIRED_MEMBERS = "expiredMembers";
$scope.today = DateUtils.momentNowNoTime().valueOf();
$scope.members = members;
$scope.memberFilterDateCalendar = {
open: function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.memberFilterDateCalendar.opened = true;
}
};
$scope.showHelp = function (show) {
$scope.display.showHelp = show;
};
$scope.cancel = function () {
close();
};
$scope.display = {
showHelp: false,
selectableMembers: [],
emailMembers: [],
saveInProgress: false,
monthsInPast: 1,
memberFilterDate: undefined,
emailType: {name: "(loading)"},
passwordResetCaption: function () {
return 'About to send a ' + $scope.display.emailType.name + ' to ' + $scope.display.emailMembers.length + ' member' + ($scope.display.emailMembers.length === 1 ? '' : 's');
},
expiryEmailsSelected: function () {
var returnValue = $scope.display.emailType.type === CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING || $scope.display.emailType.type === CAMPAIGN_TYPE_EXPIRED_MEMBERS;
logger.debug('expiryEmailsSelected -> ', returnValue);
return returnValue;
},
recentMemberEmailsSelected: function () {
return $scope.display.emailType.type === CAMPAIGN_TYPE_WELCOME || $scope.display.emailType.type === CAMPAIGN_TYPE_PASSWORD_RESET;
}
};
$scope.populateSelectableMembers = function () {
$scope.display.selectableMembers = _.chain($scope.members)
.filter(function (member) {
return EmailSubscriptionService.includeMemberInEmailList('general', member);
})
.map(extendWithInformation)
.value();
logger.debug('populateSelectableMembers:found', $scope.display.selectableMembers.length, 'members');
};
$scope.populateSelectableMembers();
$scope.calculateMemberFilterDate = function () {
$scope.display.memberFilterDate = DateUtils.momentNowNoTime().subtract($scope.display && $scope.display.emailType.monthsInPast, 'months').valueOf();
};
$scope.clearDisplayEmailMembers = function () {
$scope.display.emailMembers = [];
notify.warning({
title: 'Member selection',
message: 'current member selection was cleared'
});
};
function extendWithInformation(member) {
return $scope.display.expiryEmailsSelected() ? extendWithExpiryInformation(member) : extendWithCreatedInformation(member);
}
function extendWithExpiryInformation(member) {
var expiredActive = member.membershipExpiryDate < $scope.today ? 'expired' : 'active';
var memberGrouping = member.receivedInLastBulkLoad ? expiredActive : 'missing from last bulk load';
var datePrefix = memberGrouping === 'expired' ? ': ' : ', ' + (member.membershipExpiryDate < $scope.today ? 'expired' : 'expiry') + ': ';
var text = $filter('fullNameWithAlias')(member) + ' (' + memberGrouping + datePrefix + (DateUtils.displayDate(member.membershipExpiryDate) || 'not known') + ')';
return angular.extend({}, member, {id: member.$id(), text: text, memberGrouping: memberGrouping});
}
function extendWithCreatedInformation(member) {
var memberGrouping = member.membershipExpiryDate < $scope.today ? 'expired' : 'active';
var text = $filter('fullNameWithAlias')(member) + ' (created ' + (DateUtils.displayDate(member.createdDate) || 'not known') + ')';
return angular.extend({}, member, {id: member.$id(), text: text, memberGrouping: memberGrouping});
}
$scope.memberGrouping = function (member) {
return member.memberGrouping;
};
function populateMembersBasedOnFilter(filter) {
logger.debug('populateExpiredMembers: display.emailType ->', $scope.display.emailType);
notify.setBusy();
notify.warning({
title: 'Automatically adding expired members',
message: ' - please wait for list to be populated'
});
$scope.display.memberFilterDate = DateUtils.convertDateField($scope.display.memberFilterDate);
$scope.display.emailMembers = _($scope.display.selectableMembers)
.filter(filter);
notify.warning({
title: 'Members added to email selection',
message: 'automatically added ' + $scope.display.emailMembers.length + ' members'
});
notify.clearBusy();
}
$scope.populateMembers = function (recalcMemberFilterDate) {
logger.debug('$scope.display.memberSelection', $scope.display.emailType.memberSelection);
this.populateSelectableMembers();
switch ($scope.display.emailType.memberSelection) {
case 'recently-added':
$scope.populateRecentlyAddedMembers(recalcMemberFilterDate);
break;
case 'expired-members':
$scope.populateExpiredMembers(recalcMemberFilterDate);
break
}
};
$scope.populateRecentlyAddedMembers = function (recalcMemberFilterDate) {
if (recalcMemberFilterDate) {
$scope.calculateMemberFilterDate();
}
populateMembersBasedOnFilter(function (member) {
return member.groupMember && (member.createdDate >= $scope.display.memberFilterDate);
});
};
$scope.populateExpiredMembers = function (recalcMemberFilterDate) {
if (recalcMemberFilterDate) {
$scope.calculateMemberFilterDate();
}
populateMembersBasedOnFilter(function (member) {
return member.groupMember && member.membershipExpiryDate && (member.membershipExpiryDate < $scope.display.memberFilterDate);
});
};
$scope.populateMembersMissingFromBulkLoad = function (recalcMemberFilterDate) {
if (recalcMemberFilterDate) {
$scope.calculateMemberFilterDate();
}
populateMembersBasedOnFilter(function (member) {
return member.groupMember && member.membershipExpiryDate && !member.receivedInLastBulkLoad;
})
};
function displayEmailMembersToMembers() {
return _.chain($scope.display.emailMembers)
.map(function (memberId) {
return _.find($scope.members, function (member) {
return member.$id() === memberId.id;
})
})
.filter(function (member) {
return member && member.email;
}).value();
}
function addPasswordResetIdToMembers() {
var saveMemberPromises = [];
_.map(displayEmailMembersToMembers(), function (member) {
LoggedInMemberService.setPasswordResetId(member);
EmailSubscriptionService.resetUpdateStatusForMember(member);
saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member))
});
return $q.all(saveMemberPromises).then(function () {
return notify.success('Password reset prepared for ' + saveMemberPromises.length + ' member(s)');
});
}
function includeInNextMailchimpListUpdate() {
var saveMemberPromises = [];
_.map(displayEmailMembersToMembers(), function (member) {
EmailSubscriptionService.resetUpdateStatusForMember(member);
saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member))
});
return $q.all(saveMemberPromises).then(function () {
return notify.success('Member expiration prepared for ' + saveMemberPromises.length + ' member(s)');
});
}
function noAction() {
}
function removeExpiredMembersFromGroup() {
logger.debug('removing ', $scope.display.emailMembers.length, 'members from group');
var saveMemberPromises = [];
_($scope.display.emailMembers)
.map(function (memberId) {
return _.find($scope.members, function (member) {
return member.$id() === memberId.id;
})
}).map(function (member) {
member.groupMember = false;
EmailSubscriptionService.resetUpdateStatusForMember(member);
saveMemberPromises.push(DbUtils.auditedSaveOrUpdate(member))
});
return $q.all(saveMemberPromises)
.then(function () {
return notify.success('EKWG group membership removed for ' + saveMemberPromises.length + ' member(s)');
})
}
$scope.cancelSendEmails = function () {
$scope.cancel();
};
$scope.sendEmailsDisabled = function () {
return $scope.display.emailMembers.length === 0
};
$scope.sendEmails = function () {
$scope.alertTypeResetPassword = true;
$scope.display.saveInProgress = true;
$scope.display.duplicate = false;
$q.when(notify.success('Preparing to email ' + $scope.display.emailMembers.length + ' member' + ($scope.display.emailMembers.length === 1 ? '' : 's'), true))
.then($scope.display.emailType.preSend)
.then(updateGeneralList)
.then(createOrSaveMailchimpSegment)
.then(saveSegmentDataToMailchimpConfig)
.then(sendEmailCampaign)
.then($scope.display.emailType.postSend)
.then(notify.clearBusy)
.then($scope.cancel)
.then(resetSendFlags)
.catch(handleSendError);
};
function resetSendFlags() {
logger.debug('resetSendFlags');
$scope.display.saveInProgress = false;
}
function updateGeneralList() {
return EmailSubscriptionService.createBatchSubscriptionForList('general', $scope.members).then(function (updatedMembers) {
$scope.members = updatedMembers;
});
}
function createOrSaveMailchimpSegment() {
return MailchimpSegmentService.saveSegment('general', {segmentId: $scope.display.emailType.segmentId}, $scope.display.emailMembers, $scope.display.emailType.name, $scope.members);
}
function saveSegmentDataToMailchimpConfig(segmentResponse) {
logger.debug('saveSegmentDataToMailchimpConfig:segmentResponse', segmentResponse);
return MailchimpConfig.getConfig()
.then(function (config) {
config.mailchimp.segments.general[$scope.display.emailType.type + 'SegmentId'] = segmentResponse.segment.id;
return MailchimpConfig.saveConfig(config)
.then(function () {
logger.debug('saveSegmentDataToMailchimpConfig:returning segment id', segmentResponse.segment.id);
return segmentResponse.segment.id;
});
});
}
function sendEmailCampaign(segmentId) {
var members = $scope.display.emailMembers.length + ' member(s)';
notify.success('Sending ' + $scope.display.emailType.name + ' email to ' + members);
logger.debug('about to sendEmailCampaign:', $scope.display.emailType.type, 'campaign Id', $scope.display.emailType.campaignId, 'segmentId', segmentId, 'campaignName', $scope.display.emailType.name);
return MailchimpCampaignService.replicateAndSendWithOptions({
campaignId: $scope.display.emailType.campaignId,
campaignName: $scope.display.emailType.name,
segmentId: segmentId
}).then(function () {
notify.success('Sending of ' + $scope.display.emailType.name + ' to ' + members + ' was successful');
});
}
$scope.emailMemberList = function () {
return _($scope.display.emailMembers)
.sortBy(function (emailMember) {
return emailMember.text;
}).map(function (emailMember) {
return emailMember.text;
}).join(', ');
};
function handleSendError(errorResponse) {
$scope.display.saveInProgress = false;
notify.error({
title: 'Your notification could not be sent',
message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + ErrorMessageService.stringify(errorResponse.error)) : '')
});
notify.clearBusy();
}
MailchimpConfig.getConfig()
.then(function (config) {
$scope.display.emailTypes = [
{
preSend: addPasswordResetIdToMembers,
type: CAMPAIGN_TYPE_WELCOME,
name: config.mailchimp.campaigns.welcome.name,
monthsInPast: config.mailchimp.campaigns.welcome.monthsInPast,
campaignId: config.mailchimp.campaigns.welcome.campaignId,
segmentId: config.mailchimp.segments.general.welcomeSegmentId,
memberSelection: 'recently-added',
postSend: noAction,
dateTooltip: "All members created in the last " + config.mailchimp.campaigns.welcome.monthsInPast + " month are displayed as a default, as these are most likely to need a welcome email sent"
},
{
preSend: addPasswordResetIdToMembers,
type: CAMPAIGN_TYPE_PASSWORD_RESET,
name: config.mailchimp.campaigns.passwordReset.name,
monthsInPast: config.mailchimp.campaigns.passwordReset.monthsInPast,
campaignId: config.mailchimp.campaigns.passwordReset.campaignId,
segmentId: config.mailchimp.segments.general.passwordResetSegmentId,
memberSelection: 'recently-added',
postSend: noAction,
dateTooltip: "All members created in the last " + config.mailchimp.campaigns.passwordReset.monthsInPast + " month are displayed as a default"
},
{
preSend: includeInNextMailchimpListUpdate,
type: CAMPAIGN_TYPE_EXPIRED_MEMBERS_WARNING,
name: config.mailchimp.campaigns.expiredMembersWarning.name,
monthsInPast: config.mailchimp.campaigns.expiredMembersWarning.monthsInPast,
campaignId: config.mailchimp.campaigns.expiredMembersWarning.campaignId,
segmentId: config.mailchimp.segments.general.expiredMembersWarningSegmentId,
memberSelection: 'expired-members',
postSend: noAction,
dateTooltip: "Using the expiry date field, you can choose which members will automatically be included. " +
"A date " + config.mailchimp.campaigns.expiredMembersWarning.monthsInPast + " months in the past has been pre-selected, to avoid including members whose membership renewal is still progress"
},
{
preSend: includeInNextMailchimpListUpdate,
type: CAMPAIGN_TYPE_EXPIRED_MEMBERS,
name: config.mailchimp.campaigns.expiredMembers.name,
monthsInPast: config.mailchimp.campaigns.expiredMembers.monthsInPast,
campaignId: config.mailchimp.campaigns.expiredMembers.campaignId,
segmentId: config.mailchimp.segments.general.expiredMembersSegmentId,
memberSelection: 'expired-members',
postSend: removeExpiredMembersFromGroup,
dateTooltip: "Using the expiry date field, you can choose which members will automatically be included. " +
"A date 3 months in the past has been pre-selected, to avoid including members whose membership renewal is still progress"
}
];
$scope.display.emailType = $scope.display.emailTypes[0];
$scope.populateMembers(true);
});
}]
);
/* concatenated from client/src/app/js/memberResources.js */
angular.module('ekwgApp')
.factory('MemberResourcesService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('memberResources');
}])
.factory('MemberResourcesReferenceData', ["$log", "URLService", "ContentMetaDataService", "FileUtils", "LoggedInMemberService", "SiteEditService", function ($log, URLService, ContentMetaDataService, FileUtils, LoggedInMemberService, SiteEditService) {
var logger = $log.getInstance('MemberResourcesReferenceData');
$log.logLevels['MemberResourcesReferenceData'] = $log.LEVEL.OFF;
const subjects = [
{
id: "newsletter",
description: "Newsletter"
},
{
id: "siteReleaseNote",
description: "Site Release Note"
},
{
id: "walkPlanning",
description: "Walking Planning Advice"
}
];
const resourceTypes = [
{
id: "email",
description: "Email",
action: "View email",
icon: function () {
return "assets/images/local/mailchimp.ico"
},
resourceUrl: function (memberResource) {
var data = _.property(['data', 'campaign', 'archive_url_long'])(memberResource);
logger.debug('email:resourceUrl for', memberResource, data);
return data;
}
},
{
id: "file",
description: "File",
action: "Download",
icon: function (memberResource) {
return FileUtils.icon(memberResource, 'data')
},
resourceUrl: function (memberResource) {
var data = memberResource && memberResource.data.fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl("memberResources") + "/" + memberResource.data.fileNameData.awsFileName : "";
logger.debug('file:resourceUrl for', memberResource, data);
return data;
}
},
{
id: "url",
action: "View page",
description: "External Link",
icon: function () {
return "assets/images/ramblers/favicon.ico"
},
resourceUrl: function () {
return "TBA";
}
}
];
const accessLevels = [
{
id: "hidden",
description: "Hidden",
filter: function () {
return SiteEditService.active() || false;
}
},
{
id: "committee",
description: "Committee",
filter: function () {
return SiteEditService.active() || LoggedInMemberService.allowCommittee();
}
},
{
id: "loggedInMember",
description: "Logged-in member",
filter: function () {
return SiteEditService.active() || LoggedInMemberService.memberLoggedIn();
}
},
{
id: "public",
description: "Public",
filter: function () {
return true;
}
}];
function resourceTypeFor(resourceType) {
var type = _.find(resourceTypes, function (type) {
return type.id === resourceType;
});
logger.debug('resourceType for', type, type);
return type;
}
function accessLevelFor(accessLevel) {
var level = _.find(accessLevels, function (level) {
return level.id === accessLevel;
});
logger.debug('accessLevel for', accessLevel, level);
return level;
}
return {
subjects: subjects,
resourceTypes: resourceTypes,
accessLevels: accessLevels,
resourceTypeFor: resourceTypeFor,
accessLevelFor: accessLevelFor
};
}]);
/* concatenated from client/src/app/js/memberServices.js */
angular.module('ekwgApp')
.factory('MemberUpdateAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('memberUpdateAudit');
}])
.factory('MemberBulkLoadAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('memberBulkLoadAudit');
}])
.factory('MemberAuditService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('memberAudit');
}])
.factory('ExpenseClaimsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('expenseClaims');
}])
.factory('MemberNamingService', ["$log", "StringUtils", function ($log, StringUtils) {
var logger = $log.getInstance('MemberNamingService');
$log.logLevels['MemberNamingService'] = $log.LEVEL.OFF;
var createUserName = function (member) {
return StringUtils.replaceAll(' ', '', (member.firstName + '.' + member.lastName).toLowerCase());
};
function createDisplayName(member) {
return member.firstName.trim() + ' ' + member.lastName.trim().substring(0, 1).toUpperCase();
}
function createUniqueUserName(member, members) {
return createUniqueValueFrom(createUserName, 'userName', member, members)
}
function createUniqueDisplayName(member, members) {
return createUniqueValueFrom(createDisplayName, 'displayName', member, members)
}
function createUniqueValueFrom(nameFunction, field, member, members) {
var attempts = 0;
var suffix = "";
while (true) {
var createdName = nameFunction(member) + suffix;
if (!memberFieldExists(field, createdName, members)) {
return createdName
} else {
attempts++;
suffix = attempts;
}
}
}
function memberFieldExists(field, value, members) {
var member = _(members).find(function (member) {
return member[field] === value;
});
var returnValue = member && member[field];
logger.debug('field', field, 'matching', value, member, '->', returnValue);
return returnValue;
}
return {
createDisplayName: createDisplayName,
createUserName: createUserName,
createUniqueUserName: createUniqueUserName,
createUniqueDisplayName: createUniqueDisplayName
};
}])
.factory('MemberService', ["$mongolabResourceHttp", "$log", function ($mongolabResourceHttp, $log) {
var logger = $log.getInstance('MemberService');
var noLogger = $log.getInstance('MemberServiceMuted');
$log.logLevels['MemberServiceMuted'] = $log.LEVEL.OFF;
$log.logLevels['MemberService'] = $log.LEVEL.OFF;
var memberService = $mongolabResourceHttp('members');
memberService.filterFor = {
SOCIAL_MEMBERS_SUBSCRIBED: function (member) {
return member.groupMember && member.socialMember && member.mailchimpLists.socialEvents.subscribed
},
WALKS_MEMBERS_SUBSCRIBED: function (member) {
return member.groupMember && member.mailchimpLists.walks.subscribed
},
GENERAL_MEMBERS_SUBSCRIBED: function (member) {
return member.groupMember && member.mailchimpLists.general.subscribed
},
GROUP_MEMBERS: function (member) {
return member.groupMember;
},
COMMITTEE_MEMBERS: function (member) {
return member.groupMember && member.committee;
},
SOCIAL_MEMBERS: function (member) {
return member.groupMember && member.socialMember;
},
};
memberService.allLimitedFields = function allLimitedFields(filterFunction) {
return memberService.all({
fields: {
mailchimpLists: 1,
groupMember: 1,
socialMember: 1,
financeAdmin: 1,
treasuryAdmin: 1,
fileAdmin: 1,
committee: 1,
walkChangeNotifications: 1,
email: 1,
displayName: 1,
contactId: 1,
mobileNumber: 1,
$id: 1,
firstName: 1,
lastName: 1,
nameAlias: 1
}
}).then(function (members) {
return _.chain(members)
.filter(filterFunction)
.sortBy(function (member) {
return member.firstName + member.lastName;
}).value();
});
};
memberService.toMember = function (memberIdOrObject, members) {
var memberId = (_.has(memberIdOrObject, 'id') ? memberIdOrObject.id : memberIdOrObject);
noLogger.info('toMember:memberIdOrObject', memberIdOrObject, '->', memberId);
var member = _.find(members, function (member) {
return member.$id() === memberId;
});
noLogger.info('toMember:', memberIdOrObject, '->', member);
return member;
};
memberService.allMemberMembersWithPrivilege = function (privilege, members) {
var filteredMembers = _.filter(members, function (member) {
return member.groupMember && member[privilege];
});
logger.debug('allMemberMembersWithPrivilege:privilege', privilege, 'filtered from', members.length, '->', filteredMembers.length, 'members ->', filteredMembers);
return filteredMembers;
};
memberService.allMemberIdsWithPrivilege = function (privilege, members) {
return memberService.allMemberMembersWithPrivilege(privilege, members).map(extractMemberId);
function extractMemberId(member) {
return member.$id()
}
};
return memberService;
}]);
/* concatenated from client/src/app/js/notificationUrl.js */
angular.module("ekwgApp")
.component("notificationUrl", {
templateUrl: "partials/components/notification-url.html",
controller: ["$log", "URLService", "FileUtils", function ($log, URLService, FileUtils) {
var ctrl = this;
var logger = $log.getInstance("NotificationUrlController");
$log.logLevels['NotificationUrlController'] = $log.LEVEL.OFF;
ctrl.anchor_href = function () {
return URLService.notificationHref(ctrl);
};
ctrl.anchor_target = function () {
return "_blank";
};
ctrl.anchor_text = function () {
var text = (!ctrl.text && ctrl.name) ? FileUtils.basename(ctrl.name) : ctrl.text || ctrl.anchor_href();
logger.debug("text", text);
return text;
};
}],
bindings: {
name: "@",
text: "@",
type: "@",
id: "@",
area: "@"
}
});
/* concatenated from client/src/app/js/notifier.js */
angular.module('ekwgApp')
.factory('Notifier', ["$log", "ErrorMessageService", function ($log, ErrorMessageService) {
var ALERT_ERROR = {class: 'alert-danger', icon: 'glyphicon-exclamation-sign', failure: true};
var ALERT_WARNING = {class: 'alert-warning', icon: 'glyphicon-info-sign'};
var ALERT_INFO = {class: 'alert-success', icon: 'glyphicon-info-sign'};
var ALERT_SUCCESS = {class: 'alert-success', icon: 'glyphicon-ok'};
var logger = $log.getInstance('Notifier');
$log.logLevels['Notifier'] = $log.LEVEL.OFF;
return function (scope) {
scope.alertClass = ALERT_SUCCESS.class;
scope.alert = ALERT_SUCCESS;
scope.alertMessages = [];
scope.alertHeading = [];
scope.ready = false;
function setReady() {
clearBusy();
return scope.ready = true;
}
function clearBusy() {
logger.debug('clearing busy');
return scope.busy = false;
}
function setBusy() {
logger.debug('setting busy');
return scope.busy = true;
}
function showContactUs(state) {
logger.debug('setting showContactUs', state);
return scope.showContactUs = state;
}
function notifyAlertMessage(alertType, message, append, busy) {
var messageText = message && ErrorMessageService.stringify(_.has(message, 'message') ? message.message : message);
if (busy) setBusy();
if (!append || alertType === ALERT_ERROR) scope.alertMessages = [];
if (messageText) scope.alertMessages.push(messageText);
scope.alertTitle = message && _.has(message, 'title') ? message.title : undefined;
scope.alert = alertType;
scope.alertClass = alertType.class;
scope.showAlert = scope.alertMessages.length > 0;
scope.alertMessage = scope.alertMessages.join(', ');
if (alertType === ALERT_ERROR && !_.has(message, 'continue')) {
logger.error('notifyAlertMessage:', 'class =', alertType, 'messageText =', messageText, 'append =', append);
clearBusy();
throw message;
} else {
return logger.debug('notifyAlertMessage:', 'class =', alertType, 'messageText =', messageText, 'append =', append, 'showAlert =', scope.showAlert);
}
}
function progress(message, busy) {
return notifyAlertMessage(ALERT_INFO, message, false, busy)
}
function hide() {
notifyAlertMessage(ALERT_SUCCESS);
return clearBusy();
}
function success(message, busy) {
return notifyAlertMessage(ALERT_SUCCESS, message, false, busy)
}
function successWithAppend(message, busy) {
return notifyAlertMessage(ALERT_SUCCESS, message, true, busy)
}
function error(message, append, busy) {
return notifyAlertMessage(ALERT_ERROR, message, append, busy)
}
function warning(message, append, busy) {
return notifyAlertMessage(ALERT_WARNING, message, append, busy)
}
return {
success: success,
successWithAppend: successWithAppend,
progress: progress,
progressWithAppend: successWithAppend,
error: error,
warning: warning,
showContactUs: showContactUs,
setBusy: setBusy,
clearBusy: clearBusy,
setReady: setReady,
hide: hide
}
}
}]);
/* concatenated from client/src/app/js/profile.js */
angular.module('ekwgApp')
.factory('ProfileConfirmationService', ["$filter", "LoggedInMemberService", "DateUtils", function ($filter, LoggedInMemberService, DateUtils) {
var confirmProfile = function (member) {
if (member) {
member.profileSettingsConfirmed = true;
member.profileSettingsConfirmedAt = DateUtils.nowAsValue();
member.profileSettingsConfirmedBy = $filter('fullNameWithAlias')(LoggedInMemberService.loggedInMember());
}
};
var unconfirmProfile = function (member) {
if (member) {
delete member.profileSettingsConfirmed;
delete member.profileSettingsConfirmedAt;
delete member.profileSettingsConfirmedBy;
}
};
var processMember = function (member) {
if (member) {
if (member.profileSettingsConfirmed) {
confirmProfile(member)
} else {
unconfirmProfile(member)
}
}
};
return {
confirmProfile: confirmProfile,
unconfirmProfile: unconfirmProfile,
processMember: processMember
};
}])
.controller('ProfileController', ["$q", "$rootScope", "$routeParams", "$scope", "LoggedInMemberService", "MemberService", "URLService", "ProfileConfirmationService", "EmailSubscriptionService", "CommitteeReferenceData", function ($q, $rootScope, $routeParams, $scope, LoggedInMemberService, MemberService,
URLService, ProfileConfirmationService, EmailSubscriptionService, CommitteeReferenceData) {
$scope.showArea = function (area) {
URLService.navigateTo('admin', area)
};
$scope.contactUs = {
ready: function () {
return CommitteeReferenceData.ready;
}
};
function isArea(area) {
return (area === $routeParams.area);
}
var LOGIN_DETAILS = 'login details';
var PERSONAL_DETAILS = 'personal details';
var CONTACT_PREFERENCES = 'contact preferences';
var ALERT_CLASS_DANGER = 'alert-danger';
var ALERT_CLASS_SUCCESS = 'alert-success';
$scope.currentMember = {};
$scope.enteredMemberCredentials = {};
$scope.alertClass = ALERT_CLASS_SUCCESS;
$scope.alertType = LOGIN_DETAILS;
$scope.alertMessages = [];
$scope.personalDetailsOpen = isArea('personal-details');
$scope.loginDetailsOpen = isArea('login-details');
$scope.contactPreferencesOpen = isArea('contact-preferences');
$scope.showAlertPersonalDetails = false;
$scope.showAlertLoginDetails = false;
$scope.showAlertContactPreferences = false;
applyAllowEdits('controller init');
refreshMember();
$scope.$on('memberLoginComplete', function () {
$scope.alertMessages = [];
refreshMember();
applyAllowEdits('memberLoginComplete');
});
$scope.$on('memberLogoutComplete', function () {
$scope.alertMessages = [];
applyAllowEdits('memberLogoutComplete');
});
$scope.undoChanges = function () {
refreshMember();
};
function saveOrUpdateSuccessful() {
$scope.enteredMemberCredentials.newPassword = null;
$scope.enteredMemberCredentials.newPasswordConfirm = null;
$scope.alertMessages.push('Your ' + $scope.alertType + ' were saved successfully and will be effective on your next login.');
showAlert(ALERT_CLASS_SUCCESS, $scope.alertType);
}
function saveOrUpdateUnsuccessful(message) {
var messageDefaulted = message || 'Please try again later.';
$scope.alertMessages.push('Changes to your ' + $scope.alertType + ' could not be saved. ' + messageDefaulted);
showAlert(ALERT_CLASS_DANGER, $scope.alertType);
}
$scope.saveLoginDetails = function () {
$scope.alertMessages = [];
validateUserNameExistence();
};
$scope.$on('userNameExistenceCheckComplete', function () {
validatePassword();
validateUserName();
if ($scope.alertMessages.length === 0) {
saveMemberDetails(LOGIN_DETAILS)
} else {
showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS);
}
});
$scope.savePersonalDetails = function () {
$scope.alertMessages = [];
saveMemberDetails(PERSONAL_DETAILS);
};
$scope.saveContactPreferences = function () {
$scope.alertMessages = [];
ProfileConfirmationService.confirmProfile($scope.currentMember);
saveMemberDetails(CONTACT_PREFERENCES);
};
$scope.loggedIn = function () {
return LoggedInMemberService.memberLoggedIn();
};
function validatePassword() {
if ($scope.enteredMemberCredentials.newPassword || $scope.enteredMemberCredentials.newPasswordConfirm) {
// console.log('validating password change old=', $scope.enteredMemberCredentials.newPassword, 'new=', $scope.enteredMemberCredentials.newPasswordConfirm);
if ($scope.currentMember.password === $scope.enteredMemberCredentials.newPassword) {
$scope.alertMessages.push('The new password was the same as the old one.');
} else if ($scope.enteredMemberCredentials.newPassword !== $scope.enteredMemberCredentials.newPasswordConfirm) {
$scope.alertMessages.push('The new password was not confirmed correctly.');
} else if ($scope.enteredMemberCredentials.newPassword.length < 6) {
$scope.alertMessages.push('The new password needs to be at least 6 characters long.');
} else {
$scope.currentMember.password = $scope.enteredMemberCredentials.newPassword;
// console.log('validating password change - successful');
}
}
}
function validateUserName() {
if ($scope.enteredMemberCredentials.userName !== $scope.currentMember.userName) {
$scope.enteredMemberCredentials.userName = $scope.enteredMemberCredentials.userName.trim();
if ($scope.enteredMemberCredentials.userName.length === 0) {
$scope.alertMessages.push('The new user name cannot be blank.');
} else {
$scope.currentMember.userName = $scope.enteredMemberCredentials.userName;
}
}
}
function undoChangesTo(alertType) {
refreshMember();
$scope.alertMessages = ['Changes to your ' + alertType + ' were reverted.'];
showAlert(ALERT_CLASS_SUCCESS, alertType);
}
$scope.undoLoginDetails = function () {
undoChangesTo(LOGIN_DETAILS);
};
$scope.undoPersonalDetails = function () {
undoChangesTo(PERSONAL_DETAILS);
};
$scope.undoContactPreferences = function () {
undoChangesTo(CONTACT_PREFERENCES);
};
function saveMemberDetails(alertType) {
$scope.alertType = alertType;
EmailSubscriptionService.resetUpdateStatusForMember($scope.currentMember);
LoggedInMemberService.saveMember($scope.currentMember, saveOrUpdateSuccessful, saveOrUpdateUnsuccessful);
}
function showAlert(alertClass, alertType) {
if ($scope.alertMessages.length > 0) {
$scope.alertClass = alertClass;
$scope.alertMessage = $scope.alertMessages.join(', ');
$scope.showAlertLoginDetails = alertType === LOGIN_DETAILS;
$scope.showAlertPersonalDetails = alertType === PERSONAL_DETAILS;
$scope.showAlertContactPreferences = alertType === CONTACT_PREFERENCES;
} else {
$scope.showAlertLoginDetails = false;
$scope.showAlertPersonalDetails = false;
$scope.showAlertContactPreferences = false;
}
}
function applyAllowEdits(event) {
$scope.allowEdits = LoggedInMemberService.memberLoggedIn();
$scope.isAdmin = LoggedInMemberService.allowMemberAdminEdits();
}
function refreshMember() {
if (LoggedInMemberService.memberLoggedIn()) {
LoggedInMemberService.getMemberForUserName(LoggedInMemberService.loggedInMember().userName)
.then(function (member) {
if (!_.isEmpty(member)) {
$scope.currentMember = member;
$scope.enteredMemberCredentials = {userName: $scope.currentMember.userName};
} else {
$scope.alertMessages.push('Could not refresh member');
showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS);
}
}, function (response) {
$scope.alertMessages.push('Unexpected error occurred: ' + response);
showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS);
})
}
}
function validateUserNameExistence() {
if ($scope.enteredMemberCredentials.userName !== $scope.currentMember.userName) {
LoggedInMemberService.getMemberForUserName($scope.enteredMemberCredentials.userName)
.then(function (member) {
if (!_.isEmpty(member)) {
$scope.alertMessages.push('The user name ' + $scope.enteredMemberCredentials.userName + ' is already used by another member. Please choose another.');
$scope.enteredMemberCredentials.userName = $scope.currentMember.userName;
}
$rootScope.$broadcast('userNameExistenceCheckComplete');
}, function (response) {
$scope.alertMessages.push('Unexpected error occurred: ' + response);
showAlert(ALERT_CLASS_DANGER, LOGIN_DETAILS);
});
} else {
$rootScope.$broadcast('userNameExistenceCheckComplete');
}
}
}]);
/* concatenated from client/src/app/js/ramblersWalksServices.js */
angular.module('ekwgApp')
.factory('RamblersHttpService', ["$q", "$http", function ($q, $http) {
function call(serviceCallType, method, url, data, params) {
var deferredTask = $q.defer();
deferredTask.notify(serviceCallType);
$http({
method: method,
data: data,
params: params,
url: url
}).then(function (response) {
var responseData = response.data;
if (responseData.error) {
deferredTask.reject(response);
} else {
deferredTask.notify(responseData.information);
deferredTask.resolve(responseData)
}
}).catch(function (response) {
deferredTask.reject(response);
});
return deferredTask.promise;
}
return {
call: call
}
}])
.factory('RamblersWalksAndEventsService', ["$log", "$rootScope", "$http", "$q", "$filter", "DateUtils", "RamblersHttpService", "LoggedInMemberService", "CommitteeReferenceData", function ($log, $rootScope, $http, $q, $filter, DateUtils, RamblersHttpService, LoggedInMemberService, CommitteeReferenceData) {
var logger = $log.getInstance('RamblersWalksAndEventsService');
$log.logLevels['RamblersWalksAndEventsService'] = $log.LEVEL.OFF;
function uploadRamblersWalks(data) {
return RamblersHttpService.call('Upload Ramblers walks', 'POST', 'walksAndEventsManager/uploadWalks', data);
}
function listRamblersWalks() {
return RamblersHttpService.call('List Ramblers walks', 'GET', 'walksAndEventsManager/listWalks');
}
var walkDescriptionPrefix = function () {
return RamblersHttpService.call('Ramblers description Prefix', 'GET', 'walksAndEventsManager/walkDescriptionPrefix');
};
var walkBaseUrl = function () {
return RamblersHttpService.call('Ramblers walk url', 'GET', 'walksAndEventsManager/walkBaseUrl');
};
function exportWalksFileName() {
return 'walks-export-' + DateUtils.asMoment().format('DD-MMMM-YYYY-HH-mm') + '.csv'
}
function exportableWalks(walkExports) {
return _.chain(walkExports)
.filter(function (walkExport) {
return walkExport.selected;
})
.sortBy(function (walkExport) {
return walkExport.walk.walkDate;
})
.value();
}
function exportWalks(walkExports, members) {
return _(exportableWalks(walkExports)).pluck('walk').map(function (walk) {
return walkToCsvRecord(walk, members)
});
}
function createWalksForExportPrompt(walks, members) {
return listRamblersWalks()
.then(updateWalksWithRamblersWalkData(walks))
.then(function (updatedWalks) {
return returnWalksExport(updatedWalks, members);
});
}
function updateWalksWithRamblersWalkData(walks) {
var unreferencedList = collectExistingRamblersIdsFrom(walks);
logger.debug(unreferencedList.length, ' existing ramblers walk(s) found', unreferencedList);
return function (ramblersWalksResponses) {
var savePromises = [];
_(ramblersWalksResponses.responseData).each(function (ramblersWalksResponse) {
var foundWalk = _.find(walks, function (walk) {
return DateUtils.asString(walk.walkDate, undefined, 'dddd, Do MMMM YYYY') === ramblersWalksResponse.ramblersWalkDate
});
if (!foundWalk) {
logger.debug('no match found for ramblersWalksResponse', ramblersWalksResponse);
}
else {
unreferencedList = _.without(unreferencedList, ramblersWalksResponse.ramblersWalkId);
if (foundWalk && foundWalk.ramblersWalkId !== ramblersWalksResponse.ramblersWalkId) {
logger.debug('updating walk from', foundWalk.ramblersWalkId || 'empty', '->', ramblersWalksResponse.ramblersWalkId, 'on', $filter('displayDate')(foundWalk.walkDate));
foundWalk.ramblersWalkId = ramblersWalksResponse.ramblersWalkId;
savePromises.push(foundWalk.$saveOrUpdate())
} else {
logger.debug('no update required for walk', foundWalk.ramblersWalkId, foundWalk.walkDate, DateUtils.displayDay(foundWalk.walkDate));
}
}
});
if (unreferencedList.length > 0) {
logger.debug('removing old ramblers walk(s)', unreferencedList, 'from existing walks');
_.chain(unreferencedList)
.each(function (ramblersWalkId) {
var walk = _.findWhere(walks, {ramblersWalkId: ramblersWalkId});
if (walk) {
logger.debug('removing ramblers walk', walk.ramblersWalkId, 'from walk on', $filter('displayDate')(walk.walkDate));
delete walk.ramblersWalkId;
savePromises.push(walk.$saveOrUpdate())
}
}).value();
}
return $q.all(savePromises).then(function () {
return walks;
});
}
}
function collectExistingRamblersIdsFrom(walks) {
return _.chain(walks)
.filter(function (walk) {
return walk.ramblersWalkId;
})
.map(function (walk) {
return walk.ramblersWalkId;
})
.value();
}
function returnWalksExport(walks, members) {
var todayValue = DateUtils.momentNowNoTime().valueOf();
return _.chain(walks)
.filter(function (walk) {
return (walk.walkDate >= todayValue) && walk.briefDescriptionAndStartPoint;
})
.sortBy(function (walk) {
return walk.walkDate;
})
.map(function (walk) {
return validateWalk(walk, members);
})
.value();
}
function uploadToRamblers(walkExports, members, notify) {
notify.setBusy();
logger.debug('sourceData', walkExports);
var deleteWalks = _.chain(exportableWalks(walkExports)).pluck('walk')
.filter(function (walk) {
return walk.ramblersWalkId;
}).map(function (walk) {
return walk.ramblersWalkId;
}).value();
let rows = exportWalks(walkExports, members);
let fileName = exportWalksFileName();
var data = {
headings: exportColumnHeadings(),
rows: rows,
fileName: fileName,
deleteWalks: deleteWalks,
ramblersUser: LoggedInMemberService.loggedInMember().firstName
};
logger.debug('exporting', data);
notify.warning({
title: 'Ramblers walks upload',
message: 'Uploading ' + rows.length + ' walk(s) to Ramblers...'
});
return uploadRamblersWalks(data)
.then(function (response) {
notify.warning({
title: 'Ramblers walks upload',
message: 'Upload of ' + rows.length + ' walk(s) to Ramblers has been submitted. Monitor the Walk upload audit tab for progress'
});
logger.debug('success response data', response);
notify.clearBusy();
return fileName;
})
.catch(function (response) {
logger.debug('error response data', response);
notify.error({
title: 'Ramblers walks upload failed',
message: response
});
notify.clearBusy();
});
}
function validateWalk(walk, members) {
var walkValidations = [];
if (_.isEmpty(walk)) {
walkValidations.push('walk does not exist');
} else {
if (_.isEmpty(walkTitle(walk))) walkValidations.push('title is missing');
if (_.isEmpty(walkDistanceMiles(walk))) walkValidations.push('distance is missing');
if (_.isEmpty(walk.startTime)) walkValidations.push('start time is missing');
if (walkStartTime(walk) === 'Invalid date') walkValidations.push('start time [' + walk.startTime + '] is invalid');
if (_.isEmpty(walk.grade)) walkValidations.push('grade is missing');
if (_.isEmpty(walk.longerDescription)) walkValidations.push('description is missing');
if (_.isEmpty(walk.postcode) && _.isEmpty(walk.gridReference)) walkValidations.push('both postcode and grid reference are missing');
if (_.isEmpty(walk.contactId)) {
var contactIdMessage = LoggedInMemberService.allowWalkAdminEdits() ? 'this can be supplied for this walk on Walk Leader tab' : 'this will need to be setup for you by ' + CommitteeReferenceData.contactUsField('walks', 'fullName');
walkValidations.push('walk leader has no Ramblers contact Id setup on their member record (' + contactIdMessage + ')');
}
if (_.isEmpty(walk.displayName) && _.isEmpty(walk.displayName)) walkValidations.push('displayName for walk leader is missing');
}
return {
walk: walk,
walkValidations: walkValidations,
publishedOnRamblers: walk && !_.isEmpty(walk.ramblersWalkId),
selected: walk && walkValidations.length === 0 && _.isEmpty(walk.ramblersWalkId)
}
}
var nearestTown = function (walk) {
return walk.nearestTown ? 'Nearest Town is ' + walk.nearestTown : '';
};
function walkTitle(walk) {
var walkDescription = [];
if (walk.briefDescriptionAndStartPoint) walkDescription.push(walk.briefDescriptionAndStartPoint);
return _.chain(walkDescription).map(replaceSpecialCharacters).value().join('. ');
}
function walkDescription(walk) {
return replaceSpecialCharacters(walk.longerDescription);
}
function walkType(walk) {
return walk.walkType || "Circular";
}
function asString(value) {
return value ? value : '';
}
function contactDisplayName(walk) {
return walk.displayName ? replaceSpecialCharacters(_.first(walk.displayName.split(' '))) : '';
}
function contactIdLookup(walk, members) {
if (walk.contactId) {
return walk.contactId;
} else {
var member = _(members).find(function (member) {
return member.$id() === walk.walkLeaderMemberId;
});
var returnValue = member && member.contactId;
logger.debug('contactId: for walkLeaderMemberId', walk.walkLeaderMemberId, '->', returnValue);
return returnValue;
}
}
function replaceSpecialCharacters(value) {
return value ? value
.replace("’", "'")
.replace("é", "e")
.replace("’", "'")
.replace('…', '…')
.replace('–', '–')
.replace('’', '’')
.replace('“', '“')
: '';
}
function walkDistanceMiles(walk) {
return walk.distance ? String(parseFloat(walk.distance).toFixed(1)) : '';
}
function walkStartTime(walk) {
return walk.startTime ? DateUtils.asString(walk.startTime, 'HH mm', 'HH:mm') : '';
}
function walkGridReference(walk) {
return walk.gridReference ? walk.gridReference : '';
}
function walkPostcode(walk) {
return walk.gridReference ? '' : walk.postcode ? walk.postcode : '';
}
function walkDate(walk) {
return DateUtils.asString(walk.walkDate, undefined, 'DD-MM-YYYY');
}
function exportColumnHeadings() {
return [
"Date",
"Title",
"Description",
"Linear or Circular",
"Starting postcode",
"Starting gridref",
"Starting location details",
"Show exact starting point",
"Start time",
"Show exact meeting point?",
"Meeting time",
"Restriction",
"Difficulty",
"Local walk grade",
"Distance miles",
"Contact id",
"Contact display name"
];
}
function walkToCsvRecord(walk, members) {
return {
"Date": walkDate(walk),
"Title": walkTitle(walk),
"Description": walkDescription(walk),
"Linear or Circular": walkType(walk),
"Starting postcode": walkPostcode(walk),
"Starting gridref": walkGridReference(walk),
"Starting location details": nearestTown(walk),
"Show exact starting point": "Yes",
"Start time": walkStartTime(walk),
"Show exact meeting point?": "Yes",
"Meeting time": walkStartTime(walk),
"Restriction": "Public",
"Difficulty": asString(walk.grade),
"Local walk grade": asString(walk.grade),
"Distance miles": walkDistanceMiles(walk),
"Contact id": contactIdLookup(walk, members),
"Contact display name": contactDisplayName(walk)
};
}
return {
uploadToRamblers: uploadToRamblers,
validateWalk: validateWalk,
walkDescriptionPrefix: walkDescriptionPrefix,
walkBaseUrl: walkBaseUrl,
exportWalksFileName: exportWalksFileName,
createWalksForExportPrompt: createWalksForExportPrompt,
exportWalks: exportWalks,
exportableWalks: exportableWalks,
exportColumnHeadings: exportColumnHeadings
}
}]
);
/* concatenated from client/src/app/js/resetPasswordController.js */
angular.module("ekwgApp")
.controller("ResetPasswordController", ["$q", "$log", "$scope", "AuthenticationModalsService", "ValidationUtils", "LoggedInMemberService", "URLService", "Notifier", "userName", "message", "close", function ($q, $log, $scope, AuthenticationModalsService, ValidationUtils, LoggedInMemberService, URLService, Notifier, userName, message, close) {
var logger = $log.getInstance('ResetPasswordController');
$log.logLevels['ResetPasswordController'] = $log.LEVEL.OFF;
$scope.notify = {};
$scope.memberCredentials = {userName: userName};
var notify = Notifier($scope.notify);
if (message) {
notify.progress({
title: "Reset password",
message: message
});
}
$scope.actions = {
submittable: function () {
var newPasswordPopulated = ValidationUtils.fieldPopulated($scope.memberCredentials, "newPassword");
var newPasswordConfirmPopulated = ValidationUtils.fieldPopulated($scope.memberCredentials, "newPasswordConfirm");
logger.info("notSubmittable: newPasswordConfirmPopulated", newPasswordConfirmPopulated, "newPasswordPopulated", newPasswordPopulated);
return newPasswordPopulated && newPasswordConfirmPopulated;
},
close: function () {
close()
},
resetPassword: function () {
notify.showContactUs(false);
notify.setBusy();
notify.progress({
busy: true,
title: "Reset password",
message: "Attempting reset of password for " + $scope.memberCredentials.userName
});
LoggedInMemberService.resetPassword($scope.memberCredentials.userName, $scope.memberCredentials.newPassword, $scope.memberCredentials.newPasswordConfirm).then(function () {
var loginResponse = LoggedInMemberService.loginResponse();
if (LoggedInMemberService.memberLoggedIn()) {
notify.hide();
close();
if (!LoggedInMemberService.loggedInMember().profileSettingsConfirmed) {
return URLService.navigateTo("mailing-preferences");
}
return true;
}
else {
notify.showContactUs(true);
notify.error({
title: "Reset password failed",
message: loginResponse.alertMessage
});
}
return true;
});
}
}
}]
);
/* concatenated from client/src/app/js/resetPasswordFailedController.js */
angular.module('ekwgApp')
.controller('ResetPasswordFailedController', ["$log", "$scope", "URLService", "Notifier", "CommitteeReferenceData", "close", function ($log, $scope, URLService, Notifier, CommitteeReferenceData, close) {
var logger = $log.getInstance('ResetPasswordFailedController');
$log.logLevels['MemberAdminController'] = $log.LEVEL.OFF;
$scope.notify = {};
var notify = Notifier($scope.notify);
logger.info("CommitteeReferenceData:", CommitteeReferenceData.ready);
notify.showContactUs(true);
notify.error({
continue: true,
title: "Reset password failed",
message: "The password reset link you followed has either expired or is invalid. Click Restart Forgot Password to try again"
});
$scope.actions = {
close: function () {
close()
},
forgotPassword: function () {
URLService.navigateTo("forgot-password");
},
}
}]);
/* concatenated from client/src/app/js/services.js */
angular.module('ekwgApp')
.factory('DateUtils', ["$log", function ($log) {
var logger = $log.getInstance('DateUtils');
$log.logLevels['DateUtils'] = $log.LEVEL.OFF;
var formats = {
displayDateAndTime: 'ddd DD-MMM-YYYY, h:mm:ss a',
displayDateTh: 'MMMM Do YYYY',
displayDate: 'ddd DD-MMM-YYYY',
displayDay: 'dddd MMMM D, YYYY',
ddmmyyyyWithSlashes: 'DD/MM/YYYY',
yyyymmdd: 'YYYYMMDD'
};
function isDate(value) {
return value && asMoment(value).isValid();
}
function asMoment(dateValue, inputFormat) {
return moment(dateValue, inputFormat).tz("Europe/London");
}
function momentNow() {
return asMoment();
}
function asString(dateValue, inputFormat, outputFormat) {
var returnValue = dateValue ? asMoment(dateValue, inputFormat).format(outputFormat) : undefined;
logger.debug('asString: dateValue ->', dateValue, 'inputFormat ->', inputFormat, 'outputFormat ->', outputFormat, 'returnValue ->', returnValue);
return returnValue;
}
function asValue(dateValue, inputFormat) {
return asMoment(dateValue, inputFormat).valueOf();
}
function nowAsValue() {
return asMoment(undefined, undefined).valueOf();
}
function mailchimpDate(dateValue) {
return asString(dateValue, undefined, formats.ddmmyyyyWithSlashes);
}
function displayDateAndTime(dateValue) {
return asString(dateValue, undefined, formats.displayDateAndTime);
}
function displayDate(dateValue) {
return asString(dateValue, undefined, formats.displayDate);
}
function displayDay(dateValue) {
return asString(dateValue, undefined, formats.displayDay);
}
function asValueNoTime(dateValue, inputFormat) {
var returnValue = asMoment(dateValue, inputFormat).startOf('day').valueOf();
logger.debug('asValueNoTime: dateValue ->', dateValue, 'returnValue ->', returnValue, '->', displayDateAndTime(returnValue));
return returnValue;
}
function currentMemberBulkLoadDisplayDate() {
return asString(momentNowNoTime().startOf('month'), undefined, formats.yyyymmdd);
}
function momentNowNoTime() {
return asMoment().startOf('day');
}
function convertDateFieldInObject(object, field) {
var inputValue = object[field];
object[field] = convertDateField(inputValue);
return object;
}
function convertDateField(inputValue) {
if (inputValue) {
var dateValue = asValueNoTime(inputValue);
if (dateValue !== inputValue) {
logger.debug('Converting date from', inputValue, '(' + displayDateAndTime(inputValue) + ') to', dateValue, '(' + displayDateAndTime(dateValue) + ')');
return dateValue;
} else {
logger.debug(inputValue, inputValue, 'is already in correct format');
return inputValue;
}
} else {
logger.debug(inputValue, 'is not a date - no conversion');
return inputValue;
}
}
return {
formats: formats,
displayDateAndTime: displayDateAndTime,
displayDay: displayDay,
displayDate: displayDate,
mailchimpDate: mailchimpDate,
convertDateFieldInObject: convertDateFieldInObject,
convertDateField: convertDateField,
isDate: isDate,
asMoment: asMoment,
nowAsValue: nowAsValue,
momentNow: momentNow,
momentNowNoTime: momentNowNoTime,
asString: asString,
asValue: asValue,
asValueNoTime: asValueNoTime,
currentMemberBulkLoadDisplayDate: currentMemberBulkLoadDisplayDate
};
}])
.factory('DbUtils', ["$log", "DateUtils", "LoggedInMemberService", "AUDIT_CONFIG", function ($log, DateUtils, LoggedInMemberService, AUDIT_CONFIG) {
var logger = $log.getInstance('DbUtilsLogger');
$log.logLevels['DbUtilsLogger'] = $log.LEVEL.OFF;
function removeEmptyFieldsIn(obj) {
_.each(obj, function (value, field) {
logger.debug('processing', typeof(field), 'field', field, 'value', value);
if (_.contains([null, undefined, ""], value)) {
logger.debug('removing non-populated', typeof(field), 'field', field);
delete obj[field];
}
});
}
function auditedSaveOrUpdate(resource, updateCallback, errorCallback) {
if (AUDIT_CONFIG.auditSave) {
if (resource.$id()) {
resource.updatedDate = DateUtils.nowAsValue();
resource.updatedBy = LoggedInMemberService.loggedInMember().memberId;
logger.debug('Auditing save of existing document', resource);
} else {
resource.createdDate = DateUtils.nowAsValue();
resource.createdBy = LoggedInMemberService.loggedInMember().memberId;
logger.debug('Auditing save of new document', resource);
}
} else {
resource = DateUtils.convertDateFieldInObject(resource, 'createdDate');
logger.debug('Not auditing save of', resource);
}
return resource.$saveOrUpdate(updateCallback, updateCallback, errorCallback || updateCallback, errorCallback || updateCallback)
}
return {
removeEmptyFieldsIn: removeEmptyFieldsIn,
auditedSaveOrUpdate: auditedSaveOrUpdate,
}
}])
.factory('FileUtils', ["$log", "DateUtils", "URLService", "ContentMetaDataService", function ($log, DateUtils, URLService, ContentMetaDataService) {
var logger = $log.getInstance('FileUtils');
$log.logLevels['FileUtils'] = $log.LEVEL.OFF;
function basename(path) {
return path.split(/[\\/]/).pop()
}
function path(path) {
return path.split(basename(path))[0];
}
function attachmentTitle(resource, container, resourceName) {
return (resource && _.isEmpty(getFileNameData(resource, container)) ? 'Attach' : 'Replace') + ' ' + resourceName;
}
function getFileNameData(resource, container) {
return container ? resource[container].fileNameData : resource.fileNameData;
}
function resourceUrl(resource, container, metaDataPathSegment) {
var fileNameData = getFileNameData(resource, container);
return resource && fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl(metaDataPathSegment) + '/' + fileNameData.awsFileName : '';
}
function previewUrl(memberResource) {
if (memberResource) {
switch (memberResource.resourceType) {
case "email":
return memberResource.data.campaign.archive_url_long;
case "file":
return memberResource.data.campaign.archive_url_long;
}
}
var fileNameData = getFileNameData(resource, container);
return resource && fileNameData ? URLService.baseUrl() + ContentMetaDataService.baseUrl(metaDataPathSegment) + '/' + fileNameData.awsFileName : '';
}
function resourceTitle(resource) {
logger.debug('resourceTitle:resource =>', resource);
return resource ? (DateUtils.asString(resource.resourceDate, undefined, DateUtils.formats.displayDateTh) + ' - ' + (resource.data ? resource.data.fileNameData.title : "")) : '';
}
function fileExtensionIs(fileName, extensions) {
return _.contains(extensions, fileExtension(fileName));
}
function fileExtension(fileName) {
return fileName ? _.last(fileName.split('.')).toLowerCase() : '';
}
function icon(resource, container) {
var icon = 'icon-default.jpg';
var fileNameData = getFileNameData(resource, container);
if (fileNameData && fileExtensionIs(fileNameData.awsFileName, ['doc', 'docx', 'jpg', 'pdf', 'ppt', 'png', 'txt', 'xls', 'xlsx'])) {
icon = 'icon-' + fileExtension(fileNameData.awsFileName).substring(0, 3) + '.jpg';
}
return "assets/images/ramblers/" + icon;
}
return {
fileExtensionIs: fileExtensionIs,
fileExtension: fileExtension,
basename: basename,
path: path,
attachmentTitle: attachmentTitle,
resourceUrl: resourceUrl,
resourceTitle: resourceTitle,
icon: icon
}
}])
.factory('StringUtils', ["DateUtils", "$filter", function (DateUtils, $filter) {
function replaceAll(find, replace, str) {
return str ? str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace) : str;
}
function stripLineBreaks(str, andTrim) {
var replacedValue = str.replace(/(\r\n|\n|\r)/gm, '');
return andTrim && replacedValue ? replacedValue.trim() : replacedValue;
}
function left(str, chars) {
return str.substr(0, chars);
}
function formatAudit(who, when, members) {
var by = who ? 'by ' + $filter('memberIdToFullName')(who, members) : '';
return (who || when) ? by + (who && when ? ' on ' : '') + DateUtils.displayDateAndTime(when) : '(not audited)';
}
return {
left: left,
replaceAll: replaceAll,
stripLineBreaks: stripLineBreaks,
formatAudit: formatAudit
}
}]).factory('ValidationUtils', function () {
function fieldPopulated(object, path) {
return (_.property(path)(object) || "").length > 0;
}
return {
fieldPopulated: fieldPopulated,
}
})
.factory('NumberUtils', ["$log", function ($log) {
var logger = $log.getInstance('NumberUtils');
$log.logLevels['NumberUtils'] = $log.LEVEL.OFF;
function sumValues(items, fieldName) {
if (!items) return 0;
return _.chain(items).pluck(fieldName).reduce(function (memo, num) {
return memo + asNumber(num);
}, 0).value();
}
function generateUid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function asNumber(numberString, decimalPlaces) {
if (!numberString) return 0;
var isNumber = typeof numberString === 'number';
if (isNumber && !decimalPlaces) return numberString;
var number = isNumber ? numberString : parseFloat(numberString.replace(/[^\d\.\-]/g, ""));
if (isNaN(number)) return 0;
var returnValue = (decimalPlaces) ? (parseFloat(number).toFixed(decimalPlaces)) / 1 : number;
logger.debug('asNumber:', numberString, decimalPlaces, '->', returnValue);
return returnValue;
}
return {
asNumber: asNumber,
sumValues: sumValues,
generateUid: generateUid
};
}])
.factory('ContentMetaData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('contentMetaData');
}])
.factory('ConfigData', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('config');
}])
.factory('Config', ["$log", "ConfigData", "ErrorMessageService", function ($log, ConfigData, ErrorMessageService) {
var logger = $log.getInstance('Config');
$log.logLevels['Config'] = $log.LEVEL.OFF;
function getConfig(key, defaultOnEmpty) {
logger.debug('getConfig:', key, 'defaultOnEmpty:', defaultOnEmpty);
var queryObject = {};
queryObject[key] = {$exists: true};
return ConfigData.query(queryObject, {limit: 1})
.then(function (results) {
if (results && results.length > 0) {
return results[0];
} else {
queryObject[key] = {};
return new ConfigData(defaultOnEmpty || queryObject);
}
}, function (response) {
throw new Error('Query of ' + key + ' config failed: ' + response);
});
}
function saveConfig(key, config, saveCallback, errorSaveCallback) {
logger.debug('saveConfig:', key);
if (_.has(config, key)) {
return config.$saveOrUpdate(saveCallback, saveCallback, errorSaveCallback || saveCallback, errorSaveCallback || saveCallback);
} else {
throw new Error('Attempt to save ' + ErrorMessageService.stringify(key) + ' config when ' + ErrorMessageService.stringify(key) + ' parent key not present in data: ' + ErrorMessageService.stringify(config));
}
}
return {
getConfig: getConfig,
saveConfig: saveConfig
}
}])
.factory('ExpenseClaimsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('expenseClaims');
}])
.factory('RamblersUploadAudit', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('ramblersUploadAudit');
}])
.factory('ErrorTransformerService', ["ErrorMessageService", function (ErrorMessageService) {
function transform(errorResponse) {
var message = ErrorMessageService.stringify(errorResponse);
var duplicate = s.include(errorResponse, 'duplicate');
if (duplicate) {
message = 'Duplicate data was detected. A member record must have a unique Contact Email, Display Name, Ramblers Membership Number and combination of First Name, Last Name and Alias. Please amend the current member and try again.';
}
return {duplicate: duplicate, message: message}
}
return {transform: transform}
}])
.factory('ErrorMessageService', function () {
function stringify(message) {
return _.isObject(message) ? JSON.stringify(message, censor(message)) : message;
}
function censor(censor) {
var i = 0;
return function (key, value) {
if (i !== 0 && typeof(censor) === 'object' && typeof(value) === 'object' && censor === value)
return '[Circular]';
if (i >= 29) // seems to be a hard maximum of 30 serialized objects?
return '[Unknown]';
++i; // so we know we aren't using the original object anymore
return value;
}
}
return {
stringify: stringify
}
});
/* concatenated from client/src/app/js/siteEditActions.js */
angular.module('ekwgApp')
.component('siteEditActions', {
templateUrl: 'partials/components/site-edit.html',
controller: ["$log", "SiteEditService", function ($log, SiteEditService){
var logger = $log.getInstance('SiteEditActionsController');
$log.logLevels['SiteEditActionsController'] = $log.LEVEL.OFF;
var ctrl = this;
logger.info("initialised with SiteEditService.active()", SiteEditService.active());
ctrl.userEdits = {preview: true, saveInProgress: false, revertInProgress: false};
ctrl.editSiteActive = function () {
return SiteEditService.active() ? "active" : "";
};
ctrl.editSiteCaption = function () {
return SiteEditService.active() ? "editing site" : "edit site";
};
ctrl.toggleEditSite = function () {
SiteEditService.toggle();
};
}],
bindings: {
name: '@',
description: '@',
}
});
/* concatenated from client/src/app/js/siteEditService.js */
angular.module('ekwgApp')
.factory('SiteEditService', ["$log", "$cookieStore", "$rootScope", function ($log, $cookieStore, $rootScope) {
var logger = $log.getInstance('SiteEditService');
$log.logLevels['SiteEditService'] = $log.LEVEL.OFF;
function active() {
var active = Boolean($cookieStore.get("editSite"));
logger.debug("active:", active);
return active;
}
function toggle() {
var priorState = active();
var newState = !priorState;
logger.debug("toggle:priorState", priorState, "newState", newState);
$cookieStore.put("editSite", newState);
return $rootScope.$broadcast("editSite", newState);
}
return {
active: active,
toggle: toggle
}
}]);
/* concatenated from client/src/app/js/socialEventNotifications.js */
angular.module('ekwgApp')
.controller('SocialEventNotificationsController', ["MAILCHIMP_APP_CONSTANTS", "$window", "$log", "$sce", "$timeout", "$templateRequest", "$compile", "$q", "$rootScope", "$scope", "$filter", "$routeParams", "$location", "URLService", "DateUtils", "NumberUtils", "LoggedInMemberService", "MemberService", "ContentMetaDataService", "CommitteeFileService", "MailchimpSegmentService", "MailchimpCampaignService", "MailchimpConfig", "Notifier", "CommitteeReferenceData", "socialEvent", "close", function (MAILCHIMP_APP_CONSTANTS, $window, $log, $sce, $timeout, $templateRequest, $compile, $q, $rootScope, $scope, $filter, $routeParams,
$location, URLService, DateUtils, NumberUtils, LoggedInMemberService, MemberService,
ContentMetaDataService, CommitteeFileService, MailchimpSegmentService, MailchimpCampaignService,
MailchimpConfig, Notifier, CommitteeReferenceData, socialEvent, close) {
var logger = $log.getInstance('SocialEventNotificationsController');
$log.logLevels['SocialEventNotificationsController'] = $log.LEVEL.OFF;
$scope.notify = {};
var notify = Notifier($scope.notify);
notify.setBusy();
logger.debug('created with social event', socialEvent);
$scope.attachmentBaseUrl = ContentMetaDataService.baseUrl('socialEvents');
$scope.destinationType = '';
$scope.members = [];
$scope.selectableRecipients = [];
$scope.committeeFiles = [];
$scope.alertMessages = [];
$scope.allowConfirmDelete = false;
$scope.latestYearOpen = true;
$scope.roles = {signoff: [], replyTo: []};
$scope.showAlertMessage = function () {
return ($scope.notify.alert.class === 'alert-danger') || $scope.userEdits.sendInProgress;
};
function initialiseNotification(socialEvent) {
if (socialEvent) {
$scope.socialEvent = socialEvent;
onFirstNotificationOnly();
forEveryNotification();
} else {
logger.error('no socialEvent - problem!');
}
function onFirstNotificationOnly() {
if (!$scope.socialEvent.notification) {
$scope.socialEvent.notification = {
destinationType: 'all-ekwg-social',
recipients: [],
addresseeType: 'Hi *|FNAME|*,',
items: {
title: {include: true},
notificationText: {include: true, value: ''},
description: {include: true},
attendees: {include: socialEvent.attendees.length > 0},
attachment: {include: socialEvent.attachment},
replyTo: {
include: $scope.socialEvent.displayName,
value: $scope.socialEvent.displayName ? 'organiser' : 'social'
},
signoffText: {
include: true,
value: 'If you have any questions about the above, please don\'t hesitate to contact me.\n\nBest regards,'
}
}
};
logger.debug('onFirstNotificationOnly - creating $scope.socialEvent.notification ->', $scope.socialEvent.notification);
}
}
function forEveryNotification() {
$scope.socialEvent.notification.items.signoffAs = {
include: true,
value: loggedOnRole().type || 'social'
};
logger.debug('forEveryNotification - $scope.socialEvent.notification.signoffAs ->', $scope.socialEvent.notification.signoffAs);
}
}
function loggedOnRole() {
var memberId = LoggedInMemberService.loggedInMember().memberId;
var loggedOnRoleData = _(CommitteeReferenceData.contactUsRolesAsArray()).find(function (role) {
return role.memberId === memberId
});
logger.debug('loggedOnRole for', memberId, '->', loggedOnRoleData);
return loggedOnRoleData || {};
}
function roleForType(type) {
var role = _($scope.roles.replyTo).find(function (role) {
return role.type === type;
});
logger.debug('roleForType for', type, '->', role);
return role;
}
function initialiseRoles() {
$scope.roles.signoff = CommitteeReferenceData.contactUsRolesAsArray();
$scope.roles.replyTo = _.clone($scope.roles.signoff);
if ($scope.socialEvent.eventContactMemberId) {
$scope.roles.replyTo.unshift({
type: 'organiser',
fullName: $scope.socialEvent.displayName,
memberId: $scope.socialEvent.eventContactMemberId,
description: 'Organiser (' + $scope.socialEvent.displayName + ')',
email: $scope.socialEvent.contactEmail
});
}
logger.debug('initialiseRoles -> $scope.roles ->', $scope.roles);
}
$scope.formattedText = function () {
return $filter('lineFeedsToBreaks')($scope.socialEvent.notification.items.notificationText.value);
};
$scope.attachmentTitle = function (socialEvent) {
return socialEvent && socialEvent.attachment ? (socialEvent.attachment.title || socialEvent.attachmentTitle || 'Attachment: ' + socialEvent.attachment.originalFileName) : '';
};
$scope.attachmentUrl = function (socialEvent) {
return socialEvent && socialEvent.attachment ? URLService.baseUrl() + $scope.attachmentBaseUrl + '/' + socialEvent.attachment.awsFileName : '';
};
$scope.editAllSocialRecipients = function () {
$scope.socialEvent.notification.destinationType = 'custom';
$scope.socialEvent.notification.recipients = $scope.userEdits.socialList();
};
$scope.editAttendeeRecipients = function () {
$scope.socialEvent.notification.destinationType = 'custom';
$scope.socialEvent.notification.recipients = $scope.socialEvent.attendees;
};
$scope.clearRecipients = function () {
$scope.socialEvent.notification.recipients = [];
};
$scope.formattedSignoffText = function () {
return $filter('lineFeedsToBreaks')($scope.socialEvent.notification.items.signoffText.value);
};
$scope.attendeeList = function () {
return _($scope.socialEvent.notification && $scope.socialEvent.attendees)
.sortBy(function (attendee) {
return attendee.text;
}).map(function (attendee) {
return attendee.text;
}).join(', ');
};
$scope.memberGrouping = function (member) {
return member.memberGrouping;
};
function toSelectMember(member) {
var memberGrouping;
var order;
if (member.socialMember && member.mailchimpLists.socialEvents.subscribed) {
memberGrouping = 'Subscribed to social emails';
order = 0;
} else if (member.socialMember && !member.mailchimpLists.socialEvents.subscribed) {
memberGrouping = 'Not subscribed to social emails';
order = 1;
} else if (!member.socialMember) {
memberGrouping = 'Not a social member';
order = 2;
} else {
memberGrouping = 'Unexpected state';
order = 3;
}
return {
id: member.$id(),
order: order,
memberGrouping: memberGrouping,
text: $filter('fullNameWithAlias')(member)
};
}
function refreshMembers() {
if (LoggedInMemberService.memberLoggedIn()) {
MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS).then(function (members) {
$scope.members = members;
logger.debug('refreshMembers -> populated ->', $scope.members.length, 'members');
$scope.selectableRecipients = _.chain(members)
.map(toSelectMember)
.sortBy(function (member) {
return member.order + member.text
})
.value();
logger.debug('refreshMembers -> populated ->', $scope.selectableRecipients.length, 'selectableRecipients');
notify.clearBusy();
});
}
}
$scope.contactUs = {
ready: function () {
return CommitteeReferenceData.ready;
}
};
$scope.userEdits = {
sendInProgress: false,
cancelFlow: false,
socialList: function () {
return _.chain($scope.members)
.filter(MemberService.filterFor.SOCIAL_MEMBERS_SUBSCRIBED)
.map(toSelectMember).value();
},
replyToRole: function () {
return _($scope.roles.replyTo).find(function (role) {
return role.type === $scope.socialEvent.notification.items.replyTo.value;
});
},
notReady: function () {
return $scope.members.length === 0 || $scope.userEdits.sendInProgress;
}
};
$scope.cancelSendNotification = function () {
close();
$('#social-event-dialog').modal('show');
};
$scope.completeInMailchimp = function () {
notify.warning({
title: 'Complete in Mailchimp',
message: 'You can close this dialog now as the message was presumably completed and sent in Mailchimp'
});
$scope.confirmSendNotification(true);
};
$scope.confirmSendNotification = function (dontSend) {
notify.setBusy();
var campaignName = $scope.socialEvent.briefDescription;
logger.debug('sendSocialNotification:notification->', $scope.socialEvent.notification);
notify.progress({title: campaignName, message: 'preparing and sending notification'});
$scope.userEdits.sendInProgress = true;
$scope.userEdits.cancelFlow = false;
function getTemplate() {
return $templateRequest($sce.getTrustedResourceUrl('partials/socialEvents/social-notification.html'))
}
return $q.when(createOrSaveMailchimpSegment())
.then(getTemplate)
.then(renderTemplateContent)
.then(populateContentSections)
.then(sendEmailCampaign)
.then(saveSocialEvent)
.then(notifyEmailSendComplete)
.catch(handleError);
function handleError(errorResponse) {
$scope.userEdits.sendInProgress = false;
notify.error({
title: 'Your notification could not be sent',
message: (errorResponse.message || errorResponse) + (errorResponse.error ? ('. Error was: ' + JSON.stringify(errorResponse.error)) : '')
});
notify.clearBusy();
}
function renderTemplateContent(templateData) {
var task = $q.defer();
var templateFunction = $compile(templateData);
var templateElement = templateFunction($scope);
$timeout(function () {
$scope.$digest();
task.resolve(templateElement.html());
});
return task.promise;
}
function populateContentSections(notificationText) {
logger.debug('populateContentSections -> notificationText', notificationText);
return {
sections: {
notification_text: notificationText
}
};
}
function writeSegmentResponseDataToEvent(segmentResponse) {
$scope.socialEvent.mailchimp = {
segmentId: segmentResponse.segment.id
};
if (segmentResponse.members) $scope.socialEvent.mailchimp.members = segmentResponse.members;
}
function createOrSaveMailchimpSegment() {
var members = segmentMembers();
if (members.length > 0) {
return MailchimpSegmentService.saveSegment('socialEvents', $scope.socialEvent.mailchimp, members, MailchimpSegmentService.formatSegmentName($scope.socialEvent.briefDescription), $scope.members)
.then(writeSegmentResponseDataToEvent)
.catch(handleError);
} else {
logger.debug('not saving segment data as destination type is whole mailing list ->', $scope.socialEvent.notification.destinationType);
return true;
}
}
function segmentMembers() {
switch ($scope.socialEvent.notification.destinationType) {
case 'attendees':
return $scope.socialEvent.attendees;
case 'custom':
return $scope.socialEvent.notification.recipients;
default:
return [];
}
}
function sendEmailCampaign(contentSections) {
var replyToRole = roleForType($scope.socialEvent.notification.items.replyTo.value || 'social');
var otherOptions = ($scope.socialEvent.notification.items.replyTo.include && replyToRole.fullName && replyToRole.email) ? {
from_name: replyToRole.fullName,
from_email: replyToRole.email
} : {};
notify.progress(dontSend ? ('Preparing to complete ' + campaignName + ' in Mailchimp') : ('Sending ' + campaignName));
logger.debug('Sending ' + campaignName, 'with otherOptions', otherOptions);
return MailchimpConfig.getConfig()
.then(function (config) {
var campaignId = config.mailchimp.campaigns.socialEvents.campaignId;
switch ($scope.socialEvent.notification.destinationType) {
case 'all-ekwg-social':
logger.debug('about to replicateAndSendWithOptions to all-ekwg-social with campaignName', campaignName, 'campaign Id', campaignId);
return MailchimpCampaignService.replicateAndSendWithOptions({
campaignId: campaignId,
campaignName: campaignName,
contentSections: contentSections,
otherSegmentOptions: otherOptions,
dontSend: dontSend
}).then(openInMailchimpIf(dontSend));
default:
if (!$scope.socialEvent.mailchimp) notify.warning('Cant send campaign due to previous request failing. This could be due to network problems - please try this again');
var segmentId = $scope.socialEvent.mailchimp.segmentId;
logger.debug('about to replicateAndSendWithOptions to social with campaignName', campaignName, 'campaign Id', campaignId, 'segmentId', segmentId);
return MailchimpCampaignService.replicateAndSendWithOptions({
campaignId: campaignId,
campaignName: campaignName,
contentSections: contentSections,
segmentId: segmentId,
otherSegmentOptions: otherOptions,
dontSend: dontSend
}).then(openInMailchimpIf(dontSend));
}
})
}
function openInMailchimpIf(dontSend) {
return function (replicateCampaignResponse) {
logger.debug('openInMailchimpIf:replicateCampaignResponse', replicateCampaignResponse, 'dontSend', dontSend);
if (dontSend) {
return $window.open(MAILCHIMP_APP_CONSTANTS.apiServer + "/campaigns/wizard/neapolitan?id=" + replicateCampaignResponse.web_id, '_blank');
} else {
return true;
}
}
}
function saveSocialEvent() {
return $scope.socialEvent.$saveOrUpdate();
}
function notifyEmailSendComplete() {
notify.success('Sending of ' + campaignName + ' was successful.', false);
$scope.userEdits.sendInProgress = false;
if (!$scope.userEdits.cancelFlow) {
close();
}
notify.clearBusy();
}
};
refreshMembers();
initialiseNotification(socialEvent);
initialiseRoles(CommitteeReferenceData);
}]
);
/* concatenated from client/src/app/js/socialEvents.js */
angular.module('ekwgApp')
.factory('SocialEventsService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('socialEvents');
}])
.factory('SocialEventAttendeeService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('socialEventAttendees');
}])
.controller('SocialEventsController', ["$routeParams", "$log", "$q", "$scope", "$filter", "URLService", "Upload", "SocialEventsService", "SiteEditService", "SocialEventAttendeeService", "LoggedInMemberService", "MemberService", "AWSConfig", "ContentMetaDataService", "DateUtils", "MailchimpSegmentService", "ClipboardService", "Notifier", "EKWGFileUpload", "CommitteeReferenceData", "ModalService", function ($routeParams, $log, $q, $scope, $filter, URLService, Upload,
SocialEventsService, SiteEditService,
SocialEventAttendeeService, LoggedInMemberService, MemberService,
AWSConfig, ContentMetaDataService, DateUtils, MailchimpSegmentService,
ClipboardService, Notifier, EKWGFileUpload, CommitteeReferenceData, ModalService) {
$scope.userEdits = {
copyToClipboard: ClipboardService.copyToClipboard,
longerDescriptionPreview: true,
socialEventLink: function (socialEvent) {
return socialEvent && socialEvent.$id() ? URLService.notificationHref({
type: "socialEvent",
area: "social",
id: socialEvent.$id()
}) : undefined;
}
};
$scope.previewLongerDescription = function () {
logger.debug('previewLongerDescription');
$scope.userEdits.longerDescriptionPreview = true;
};
$scope.editLongerDescription = function () {
logger.debug('editLongerDescription');
$scope.userEdits.longerDescriptionPreview = false;
};
$scope.contactUs = {
ready: function () {
return CommitteeReferenceData.ready;
}
};
var logger = $log.getInstance('SocialEventsController');
$log.logLevels['SocialEventsController'] = $log.LEVEL.OFF;
var notify = Notifier($scope);
$scope.attachmentBaseUrl = ContentMetaDataService.baseUrl('socialEvents');
$scope.selectMembers = [];
$scope.display = {attendees: []};
$scope.socialEventsDetailProgrammeOpen = true;
$scope.socialEventsBriefProgrammeOpen = true;
$scope.socialEventsInformationOpen = true;
$scope.todayValue = DateUtils.momentNowNoTime().valueOf();
applyAllowEdits('controllerInitialisation');
$scope.eventDateCalendar = {
open: function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.eventDateCalendar.opened = true;
}
};
$scope.$on('memberLoginComplete', function () {
applyAllowEdits('memberLoginComplete');
refreshMembers();
refreshSocialEvents();
});
$scope.$on('memberLogoutComplete', function () {
applyAllowEdits('memberLogoutComplete');
});
$scope.$on('editSite', function () {
applyAllowEdits('editSite');
});
$scope.addSocialEvent = function () {
showSocialEventDialog(new SocialEventsService({eventDate: $scope.todayValue, attendees: []}), 'Add New');
};
$scope.viewSocialEvent = function (socialEvent) {
showSocialEventDialog(socialEvent, 'View');
};
$scope.editSocialEvent = function (socialEvent) {
showSocialEventDialog(socialEvent, 'Edit Existing');
};
$scope.deleteSocialEventDetails = function () {
$scope.allowDelete = false;
$scope.allowConfirmDelete = true;
};
$scope.cancelSocialEventDetails = function () {
hideSocialEventDialogAndRefreshSocialEvents();
};
$scope.saveSocialEventDetails = function () {
$q.when(notify.progress({title: 'Save in progress', message: 'Saving social event'}, true))
.then(prepareToSave, notify.error, notify.progress)
.then(saveSocialEvent, notify.error, notify.progress)
.then(notify.clearBusy, notify.error, notify.progress)
.catch(notify.error);
};
function prepareToSave() {
DateUtils.convertDateFieldInObject($scope.currentSocialEvent, 'eventDate');
}
function saveSocialEvent() {
return $scope.currentSocialEvent.$saveOrUpdate(hideSocialEventDialogAndRefreshSocialEvents, hideSocialEventDialogAndRefreshSocialEvents);
}
$scope.confirmDeleteSocialEventDetails = function () {
$q.when(notify.progress('Deleting social event', true))
.then(deleteMailchimpSegment, notify.error, notify.progress)
.then(removeSocialEventHideSocialEventDialogAndRefreshSocialEvents, notify.error, notify.progress)
.then(notify.clearBusy, notify.error, notify.progress)
.catch(notify.error);
};
var deleteMailchimpSegment = function () {
if ($scope.currentSocialEvent.mailchimp && $scope.currentSocialEvent.mailchimp.segmentId) {
return MailchimpSegmentService.deleteSegment('socialEvents', $scope.currentSocialEvent.mailchimp.segmentId);
}
};
var removeSocialEventHideSocialEventDialogAndRefreshSocialEvents = function () {
$scope.currentSocialEvent.$remove(hideSocialEventDialogAndRefreshSocialEvents)
};
$scope.copyDetailsToNewSocialEvent = function () {
var copiedSocialEvent = new SocialEventsService($scope.currentSocialEvent);
delete copiedSocialEvent._id;
delete copiedSocialEvent.mailchimp;
DateUtils.convertDateFieldInObject(copiedSocialEvent, 'eventDate');
showSocialEventDialog(copiedSocialEvent, 'Copy Existing');
notify.success({
title: 'Existing social event copied!',
message: 'Make changes here and save to create a new social event.'
});
};
$scope.selectMemberContactDetails = function () {
var socialEvent = $scope.currentSocialEvent;
var memberId = socialEvent.eventContactMemberId;
if (memberId === null) {
delete socialEvent.eventContactMemberId;
delete socialEvent.displayName;
delete socialEvent.contactPhone;
delete socialEvent.contactEmail;
// console.log('deleted contact details from', socialEvent);
} else {
var selectedMember = _.find($scope.members, function (member) {
return member.$id() === memberId;
});
socialEvent.displayName = selectedMember.displayName;
socialEvent.contactPhone = selectedMember.mobileNumber;
socialEvent.contactEmail = selectedMember.email;
// console.log('set contact details on', socialEvent);
}
};
$scope.dataQueryParameters = {
query: '',
selectType: '1',
newestFirst: 'false'
};
$scope.removeAttachment = function () {
delete $scope.currentSocialEvent.attachment;
delete $scope.currentSocialEvent.attachmentTitle;
$scope.uploadedFile = undefined;
};
$scope.resetMailchimpData = function () {
delete $scope.currentSocialEvent.mailchimp;
};
$scope.addOrReplaceAttachment = function () {
$('#hidden-input').click();
};
$scope.attachmentTitle = function (socialEvent) {
return socialEvent && socialEvent.attachment ? (socialEvent.attachment.title || socialEvent.attachmentTitle || 'Attachment: ' + socialEvent.attachment.originalFileName) : '';
};
$scope.attachmentUrl = function (socialEvent) {
return socialEvent && socialEvent.attachment ? $scope.attachmentBaseUrl + '/' + socialEvent.attachment.awsFileName : '';
};
$scope.onFileSelect = function (file) {
if (file) {
$scope.uploadedFile = file;
EKWGFileUpload.onFileSelect(file, notify, 'socialEvents').then(function (fileNameData) {
$scope.currentSocialEvent.attachment = fileNameData;
});
}
};
function allowSummaryView() {
return (LoggedInMemberService.allowSocialAdminEdits() || !LoggedInMemberService.allowSocialDetailView());
}
function applyAllowEdits(event) {
$scope.allowDelete = false;
$scope.allowConfirmDelete = false;
$scope.allowDetailView = LoggedInMemberService.allowSocialDetailView();
$scope.allowEdits = LoggedInMemberService.allowSocialAdminEdits();
$scope.allowCopy = LoggedInMemberService.allowSocialAdminEdits();
$scope.allowContentEdits = SiteEditService.active() && LoggedInMemberService.allowContentEdits();
$scope.allowSummaryView = allowSummaryView();
}
$scope.showLoginTooltip = function () {
return !LoggedInMemberService.memberLoggedIn();
};
$scope.login = function () {
if (!LoggedInMemberService.memberLoggedIn()) {
URLService.navigateTo("login");
}
};
function showSocialEventDialog(socialEvent, socialEventEditMode) {
$scope.uploadedFile = undefined;
$scope.showAlert = false;
$scope.allowConfirmDelete = false;
if (!socialEvent.attendees) socialEvent.attendees = [];
$scope.allowEdits = LoggedInMemberService.allowSocialAdminEdits();
var existingRecordEditEnabled = $scope.allowEdits && s.startsWith(socialEventEditMode, 'Edit');
$scope.allowCopy = existingRecordEditEnabled;
$scope.allowDelete = existingRecordEditEnabled;
$scope.socialEventEditMode = socialEventEditMode;
$scope.currentSocialEvent = socialEvent;
$('#social-event-dialog').modal('show');
}
$scope.attendeeCaption = function () {
return $scope.currentSocialEvent && $scope.currentSocialEvent.attendees.length + ($scope.currentSocialEvent.attendees.length === 1 ? ' member is attending' : ' members are attending');
};
$scope.attendeeList = function () {
return _($scope.display.attendees)
.sortBy(function (attendee) {
return attendee.text;
}).map(function (attendee) {
return attendee.text;
}).join(', ');
};
function hideSocialEventDialogAndRefreshSocialEvents() {
$('#social-event-dialog').modal('hide');
refreshSocialEvents();
}
function refreshMembers() {
if (LoggedInMemberService.memberLoggedIn()) {
MemberService.allLimitedFields(MemberService.filterFor.SOCIAL_MEMBERS).then(function (members) {
$scope.members = members;
logger.debug('found', $scope.members.length, 'members');
$scope.selectMembers = _($scope.members).map(function (member) {
return {id: member.$id(), text: $filter('fullNameWithAlias')(member)};
})
});
}
}
$scope.sendSocialEventNotification = function () {
$('#social-event-dialog').modal('hide');
ModalService.showModal({
templateUrl: "partials/socialEvents/send-notification-dialog.html",
controller: "SocialEventNotificationsController",
preClose: function (modal) {
logger.debug('preClose event with modal', modal);
modal.element.modal('hide');
},
inputs: {
socialEvent: $scope.currentSocialEvent
}
}).then(function (modal) {
logger.debug('modal event with modal', modal);
modal.element.modal();
modal.close.then(function (result) {
logger.debug('close event with result', result);
});
})
};
function refreshSocialEvents() {
if (URLService.hasRouteParameter('socialEventId')) {
return SocialEventsService.getById($routeParams.socialEventId)
.then(function (socialEvent) {
if (!socialEvent) notify.error('Social event could not be found');
$scope.socialEvents = [socialEvent];
});
} else {
var socialEvents = LoggedInMemberService.allowSocialDetailView() ? SocialEventsService.all() : SocialEventsService.all({
fields: {
briefDescription: 1,
eventDate: 1,
thumbnail: 1
}
});
socialEvents.then(function (socialEvents) {
$scope.socialEvents = _.chain(socialEvents)
.filter(function (socialEvent) {
return socialEvent.eventDate >= $scope.todayValue
})
.sortBy(function (socialEvent) {
return socialEvent.eventDate;
})
.value();
logger.debug('found', $scope.socialEvents.length, 'social events');
});
}
}
$q.when(refreshSocialEvents())
.then(refreshMembers)
.then(refreshImages);
function refreshImages() {
ContentMetaDataService.getMetaData('imagesSocialEvents').then(function (contentMetaData) {
$scope.interval = 5000;
$scope.slides = contentMetaData.files;
logger.debug('found', $scope.slides.length, 'slides');
}, function (response) {
throw new Error(response);
});
}
}]);
/* concatenated from client/src/app/js/urlServices.js */
angular.module('ekwgApp')
.factory('URLService', ["$window", "$rootScope", "$timeout", "$location", "$routeParams", "$log", "PAGE_CONFIG", "ContentMetaDataService", function ($window, $rootScope, $timeout, $location, $routeParams, $log, PAGE_CONFIG, ContentMetaDataService) {
var logger = $log.getInstance('URLService');
$log.logLevels['URLService'] = $log.LEVEL.OFF;
function baseUrl(optionalUrl) {
return _.first((optionalUrl || $location.absUrl()).split('/#'));
}
function relativeUrl(optionalUrl) {
var relativeUrlValue = _.last((optionalUrl || $location.absUrl()).split("/#"));
logger.debug("relativeUrlValue:", relativeUrlValue);
return relativeUrlValue;
}
function relativeUrlFirstSegment(optionalUrl) {
var relativeUrlValue = relativeUrl(optionalUrl);
var index = relativeUrlValue.indexOf("/", 1);
var relativeUrlFirstSegment = index === -1 ? relativeUrlValue : relativeUrlValue.substring(0, index);
logger.debug("relativeUrl:", relativeUrlValue, "relativeUrlFirstSegment:", relativeUrlFirstSegment);
return relativeUrlFirstSegment;
}
function resourceUrl(area, type, id) {
return baseUrl() + '/#/' + area + '/' + type + 'Id/' + id;
}
function notificationHref(ctrl) {
var href = (ctrl.name) ? resourceUrlForAWSFileName(ctrl.name) : resourceUrl(ctrl.area, ctrl.type, ctrl.id);
logger.debug("href:", href);
return href;
}
function resourceUrlForAWSFileName(fileName) {
return baseUrl() + ContentMetaDataService.baseUrl(fileName);
}
function hasRouteParameter(parameter) {
var hasRouteParameter = !!($routeParams[parameter]);
logger.debug('hasRouteParameter', parameter, hasRouteParameter);
return hasRouteParameter;
}
function isArea(areas) {
logger.debug('isArea:areas', areas, '$routeParams', $routeParams);
return _.some(_.isArray(areas) ? areas : [areas], function (area) {
var matched = area === $routeParams.area;
logger.debug('isArea', area, 'matched =', matched);
return matched;
});
}
let pageUrl = function (page) {
var pageOrEmpty = (page ? page : "");
return s.startsWith(pageOrEmpty, "/") ? pageOrEmpty : "/" + pageOrEmpty;
};
function navigateTo(page, area) {
$timeout(function () {
var url = pageUrl(page) + (area ? "/" + area : "");
logger.info("navigating to page:", page, "area:", area, "->", url);
$location.path(url);
logger.info("$location.path is now", $location.path())
}, 1);
}
function navigateBackToLastMainPage() {
var lastPage = _.chain($rootScope.pageHistory.reverse())
.find(function (page) {
return _.contains(_.values(PAGE_CONFIG.mainPages), relativeUrlFirstSegment(page));
})
.value();
logger.info("navigateBackToLastMainPage:$rootScope.pageHistory", $rootScope.pageHistory, "lastPage->", lastPage);
navigateTo(lastPage || "/")
}
function noArea() {
return !$routeParams.area;
}
function setRoot() {
return navigateTo();
}
function area() {
return $routeParams.area;
}
return {
setRoot: setRoot,
navigateBackToLastMainPage: navigateBackToLastMainPage,
navigateTo: navigateTo,
hasRouteParameter: hasRouteParameter,
noArea: noArea,
isArea: isArea,
baseUrl: baseUrl,
area: area,
resourceUrlForAWSFileName: resourceUrlForAWSFileName,
notificationHref: notificationHref,
resourceUrl: resourceUrl,
relativeUrlFirstSegment: relativeUrlFirstSegment,
relativeUrl: relativeUrl
}
}]);
/* concatenated from client/src/app/js/walkNotifications.js */
angular.module('ekwgApp')
.controller('WalkNotificationsController', ["$log", "$scope", "WalkNotificationService", "RamblersWalksAndEventsService", function ($log, $scope, WalkNotificationService, RamblersWalksAndEventsService) {
$scope.dataAuditDelta = WalkNotificationService.dataAuditDelta($scope.walk, $scope.status);
$scope.validateWalk = RamblersWalksAndEventsService.validateWalk($scope.walk);
RamblersWalksAndEventsService.walkBaseUrl().then(function (walkBaseUrl) {
$scope.ramblersWalkBaseUrl = walkBaseUrl;
});
}])
.factory('WalkNotificationService', ["$sce", "$log", "$timeout", "$filter", "$location", "$rootScope", "$q", "$compile", "$templateRequest", "$routeParams", "$cookieStore", "URLService", "MemberService", "MailchimpConfig", "MailchimpSegmentService", "WalksReferenceService", "MemberAuditService", "RamblersWalksAndEventsService", "MailchimpCampaignService", "LoggedInMemberService", "DateUtils", function ($sce, $log, $timeout, $filter, $location, $rootScope, $q, $compile, $templateRequest, $routeParams,
$cookieStore, URLService, MemberService, MailchimpConfig, MailchimpSegmentService, WalksReferenceService,
MemberAuditService, RamblersWalksAndEventsService, MailchimpCampaignService, LoggedInMemberService, DateUtils) {
var logger = $log.getInstance('WalkNotificationService');
var noLogger = $log.getInstance('WalkNotificationServiceNoLog');
$log.logLevels['WalkNotificationService'] = $log.LEVEL.OFF;
$log.logLevels['WalkNotificationServiceNoLog'] = $log.LEVEL.OFF;
var basePartialsUrl = 'partials/walks/notifications';
var auditedFields = ['grade', 'walkDate', 'walkType', 'startTime', 'briefDescriptionAndStartPoint', 'longerDescription', 'distance', 'nearestTown', 'gridReference', 'meetupEventUrl', 'meetupEventTitle', 'osMapsRoute', 'osMapsTitle', 'postcode', 'walkLeaderMemberId', 'contactPhone', 'contactEmail', 'contactId', 'displayName', 'ramblersWalkId'];
function currentDataValues(walk) {
return _.compactObject(_.pick(walk, auditedFields));
}
function previousDataValues(walk) {
var event = latestWalkEvent(walk);
return event && event.data || {};
}
function latestWalkEvent(walk) {
return (walk.events && _.last(walk.events)) || {};
}
function eventsLatestFirst(walk) {
var events = walk.events && _(walk.events).clone().reverse() || [];
noLogger.info('eventsLatestFirst:', events);
return events;
}
function latestEventWithStatusChange(walk) {
return _(eventsLatestFirst(walk)).find(function (event) {
return (WalksReferenceService.toEventType(event.eventType) || {}).statusChange;
}) || {};
}
function dataAuditDelta(walk, status) {
if (!walk) return {};
var currentData = currentDataValues(walk);
var previousData = previousDataValues(walk);
var changedItems = calculateChangedItems();
var eventExists = latestEventWithStatusChangeIs(walk, status);
var dataChanged = changedItems.length > 0;
var dataAuditDelta = {
currentData: currentData,
previousData: previousData,
changedItems: changedItems,
eventExists: eventExists,
dataChanged: dataChanged,
notificationRequired: dataChanged || !eventExists,
eventType: dataChanged && eventExists ? WalksReferenceService.eventTypes.walkDetailsUpdated.eventType : status
};
dataAuditDelta.dataChanged && noLogger.info('dataAuditDelta', dataAuditDelta);
return dataAuditDelta;
function calculateChangedItems() {
return _.compact(_.map(auditedFields, function (key) {
var currentValue = currentData[key];
var previousValue = previousData[key];
noLogger.info('auditing', key, 'now:', currentValue, 'previous:', previousValue);
if (previousValue !== currentValue) return {
fieldName: key,
previousValue: previousValue,
currentValue: currentValue
}
}));
}
}
function latestEventWithStatusChangeIs(walk, eventType) {
if (!walk) return false;
return latestEventWithStatusChange(walk).eventType === toEventTypeValue(eventType);
}
function toEventTypeValue(eventType) {
return _.has(eventType, 'eventType') ? eventType.eventType : eventType;
}
function latestEventForEventType(walk, eventType) {
if (walk) {
var eventTypeString = toEventTypeValue(eventType);
return eventsLatestFirst(walk).find(function (event) {
return event.eventType === eventTypeString;
});
}
}
function populateWalkApprovedEventsIfRequired(walks) {
return _(walks).map(function (walk) {
if (_.isArray(walk.events)) {
return walk
} else {
var event = createEventIfRequired(walk, WalksReferenceService.eventTypes.approved.eventType, 'Marking past walk as approved');
writeEventIfRequired(walk, event);
walk.$saveOrUpdate();
return walk;
}
})
}
function createEventIfRequired(walk, status, reason) {
var dataAuditDeltaInfo = dataAuditDelta(walk, status);
logger.debug('createEventIfRequired:', dataAuditDeltaInfo);
if (dataAuditDeltaInfo.notificationRequired) {
var event = {
"date": DateUtils.nowAsValue(),
"memberId": LoggedInMemberService.loggedInMember().memberId,
"data": dataAuditDeltaInfo.currentData,
"eventType": dataAuditDeltaInfo.eventType
};
if (reason) event.reason = reason;
if (dataAuditDeltaInfo.dataChanged) event.description = 'Changed: ' + $filter('toAuditDeltaChangedItems')(dataAuditDeltaInfo.changedItems);
logger.debug('createEventIfRequired: event created:', event);
return event;
} else {
logger.debug('createEventIfRequired: event creation not necessary');
}
}
function writeEventIfRequired(walk, event) {
if (event) {
logger.debug('writing event', event);
if (!_.isArray(walk.events)) walk.events = [];
walk.events.push(event);
} else {
logger.debug('no event to write');
}
}
function createEventAndSendNotifications(members, walk, status, notify, sendNotification, reason) {
notify.setBusy();
var event = createEventIfRequired(walk, status, reason);
var notificationScope = $rootScope.$new();
notificationScope.walk = walk;
notificationScope.members = members;
notificationScope.event = event;
notificationScope.status = status;
var eventType = event && WalksReferenceService.toEventType(event.eventType);
if (event && sendNotification) {
return sendNotificationsToAllRoles()
.then(function () {
return writeEventIfRequired(walk, event);
})
.then(function () {
return true;
})
.catch(function (error) {
logger.debug('failed with error', error);
return notify.error({title: error.message, message: error.error})
});
} else {
logger.debug('Not sending notification');
return $q.when(writeEventIfRequired(walk, event))
.then(function () {
return false;
});
}
function renderTemplateContent(templateData) {
var task = $q.defer();
var templateFunction = $compile(templateData);
var templateElement = templateFunction(notificationScope);
$timeout(function () {
notificationScope.$digest();
task.resolve(templateElement.html());
});
return task.promise;
}
function sendNotificationsToAllRoles() {
return LoggedInMemberService.getMemberForMemberId(walk.walkLeaderMemberId)
.then(function (member) {
logger.debug('sendNotification:', 'memberId', walk.walkLeaderMemberId, 'member', member);
var walkLeaderName = $filter('fullNameWithAlias')(member);
var walkDate = $filter('displayDate')(walk.walkDate);
return $q.when(notify.progress('Preparing to send email notifications'))
.then(sendLeaderNotifications, notify.error, notify.progress)
.then(sendCoordinatorNotifications, notify.error, notify.progress);
function sendLeaderNotifications() {
if (eventType.notifyLeader) return sendNotificationsTo({
templateUrl: templateForEvent('leader', eventType.eventType),
memberIds: [walk.walkLeaderMemberId],
segmentType: 'walkLeader',
segmentName: MailchimpSegmentService.formatSegmentName('Walk leader notifications for ' + walkLeaderName),
emailSubject: 'Your walk on ' + walkDate,
destination: 'walk leader'
});
logger.debug('not sending leader notification');
}
function sendCoordinatorNotifications() {
if (eventType.notifyCoordinator) {
var memberIds = MemberService.allMemberIdsWithPrivilege('walkChangeNotifications', members);
if (memberIds.length > 0) {
return sendNotificationsTo({
templateUrl: templateForEvent('coordinator', eventType.eventType),
memberIds: memberIds,
segmentType: 'walkCoordinator',
segmentName: MailchimpSegmentService.formatSegmentName('Walk co-ordinator notifications for ' + walkLeaderName),
emailSubject: walkLeaderName + "'s walk on " + walkDate,
destination: 'walk co-ordinators'
});
} else {
logger.debug('not sending coordinator notifications as none are configured with walkChangeNotifications');
}
} else {
logger.debug('not sending coordinator notifications as event type is', eventType.eventType);
}
}
function templateForEvent(role, eventTypeString) {
return basePartialsUrl + '/' + role + '/' + s.dasherize(eventTypeString) + '.html';
}
function sendNotificationsTo(templateAndNotificationMembers) {
if (templateAndNotificationMembers.memberIds.length === 0) throw new Error('No members have been configured as ' + templateAndNotificationMembers.destination + ' therefore notifications cannot be sent');
var memberFullNames = $filter('memberIdsToFullNames')(templateAndNotificationMembers.memberIds, members);
logger.debug('sendNotificationsTo:', templateAndNotificationMembers);
var campaignName = templateAndNotificationMembers.emailSubject + ' (' + eventType.description + ')';
var segmentName = templateAndNotificationMembers.segmentName;
return $templateRequest($sce.getTrustedResourceUrl(templateAndNotificationMembers.templateUrl))
.then(renderTemplateContent, notify.error)
.then(populateContentSections, notify.error)
.then(sendNotification(templateAndNotificationMembers), notify.error);
function populateContentSections(walkNotificationText) {
logger.debug('populateContentSections -> walkNotificationText', walkNotificationText);
return {
sections: {
notification_text: walkNotificationText
}
};
}
function sendNotification(templateAndNotificationMembers) {
return function (contentSections) {
return createOrSaveMailchimpSegment()
.then(saveSegmentDataToMember, notify.error, notify.progress)
.then(sendEmailCampaign, notify.error, notify.progress)
.then(notifyEmailSendComplete, notify.error, notify.success);
function createOrSaveMailchimpSegment() {
return MailchimpSegmentService.saveSegment('walks', {segmentId: MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType)}, templateAndNotificationMembers.memberIds, segmentName, members);
}
function saveSegmentDataToMember(segmentResponse) {
MailchimpSegmentService.setMemberSegmentId(member, templateAndNotificationMembers.segmentType, segmentResponse.segment.id);
return LoggedInMemberService.saveMember(member);
}
function sendEmailCampaign() {
notify.progress('Sending ' + campaignName);
return MailchimpConfig.getConfig()
.then(function (config) {
var campaignId = config.mailchimp.campaigns.walkNotification.campaignId;
var segmentId = MailchimpSegmentService.getMemberSegmentId(member, templateAndNotificationMembers.segmentType);
logger.debug('about to send campaign', campaignName, 'campaign Id', campaignId, 'segmentId', segmentId);
return MailchimpCampaignService.replicateAndSendWithOptions({
campaignId: campaignId,
campaignName: campaignName,
contentSections: contentSections,
segmentId: segmentId
});
})
.then(function () {
notify.progress('Sending of ' + campaignName + ' was successful', true);
});
}
function notifyEmailSendComplete() {
notify.success('Sending of ' + campaignName + ' was successful. Check your inbox for details.');
return true;
}
}
}
}
});
}
}
return {
dataAuditDelta: dataAuditDelta,
eventsLatestFirst: eventsLatestFirst,
createEventIfRequired: createEventIfRequired,
populateWalkApprovedEventsIfRequired: populateWalkApprovedEventsIfRequired,
writeEventIfRequired: writeEventIfRequired,
latestEventWithStatusChangeIs: latestEventWithStatusChangeIs,
latestEventWithStatusChange: latestEventWithStatusChange,
createEventAndSendNotifications: createEventAndSendNotifications
}
}]);
/* concatenated from client/src/app/js/walkSlots.js.js */
angular.module('ekwgApp')
.controller('WalkSlotsController', ["$rootScope", "$log", "$scope", "$filter", "$q", "WalksService", "WalksQueryService", "WalksReferenceService", "WalkNotificationService", "LoggedInMemberService", "DateUtils", "Notifier", function ($rootScope, $log, $scope, $filter, $q, WalksService, WalksQueryService, WalksReferenceService, WalkNotificationService, LoggedInMemberService, DateUtils, Notifier) {
var logger = $log.getInstance('WalkSlotsController');
$log.logLevels['WalkSlotsController'] = $log.LEVEL.OFF;
$scope.slotsAlert = {};
$scope.todayValue = DateUtils.momentNowNoTime().valueOf();
$scope.slot = {
open: function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.slot.opened = true;
},
validDate: function (date) {
return DateUtils.isDate(date);
},
until: DateUtils.momentNowNoTime().day(7 * 12).valueOf(),
bulk: true
};
var notify = Notifier($scope.slotsAlert);
function createSlots(requiredSlots, confirmAction, prompt) {
$scope.requiredWalkSlots = requiredSlots.map(function (date) {
var walk = new WalksService({
walkDate: date
});
walk.events = [WalkNotificationService.createEventIfRequired(walk, WalksReferenceService.eventTypes.awaitingLeader.eventType, 'Walk slot created')];
return walk;
});
logger.debug('$scope.requiredWalkSlots', $scope.requiredWalkSlots);
if ($scope.requiredWalkSlots.length > 0) {
$scope.confirmAction = confirmAction;
notify.warning(prompt)
} else {
notify.error({title: "Nothing to do!", message: "All slots are already created between today and " + $filter('displayDate')($scope.slot.until)});
delete $scope.confirmAction;
}
}
$scope.addWalkSlots = function () {
WalksService.query({walkDate: {$gte: $scope.todayValue}}, {fields: {events: 1, walkDate: 1}, sort: {walkDate: 1}})
.then(function (walks) {
var sunday = DateUtils.momentNowNoTime().day(7);
var untilDate = DateUtils.asMoment($scope.slot.until).startOf('day');
var weeks = untilDate.clone().diff(sunday, 'weeks');
var allGeneratedSlots = _.times(weeks, function (index) {
return DateUtils.asValueNoTime(sunday.clone().add(index, 'week'));
}).filter(function (date) {
return DateUtils.asString(date, undefined, 'DD-MMM') !== '25-Dec';
});
var existingDates = _.pluck(WalksQueryService.activeWalks(walks), 'walkDate');
logger.debug('sunday', sunday, 'untilDate', untilDate, 'weeks', weeks);
logger.debug('existingDatesAsDates', _(existingDates).map($filter('displayDateAndTime')));
logger.debug('allGeneratedSlotsAsDates', _(allGeneratedSlots).map($filter('displayDateAndTime')));
var requiredSlots = _.difference(allGeneratedSlots, existingDates);
var requiredDates = $filter('displayDates')(requiredSlots);
createSlots(requiredSlots, {addSlots: true}, {
title: "Add walk slots",
message: " - You are about to add " + requiredSlots.length + " empty walk slots up to " + $filter('displayDate')($scope.slot.until) + '. Slots are: ' + requiredDates
});
});
};
$scope.addWalkSlot = function () {
createSlots([DateUtils.asValueNoTime($scope.slot.single)], {addSlot: true}, {
title: "Add walk slots",
message: " - You are about to add 1 empty walk slot for " + $filter('displayDate')($scope.slot.single)
});
};
$scope.selectBulk = function (bulk) {
$scope.slot.bulk = bulk;
delete $scope.confirmAction;
notify.hide();
};
$scope.allow = {
addSlot: function () {
return !$scope.confirmAction && !$scope.slot.bulk && LoggedInMemberService.allowWalkAdminEdits();
},
addSlots: function () {
return !$scope.confirmAction && $scope.slot.bulk && LoggedInMemberService.allowWalkAdminEdits();
},
close: function () {
return !$scope.confirmAction;
}
};
$scope.cancelConfirmableAction = function () {
delete $scope.confirmAction;
notify.hide();
};
$scope.confirmAddWalkSlots = function () {
notify.success({title: "Add walk slots - ", message: "now creating " + $scope.requiredWalkSlots.length + " empty walk slots up to " + $filter('displayDate')($scope.slot.until)});
$q.all($scope.requiredWalkSlots.map(function (slot) {
return slot.$saveOrUpdate();
})).then(function () {
notify.success({title: "Done!", message: "Choose Close to see your newly created slots"});
delete $scope.confirmAction;
});
};
$scope.$on('addWalkSlotsDialogOpen', function () {
$('#add-slots-dialog').modal();
delete $scope.confirmAction;
notify.hide();
});
$scope.closeWalkSlotsDialog = function () {
$('#add-slots-dialog').modal('hide');
$rootScope.$broadcast('walkSlotsCreated');
};
}]
);
/* concatenated from client/src/app/js/walks.js */
angular.module('ekwgApp')
.factory('WalksService', ["$mongolabResourceHttp", function ($mongolabResourceHttp) {
return $mongolabResourceHttp('walks')
}])
.factory('WalksQueryService', ["WalkNotificationService", "WalksReferenceService", function (WalkNotificationService, WalksReferenceService) {
function activeWalks(walks) {
return _.filter(walks, function (walk) {
return !WalkNotificationService.latestEventWithStatusChangeIs(walk, WalksReferenceService.eventTypes.deleted)
})
}
return {
activeWalks: activeWalks
}
}])
.factory('WalksReferenceService', function () {
var eventTypes = {
awaitingLeader: {
statusChange: true,
eventType: 'awaitingLeader',
description: 'Awaiting walk leader'
},
awaitingWalkDetails: {
mustHaveLeader: true,
statusChange: true,
eventType: 'awaitingWalkDetails',
description: 'Awaiting walk details from leader',
notifyLeader: true,
notifyCoordinator: true
},
walkDetailsRequested: {
mustHaveLeader: true,
eventType: 'walkDetailsRequested',
description: 'Walk details requested from leader',
notifyLeader: true,
notifyCoordinator: true
},
walkDetailsUpdated: {
eventType: 'walkDetailsUpdated',
description: 'Walk details updated',
notifyLeader: true,
notifyCoordinator: true
},
walkDetailsCopied: {
eventType: 'walkDetailsCopied',
description: 'Walk details copied'
},
awaitingApproval: {
mustHaveLeader: true,
mustPassValidation: true,
statusChange: true,
eventType: 'awaitingApproval',
readyToBe: 'approved',
description: 'Awaiting confirmation of walk details',
notifyLeader: true,
notifyCoordinator: true
},
approved: {
mustHaveLeader: true,
mustPassValidation: true,
showDetails: true,
statusChange: true,
eventType: 'approved',
readyToBe: 'published',
description: 'Approved',
notifyLeader: true,
notifyCoordinator: true
},
deleted: {
statusChange: true,
eventType: 'deleted',
description: 'Deleted',
notifyLeader: true,
notifyCoordinator: true
}
};
return {
toEventType: function (eventTypeString) {
if (eventTypeString) {
if (_.includes(eventTypeString, ' ')) eventTypeString = s.camelcase(eventTypeString.toLowerCase());
var eventType = eventTypes[eventTypeString];
if (!eventType) throw new Error("Event Type '" + eventTypeString + "' does not exist. Must be one of: " + _.keys(eventTypes).join(', '));
return eventType;
}
},
walkEditModes: {
add: {caption: 'add', title: 'Add new'},
edit: {caption: 'edit', title: 'Edit existing', editEnabled: true},
more: {caption: 'more', title: 'View'},
lead: {caption: 'lead', title: 'Lead this', initialiseWalkLeader: true}
},
eventTypes: eventTypes,
walkStatuses: _(eventTypes).filter(function (eventType) {
return eventType.statusChange;
})
}
})
.controller('WalksController', ["$sce", "$log", "$routeParams", "$interval", "$rootScope", "$location", "$scope", "$filter", "$q", "RamblersUploadAudit", "WalksService", "WalksQueryService", "URLService", "ClipboardService", "WalksReferenceService", "WalkNotificationService", "LoggedInMemberService", "MemberService", "DateUtils", "BatchGeoExportService", "RamblersWalksAndEventsService", "Notifier", "CommitteeReferenceData", "GoogleMapsConfig", "MeetupService", function ($sce, $log, $routeParams, $interval, $rootScope, $location, $scope, $filter, $q, RamblersUploadAudit, WalksService, WalksQueryService, URLService,
ClipboardService, WalksReferenceService, WalkNotificationService, LoggedInMemberService, MemberService, DateUtils, BatchGeoExportService,
RamblersWalksAndEventsService, Notifier, CommitteeReferenceData, GoogleMapsConfig, MeetupService) {
var logger = $log.getInstance('WalksController');
var noLogger = $log.getInstance('WalksControllerNoLogger');
$log.logLevels['WalksControllerNoLogger'] = $log.LEVEL.OFF;
$log.logLevels['WalksController'] = $log.LEVEL.OFF;
$scope.contactUs = {
ready: function () {
return CommitteeReferenceData.ready;
}
};
$scope.$watch('filterParameters.quickSearch', function (quickSearch, oldQuery) {
refreshFilteredWalks();
});
$scope.finalStatusError = function () {
return _.findWhere($scope.ramblersUploadAudit, {status: "error"});
};
$scope.fileNameChanged = function () {
logger.debug('filename changed to', $scope.userEdits.fileName);
$scope.refreshRamblersUploadAudit();
};
$scope.refreshRamblersUploadAudit = function (stop) {
logger.debug('refreshing audit trail records related to', $scope.userEdits.fileName);
return RamblersUploadAudit.query({fileName: $scope.userEdits.fileName}, {sort: {auditTime: -1}})
.then(function (auditItems) {
logger.debug('Filtering', auditItems.length, 'audit trail records related to', $scope.userEdits.fileName);
$scope.ramblersUploadAudit = _.chain(auditItems)
.filter(function (auditItem) {
return $scope.userEdits.showDetail || auditItem.type !== "detail";
})
.map(function (auditItem) {
if (auditItem.status === "complete") {
logger.debug('Upload complete');
notifyWalkExport.success("Ramblers upload completed");
$interval.cancel(stop);
$scope.userEdits.saveInProgress = false;
}
return auditItem;
})
.value();
});
};
$scope.ramblersUploadAudit = [];
$scope.walksForExport = [];
$scope.walkEditModes = WalksReferenceService.walkEditModes;
$scope.walkStatuses = WalksReferenceService.walkStatuses;
$scope.walkAlert = {};
$scope.walkExport = {};
var notify = Notifier($scope);
var notifyWalkExport = Notifier($scope.walkExport);
var notifyWalkEdit = Notifier($scope.walkAlert);
var SHOW_START_POINT = "show-start-point";
var SHOW_DRIVING_DIRECTIONS = "show-driving-directions";
notify.setBusy();
$scope.copyFrom = {walkTemplates: [], walkTemplate: {}};
$scope.userEdits = {
copyToClipboard: ClipboardService.copyToClipboard,
meetupEvent: {},
copySource: 'copy-selected-walk-leader',
copySourceFromWalkLeaderMemberId: undefined,
expandedWalks: [],
mapDisplay: SHOW_START_POINT,
longerDescriptionPreview: true,
walkExportActive: function (activeTab) {
return activeTab === $scope.walkExportActive;
},
walkExportTab0Active: true,
walkExportTab1Active: false,
walkExportTabActive: 0,
status: undefined,
sendNotifications: true,
saveInProgress: false,
fileNames: [],
walkLink: function (walk) {
return walk && walk.$id() ? URLService.notificationHref({
type: "walk",
area: "walks",
id: walk.$id()
}) : undefined
}
};
$scope.walks = [];
$scope.busy = false;
$scope.walksProgrammeOpen = URLService.isArea('programme', 'walkId') || URLService.noArea();
$scope.walksInformationOpen = URLService.isArea('information');
$scope.walksMapViewOpen = URLService.isArea('mapview');
$scope.todayValue = DateUtils.momentNowNoTime().valueOf();
$scope.userEdits.walkDateCalendar = {
open: function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.userEdits.walkDateCalendar.opened = true;
}
};
$scope.addWalk = function () {
showWalkDialog(new WalksService({
status: WalksReferenceService.eventTypes.awaitingLeader.eventType,
walkType: $scope.type[0],
walkDate: $scope.todayValue
}), WalksReferenceService.walkEditModes.add);
};
$scope.addWalkSlotsDialog = function () {
$rootScope.$broadcast('addWalkSlotsDialogOpen');
};
$scope.unlinkRamblersDataFromCurrentWalk = function () {
delete $scope.currentWalk.ramblersWalkId;
notify.progress('Previous Ramblers walk has now been unlinked.')
};
$scope.canUnlinkRamblers = function () {
return LoggedInMemberService.allowWalkAdminEdits() && $scope.ramblersWalkExists();
};
$scope.notUploadedToRamblersYet = function () {
return !$scope.ramblersWalkExists();
};
$scope.insufficientDataToUploadToRamblers = function () {
return LoggedInMemberService.allowWalkAdminEdits() && $scope.currentWalk && !($scope.currentWalk.gridReference || $scope.currentWalk.postcode);
};
$scope.canExportToRamblers = function () {
return LoggedInMemberService.allowWalkAdminEdits() && $scope.validateWalk().selected;
};
$scope.validateWalk = function () {
return RamblersWalksAndEventsService.validateWalk($scope.currentWalk, $scope.members);
};
$scope.walkValidations = function () {
var walkValidations = $scope.validateWalk().walkValidations;
return 'This walk cannot be included in the Ramblers Walks and Events Manager export due to the following ' + walkValidations.length + ' problem(s): ' + walkValidations.join(", ") + '.';
};
$scope.grades = ['Easy access', 'Easy', 'Leisurely', 'Moderate', 'Strenuous', 'Technical'];
$scope.walkTypes = ['Circular', 'Linear'];
$scope.meetupEventUrlChange = function (walk) {
walk.meetupEventTitle = $scope.userEdits.meetupEvent.title;
walk.meetupEventUrl = $scope.userEdits.meetupEvent.url;
};
$scope.meetupSelectSync = function (walk) {
$scope.userEdits.meetupEvent = _.findWhere($scope.meetupEvents, {url: walk.meetupEventUrl});
};
$scope.ramblersWalkExists = function () {
return $scope.validateWalk().publishedOnRamblers
};
function loggedInMemberIsLeadingWalk(walk) {
return walk && walk.walkLeaderMemberId === LoggedInMemberService.loggedInMember().memberId
}
$scope.loggedIn = function () {
return LoggedInMemberService.memberLoggedIn();
};
$scope.toWalkEditMode = function (walk) {
if (LoggedInMemberService.memberLoggedIn()) {
if (loggedInMemberIsLeadingWalk(walk) || LoggedInMemberService.allowWalkAdminEdits()) {
return WalksReferenceService.walkEditModes.edit;
} else if (!walk.walkLeaderMemberId) {
return WalksReferenceService.walkEditModes.lead;
}
}
};
$scope.actionWalk = function (walk) {
showWalkDialog(walk, $scope.toWalkEditMode(walk));
};
$scope.deleteWalkDetails = function () {
$scope.confirmAction = {delete: true};
notifyWalkEdit.warning({
title: 'Confirm delete of walk details.',
message: 'If you confirm this, the slot for ' + $filter('displayDate')($scope.currentWalk.walkDate) + ' will be deleted from the site.'
});
};
$scope.cancelWalkDetails = function () {
$scope.confirmAction = {cancel: true};
notifyWalkEdit.warning({
title: 'Cancel changes.',
message: 'Click Confirm to lose any changes you\'ve just made for ' + $filter('displayDate')($scope.currentWalk.walkDate) + ', or Cancel to carry on editing.'
});
};
$scope.confirmCancelWalkDetails = function () {
hideWalkDialogAndRefreshWalks();
};
function isWalkReadyForStatusChangeTo(eventType) {
notifyWalkEdit.hide();
logger.info('isWalkReadyForStatusChangeTo ->', eventType);
var walkValidations = $scope.validateWalk().walkValidations;
if (eventType.mustHaveLeader && !$scope.currentWalk.walkLeaderMemberId) {
notifyWalkEdit.warning(
{
title: 'Walk leader needed',
message: ' - this walk cannot be changed to ' + eventType.description + ' yet.'
});
revertToPriorWalkStatus();
return false;
} else if (eventType.mustPassValidation && walkValidations.length > 0) {
notifyWalkEdit.warning(
{
title: 'This walk is not ready to be ' + eventType.readyToBe + ' yet due to the following ' + walkValidations.length + ' problem(s): ',
message: walkValidations.join(", ") + '. You can still save this walk, then come back later on to complete the rest of the details.'
});
revertToPriorWalkStatus();
return false;
} else {
return true;
}
}
function initiateEvent() {
$scope.userEdits.saveInProgress = true;
var walk = DateUtils.convertDateFieldInObject($scope.currentWalk, 'walkDate');
return WalkNotificationService.createEventAndSendNotifications($scope.members, walk, $scope.userEdits.status, notifyWalkEdit, $scope.userEdits.sendNotifications && walk.walkLeaderMemberId);
}
$scope.confirmDeleteWalkDetails = function () {
$scope.userEdits.status = WalksReferenceService.eventTypes.deleted.eventType;
return initiateEvent()
.then(function () {
return $scope.currentWalk.$saveOrUpdate(hideWalkDialogAndRefreshWalks, hideWalkDialogAndRefreshWalks);
})
.catch(function () {
$scope.userEdits.saveInProgress = false;
});
};
$scope.saveWalkDetails = function () {
return initiateEvent()
.then(function (notificationSent) {
return $scope.currentWalk.$saveOrUpdate(afterSaveWith(notificationSent), afterSaveWith(notificationSent));
})
.catch(function () {
$scope.userEdits.saveInProgress = false;
});
};
$scope.requestApproval = function () {
logger.info('requestApproval called with current status:', $scope.userEdits.status);
if (isWalkReadyForStatusChangeTo(WalksReferenceService.eventTypes.awaitingApproval)) {
$scope.confirmAction = {requestApproval: true};
notifyWalkEdit.warning({
title: 'Confirm walk details complete.',
message: 'If you confirm this, your walk details will be emailed to ' + walksCoordinatorName() + ' and they will publish these to the site.'
});
}
};
$scope.contactOther = function () {
notifyWalkEdit.warning({
title: 'Confirm walk details complete.',
message: 'If you confirm this, your walk details will be emailed to ' + walksCoordinatorName() + ' and they will publish these to the site.'
});
};
$scope.walkStatusChange = function (status) {
$scope.userEdits.priorStatus = status;
notifyWalkEdit.hide();
logger.info('walkStatusChange - was:', status, 'now:', $scope.userEdits.status);
if (isWalkReadyForStatusChangeTo(WalksReferenceService.toEventType($scope.userEdits.status)))
switch ($scope.userEdits.status) {
case WalksReferenceService.eventTypes.awaitingLeader.eventType: {
var walkDate = $scope.currentWalk.walkDate;
$scope.userEdits.status = WalksReferenceService.eventTypes.awaitingLeader.eventType;
$scope.currentWalk = new WalksService(_.pick($scope.currentWalk, ['_id', 'events', 'walkDate']));
return notifyWalkEdit.success({
title: 'Walk details reset for ' + $filter('displayDate')(walkDate) + '.',
message: 'Status is now ' + WalksReferenceService.eventTypes.awaitingLeader.description
});
}
case WalksReferenceService.eventTypes.approved.eventType: {
return $scope.approveWalkDetails();
}
}
};
$scope.approveWalkDetails = function () {
var walkValidations = $scope.validateWalk().walkValidations;
if (walkValidations.length > 0) {
notifyWalkEdit.warning({
title: 'This walk still has the following ' + walkValidations.length + ' field(s) that need attention: ',
message: walkValidations.join(", ") +
'. You\'ll have to get the rest of these details completed before you mark the walk as approved.'
});
revertToPriorWalkStatus();
} else {
notifyWalkEdit.success({
title: 'Ready to publish walk details!',
message: 'All fields appear to be filled in okay, so next time you save this walk it will be published.'
});
}
};
$scope.confirmRequestApproval = function () {
$scope.userEdits.status = WalksReferenceService.eventTypes.awaitingApproval.eventType;
$scope.saveWalkDetails();
};
$scope.cancelConfirmableAction = function () {
delete $scope.confirmAction;
notify.hide();
notifyWalkEdit.hide();
};
function revertToPriorWalkStatus() {
logger.info('revertToPriorWalkStatus:', $scope.userEdits.status, '->', $scope.userEdits.priorStatus);
if ($scope.userEdits.priorStatus) $scope.userEdits.status = $scope.userEdits.priorStatus;
}
$scope.populateCurrentWalkFromTemplate = function () {
var walkTemplate = _.clone($scope.copyFrom.walkTemplate);
if (walkTemplate) {
var templateDate = $filter('displayDate')(walkTemplate.walkDate);
delete walkTemplate._id;
delete walkTemplate.events;
delete walkTemplate.ramblersWalkId;
delete walkTemplate.walkDate;
delete walkTemplate.displayName;
delete walkTemplate.contactPhone;
delete walkTemplate.contactEmail;
angular.extend($scope.currentWalk, walkTemplate);
var event = WalkNotificationService.createEventIfRequired($scope.currentWalk, WalksReferenceService.eventTypes.walkDetailsCopied.eventType, 'Copied from previous walk on ' + templateDate);
WalkNotificationService.writeEventIfRequired($scope.currentWalk, event);
notifyWalkEdit.success({
title: 'Walk details were copied from ' + templateDate + '.',
message: 'Make any further changes here and save when you are done.'
});
}
};
$scope.filterParameters = {
quickSearch: '',
selectType: '1',
ascending: "true"
};
$scope.selectCopySelectedLeader = function () {
$scope.userEdits.copySource = 'copy-selected-walk-leader';
$scope.populateWalkTemplates();
};
$scope.populateWalkTemplates = function (injectedMemberId) {
var memberId = $scope.currentWalk.walkLeaderMemberId || injectedMemberId;
var criteria;
switch ($scope.userEdits.copySource) {
case "copy-selected-walk-leader": {
criteria = {
walkLeaderMemberId: $scope.userEdits.copySourceFromWalkLeaderMemberId,
briefDescriptionAndStartPoint: {$exists: true}
};
break
}
case "copy-with-os-maps-route-selected": {
criteria = {osMapsRoute: {$exists: true}};
break
}
default: {
criteria = {walkLeaderMemberId: memberId};
}
}
logger.info('selecting walks', $scope.userEdits.copySource, criteria);
WalksService.query(criteria, {sort: {walkDate: -1}})
.then(function (walks) {
$scope.copyFrom.walkTemplates = walks;
});
};
$scope.walkLeaderMemberIdChanged = function () {
notifyWalkEdit.hide();
var walk = $scope.currentWalk;
var memberId = walk.walkLeaderMemberId;
if (!memberId) {
$scope.userEdits.status = WalksReferenceService.eventTypes.awaitingLeader.eventType;
delete walk.walkLeaderMemberId;
delete walk.contactId;
delete walk.displayName;
delete walk.contactPhone;
delete walk.contactEmail;
} else {
var selectedMember = _.find($scope.members, function (member) {
return member.$id() === memberId;
});
if (selectedMember) {
$scope.userEdits.status = WalksReferenceService.eventTypes.awaitingWalkDetails.eventType;
walk.contactId = selectedMember.contactId;
walk.displayName = selectedMember.displayName;
walk.contactPhone = selectedMember.mobileNumber;
walk.contactEmail = selectedMember.email;
$scope.populateWalkTemplates(memberId);
}
}
};
$scope.myOrWalkLeader = function () {
return loggedInMemberIsLeadingWalk($scope.currentWalk) ? 'my' : $scope.currentWalk && $scope.currentWalk.displayName + "'s";
};
$scope.meOrWalkLeader = function () {
return loggedInMemberIsLeadingWalk($scope.currentWalk) ? 'me' : $scope.currentWalk && $scope.currentWalk.displayName;
};
$scope.personToNotify = function () {
return loggedInMemberIsLeadingWalk($scope.currentWalk) ? walksCoordinatorName() : $scope.currentWalk && $scope.currentWalk.displayName;
};
function walksCoordinatorName() {
return CommitteeReferenceData.contactUsField('walks', 'fullName');
}
function convertWalkDateIfNotNumeric(walk) {
var walkDate = DateUtils.asValueNoTime(walk.walkDate);
if (walkDate !== walk.walkDate) {
logger.info('Converting date from', walk.walkDate, '(' + $filter('displayDateAndTime')(walk.walkDate) + ') to', walkDate, '(' + $filter('displayDateAndTime')(walkDate) + ')');
walk.walkDate = walkDate;
} else {
logger.info('Walk date', walk.walkDate, 'is already in correct format');
}
return walk;
}
function latestEventWithStatusChangeIs(eventType) {
return WalkNotificationService.latestEventWithStatusChangeIs($scope.currentWalk, eventType);
}
$scope.dataHasChanged = function () {
var dataAuditDelta = WalkNotificationService.dataAuditDelta($scope.currentWalk, $scope.userEdits.status);
var notificationRequired = dataAuditDelta.notificationRequired;
dataAuditDelta.notificationRequired && noLogger.info('dataAuditDelta - eventExists:', dataAuditDelta.eventExists, 'dataChanged:', dataAuditDelta.dataChanged, $filter('toAuditDeltaChangedItems')(dataAuditDelta.changedItems));
dataAuditDelta.dataChanged && noLogger.info('dataAuditDelta - previousData:', dataAuditDelta.previousData, 'currentData:', dataAuditDelta.currentData);
return notificationRequired;
};
function ownedAndAwaitingWalkDetails() {
return loggedInMemberIsLeadingWalk($scope.currentWalk) && $scope.userEdits.status === WalksReferenceService.eventTypes.awaitingWalkDetails.eventType;
}
function editable() {
return !$scope.confirmAction && (LoggedInMemberService.allowWalkAdminEdits() || loggedInMemberIsLeadingWalk($scope.currentWalk));
}
function allowSave() {
return editable() && $scope.dataHasChanged();
}
$scope.allow = {
close: function () {
return !$scope.userEdits.saveInProgress && !$scope.confirmAction && !allowSave()
},
save: allowSave,
cancel: function () {
return !$scope.userEdits.saveInProgress && editable() && $scope.dataHasChanged();
},
delete: function () {
return !$scope.confirmAction && LoggedInMemberService.allowWalkAdminEdits() && $scope.walkEditMode && $scope.walkEditMode.editEnabled;
},
notifyConfirmation: function () {
return (allowSave() || $scope.confirmAction && $scope.confirmAction.delete) && $scope.currentWalk.walkLeaderMemberId;
},
adminEdits: function () {
return LoggedInMemberService.allowWalkAdminEdits();
},
edits: editable,
historyView: function () {
return loggedInMemberIsLeadingWalk($scope.currentWalk) || LoggedInMemberService.allowWalkAdminEdits();
},
detailView: function () {
return LoggedInMemberService.memberLoggedIn();
},
approve: function () {
return !$scope.confirmAction && LoggedInMemberService.allowWalkAdminEdits() && latestEventWithStatusChangeIs(WalksReferenceService.eventTypes.awaitingApproval);
},
requestApproval: function () {
return !$scope.confirmAction && ownedAndAwaitingWalkDetails();
}
};
$scope.previewLongerDescription = function () {
logger.debug('previewLongerDescription');
$scope.userEdits.longerDescriptionPreview = true;
};
$scope.editLongerDescription = function () {
logger.debug('editLongerDescription');
$scope.userEdits.longerDescriptionPreview = false;
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
$scope.showAllWalks = function () {
$scope.expensesOpen = true;
$location.path('/walks/programme')
};
$scope.googleMaps = function (walk) {
return $scope.userEdits.mapDisplay === SHOW_DRIVING_DIRECTIONS ?
"https://www.google.com/maps/embed/v1/directions?origin=" + $scope.userEdits.fromPostcode + "&destination=" + walk.postcode + "&key=" + $scope.googleMapsConfig.apiKey :
"https://www.google.com/maps/embed/v1/place?q=" + walk.postcode + "&zoom=" + $scope.googleMapsConfig.zoomLevel + "&key=" + $scope.googleMapsConfig.apiKey;
};
$scope.autoSelectMapDisplay = function () {
var switchToShowStartPoint = $scope.drivingDirectionsDisabled() && $scope.userEdits.mapDisplay === SHOW_DRIVING_DIRECTIONS;
var switchToShowDrivingDirections = !$scope.drivingDirectionsDisabled() && $scope.userEdits.mapDisplay === SHOW_START_POINT;
if (switchToShowStartPoint) {
$scope.userEdits.mapDisplay = SHOW_START_POINT;
} else if (switchToShowDrivingDirections) {
$scope.userEdits.mapDisplay = SHOW_DRIVING_DIRECTIONS;
}
};
$scope.drivingDirectionsDisabled = function () {
return $scope.userEdits.fromPostcode.length < 3;
};
$scope.eventTypeFor = function (walk) {
var latestEventWithStatusChange = WalkNotificationService.latestEventWithStatusChange(walk);
var eventType = WalksReferenceService.toEventType(latestEventWithStatusChange.eventType) || walk.status || WalksReferenceService.eventTypes.awaitingWalkDetails.eventType;
noLogger.info('latestEventWithStatusChange', latestEventWithStatusChange, 'eventType', eventType, 'walk.events', walk.events);
return eventType;
};
$scope.viewWalkField = function (walk, field) {
var eventType = $scope.eventTypeFor(walk);
if (eventType.showDetails) {
return walk[field] || '';
} else if (field === 'briefDescriptionAndStartPoint') {
return eventType.description;
} else {
return '';
}
};
function showWalkDialog(walk, walkEditMode) {
delete $scope.confirmAction;
$scope.userEdits.sendNotifications = true;
$scope.walkEditMode = walkEditMode;
$scope.currentWalk = walk;
if (walkEditMode.initialiseWalkLeader) {
$scope.userEdits.status = WalksReferenceService.eventTypes.awaitingWalkDetails.eventType;
walk.walkLeaderMemberId = LoggedInMemberService.loggedInMember().memberId;
$scope.walkLeaderMemberIdChanged();
notifyWalkEdit.success({
title: 'Thanks for offering to lead this walk ' + LoggedInMemberService.loggedInMember().firstName + '!',
message: 'Please complete as many details you can, then save to allocate this slot on the walks programme. ' +
'It will be published to the public once it\'s approved. If you want to release this slot again, just click cancel.'
});
} else {
var eventTypeIfExists = WalkNotificationService.latestEventWithStatusChange($scope.currentWalk).eventType;
if (eventTypeIfExists) {
$scope.userEdits.status = eventTypeIfExists
}
$scope.userEdits.copySourceFromWalkLeaderMemberId = walk.walkLeaderMemberId || LoggedInMemberService.loggedInMember().memberId;
$scope.populateWalkTemplates();
$scope.meetupSelectSync($scope.currentWalk);
notifyWalkEdit.hide();
}
$('#walk-dialog').modal();
}
function walksCriteriaObject() {
switch ($scope.filterParameters.selectType) {
case '1':
return {walkDate: {$gte: $scope.todayValue}};
case '2':
return {walkDate: {$lt: $scope.todayValue}};
case '3':
return {};
case '4':
return {displayName: {$exists: false}};
case '5':
return {briefDescriptionAndStartPoint: {$exists: false}};
}
}
function walksSortObject() {
switch ($scope.filterParameters.ascending) {
case 'true':
return {sort: {walkDate: 1}};
case 'false':
return {sort: {walkDate: -1}};
}
}
function query() {
if (URLService.hasRouteParameter('walkId')) {
return WalksService.getById($routeParams.walkId)
.then(function (walk) {
if (!walk) notify.error('Walk could not be found. Try opening again from the link in the notification email, or choose the Show All Walks button');
return [walk];
});
} else {
return WalksService.query(walksCriteriaObject(), walksSortObject());
}
}
function refreshFilteredWalks() {
notify.setBusy();
$scope.filteredWalks = $filter('filter')($scope.walks, $scope.filterParameters.quickSearch);
var walksCount = ($scope.filteredWalks && $scope.filteredWalks.length) || 0;
notify.progress('Showing ' + walksCount + ' walk(s)');
if ($scope.filteredWalks.length > 0) {
$scope.userEdits.expandedWalks = [$scope.filteredWalks[0].$id()];
}
notify.clearBusy();
}
$scope.showTableHeader = function (walk) {
return $scope.filteredWalks.indexOf(walk) === 0 || $scope.isExpandedFor($scope.filteredWalks[$scope.filteredWalks.indexOf(walk) - 1]);
};
$scope.nextWalk = function (walk) {
return walk && walk.$id() === $scope.nextWalkId;
};
$scope.durationInFutureFor = function (walk) {
return walk && walk.walkDate === $scope.todayValue ? 'today' : (DateUtils.asMoment(walk.walkDate).fromNow());
};
$scope.toggleViewFor = function (walk) {
function arrayRemove(arr, value) {
return arr.filter(function (ele) {
return ele !== value;
});
}
var walkId = walk.$id();
if (_.contains($scope.userEdits.expandedWalks, walkId)) {
$scope.userEdits.expandedWalks = arrayRemove($scope.userEdits.expandedWalks, walkId);
logger.debug('toggleViewFor:', walkId, '-> collapsing');
} else {
$scope.userEdits.expandedWalks.push(walkId);
logger.debug('toggleViewFor:', walkId, '-> expanding');
}
logger.debug('toggleViewFor:', walkId, '-> expandedWalks contains', $scope.userEdits.expandedWalks)
};
$scope.isExpandedFor = function (walk) {
return _.contains($scope.userEdits.expandedWalks, walk.$id());
};
$scope.tableRowOdd = function (walk) {
return $scope.filteredWalks.indexOf(walk) % 2 === 0;
};
function getNextWalkId(walks) {
var nextWalk = _.chain(walks).sortBy('walkDate').find(function (walk) {
return walk.walkDate >= $scope.todayValue;
}).value();
return nextWalk && nextWalk.$id();
}
$scope.refreshWalks = function (notificationSent) {
notify.setBusy();
notify.progress('Refreshing walks...');
return query()
.then(function (walks) {
$scope.nextWalkId = URLService.hasRouteParameter('walkId') ? undefined : getNextWalkId(walks);
$scope.walks = URLService.hasRouteParameter('walkId') ? walks : WalksQueryService.activeWalks(walks);
refreshFilteredWalks();
notify.clearBusy();
if (!notificationSent) {
notifyWalkEdit.hide();
}
$scope.userEdits.saveInProgress = false;
});
};
$scope.hideWalkDialog = function () {
$('#walk-dialog').modal('hide');
delete $scope.confirmAction;
};
function hideWalkDialogAndRefreshWalks() {
logger.info('hideWalkDialogAndRefreshWalks');
$scope.hideWalkDialog();
$scope.refreshWalks();
}
function afterSaveWith(notificationSent) {
return function () {
if (!notificationSent) $('#walk-dialog').modal('hide');
notifyWalkEdit.clearBusy();
delete $scope.confirmAction;
$scope.refreshWalks(notificationSent);
$scope.userEdits.saveInProgress = false;
}
}
function refreshRamblersConfig() {
RamblersWalksAndEventsService.walkBaseUrl().then(function (walkBaseUrl) {
$scope.ramblersWalkBaseUrl = walkBaseUrl;
});
}
function refreshGoogleMapsConfig() {
GoogleMapsConfig.getConfig().then(function (googleMapsConfig) {
$scope.googleMapsConfig = googleMapsConfig;
$scope.googleMapsConfig.zoomLevel = 12;
});
}
function refreshMeetupData() {
MeetupService.config().then(function (meetupConfig) {
$scope.meetupConfig = meetupConfig;
});
MeetupService.eventsForStatus('past')
.then(function (pastEvents) {
MeetupService.eventsForStatus('upcoming')
.then(function (futureEvents) {
$scope.meetupEvents = _.sortBy(pastEvents.concat(futureEvents), 'date,').reverse();
});
})
}
function refreshHomePostcode() {
$scope.userEdits.fromPostcode = LoggedInMemberService.memberLoggedIn() ? LoggedInMemberService.loggedInMember().postcode : "";
logger.debug('set from postcode to', $scope.userEdits.fromPostcode);
$scope.autoSelectMapDisplay();
}
$scope.$on('memberLoginComplete', function () {
refreshMembers();
refreshHomePostcode();
});
$scope.$on('walkSlotsCreated', function () {
$scope.refreshWalks();
});
function refreshMembers() {
if (LoggedInMemberService.memberLoggedIn()) MemberService.allLimitedFields(MemberService.filterFor.GROUP_MEMBERS)
.then(function (members) {
$scope.members = members;
return members;
});
}
$scope.batchGeoDownloadFile = function () {
return BatchGeoExportService.exportWalks($scope.walks, $scope.members);
};
$scope.batchGeoDownloadFileName = function () {
return BatchGeoExportService.exportWalksFileName();
};
$scope.batchGeoDownloadHeader = function () {
return BatchGeoExportService.exportColumnHeadings();
};
$scope.exportableWalks = function () {
return RamblersWalksAndEventsService.exportableWalks($scope.walksForExport);
};
$scope.walksDownloadFile = function () {
return RamblersWalksAndEventsService.exportWalks($scope.exportableWalks(), $scope.members);
};
$scope.uploadToRamblers = function () {
$scope.ramblersUploadAudit = [];
$scope.userEdits.walkExportTab0Active = false;
$scope.userEdits.walkExportTab1Active = true;
$scope.userEdits.saveInProgress = true;
RamblersWalksAndEventsService.uploadToRamblers($scope.walksForExport, $scope.members, notifyWalkExport).then(function (fileName) {
$scope.userEdits.fileName = fileName;
var stop = $interval(callAtInterval, 2000, false);
if (!_.contains($scope.userEdits.fileNames, $scope.userEdits.fileName)) {
$scope.userEdits.fileNames.push($scope.userEdits.fileName);
logger.debug('added', $scope.userEdits.fileName, 'to filenames of', $scope.userEdits.fileNames.length, 'audit trail records');
}
delete $scope.finalStatusError;
function callAtInterval() {
logger.debug("Refreshing audit trail for file", $scope.userEdits.fileName, 'count =', $scope.ramblersUploadAudit.length);
$scope.refreshRamblersUploadAudit(stop);
}
});
};
$scope.walksDownloadFileName = function () {
return RamblersWalksAndEventsService.exportWalksFileName();
};
$scope.walksDownloadHeader = function () {
return RamblersWalksAndEventsService.exportColumnHeadings();
};
$scope.selectWalksForExport = function () {
showWalkExportDialog();
};
$scope.changeWalkExportSelection = function (walk) {
if (walk.walkValidations.length === 0) {
walk.selected = !walk.selected;
notifyWalkExport.hide();
} else {
notifyWalkExport.error({
title: 'You can\'t export the walk for ' + $filter('displayDate')(walk.walk.walkDate),
message: walk.walkValidations.join(', ')
});
}
};
$scope.cancelExportWalkDetails = function () {
$('#walk-export-dialog').modal('hide');
};
function populateWalkExport(walksForExport) {
$scope.walksForExport = walksForExport;
notifyWalkExport.success('Found total of ' + $scope.walksForExport.length + ' walk(s), ' + $scope.walksDownloadFile().length + ' preselected for export');
notifyWalkExport.clearBusy();
}
function showWalkExportDialog() {
$scope.walksForExport = [];
notifyWalkExport.warning('Determining which walks to export', true);
RamblersUploadAudit.all({limit: 1000, sort: {auditTime: -1}})
.then(function (auditItems) {
logger.debug('found total of', auditItems.length, 'audit trail records');
$scope.userEdits.fileNames = _.chain(auditItems).pluck('fileName').unique().value();
logger.debug('unique total of', $scope.userEdits.fileNames.length, 'audit trail records');
});
RamblersWalksAndEventsService.createWalksForExportPrompt($scope.walks, $scope.members)
.then(populateWalkExport)
.catch(function (error) {
logger.debug('error->', error);
notifyWalkExport.error({title: 'Problem with Ramblers export preparation', message: JSON.stringify(error)});
});
$('#walk-export-dialog').modal();
}
refreshMembers();
$scope.refreshWalks();
refreshRamblersConfig();
refreshGoogleMapsConfig();
refreshMeetupData();
refreshHomePostcode();
}]
)
;
| nbarrett/ekwg | dist/app/js/ekwg.js | JavaScript | mit | 405,222 |
angular.module('MEANcraftApp', ['ngRoute', 'MEANcraftApp.login', 'MEANcraftApp.overview', 'btford.socket-io'/*,'socket-io', 'flow'*/])
.config(function ($httpProvider, $routeProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
$routeProvider
.when('/login', {
templateUrl: 'app/login/login',
controller: 'loginCtrl',
protect: false
})
.when('/overview', {
templateUrl: 'app/overview/overview',
//controller: 'overviewCtrl',
protect: true,
resolve: {
initialData: function (ServerSocket, FetchData, $q) {
return $q(function (resolve, reject) {
ServerSocket.emit('info');
ServerSocket.once('info', function (data) {
console.log(data);
FetchData = angular.extend(FetchData, data);
resolve();
});
});
}
}
})
.otherwise({
redirectTo: '/overview'
});
})
.run(function ($rootScope, $location, $window, $routeParams, UserAuth) {
if (!UserAuth.isLogged) {
$location.path('/login');
}
$rootScope.$on('$routeChangeStart', function (event, nextRoute, prevRoute) {
console.groupCollapsed('%cAPP.RUN -> ROUTE CHANGE START', 'background: #222; color: #bada55;');
console.log('%cTOKEN -> %c' + $window.sessionStorage.token, 'font-weight: bold', '');
console.log('%cLOGGIN STATUS -> %c' + UserAuth.isLogged, 'font-weight: bold', UserAuth.isLogged ? 'color: green;' : 'color: red;');
console.groupEnd('APP.RUN -> ROUTE CHANGE START');
if (nextRoute.protect && UserAuth.isLogged === false && !$window.sessionStorage.token) {
$location.path('/login');
console.error('Route protected, user not logged in');
} else if (!nextRoute.protect && UserAuth.isLogged) {
$location.path('/overview');
}
});
}); | frotunato/MEANcraft | client/app/app.js | JavaScript | mit | 1,953 |
var GridLayout = require("ui/layouts/grid-layout").GridLayout;
var ListView = require("ui/list-view").ListView;
var StackLayout = require("ui/layouts/stack-layout").StackLayout;
var Image = require("ui/image").Image;
var Label = require("ui/label").Label;
var ScrapbookList = (function (_super) {
global.__extends(ScrapbookList, _super);
Object.defineProperty(ScrapbookList.prototype, "items", {
get: function() {
return this._items;
},
set: function(value) {
this._items = value;
this.bindData();
}
});
function ScrapbookList() {
_super.call(this);
this._items;
this.rows = "*";
this.columns = "*";
var listView = new ListView();
listView.className = "list-group";
listView.itemTemplate = function() {
var stackLayout = new StackLayout();
stackLayout.orientation = "horizontal";
stackLayout.bind({
targetProperty: "className",
sourceProperty: "$value",
expression: "isActive ? 'list-group-item active' : 'list-group-item'"
});
var image = new Image();
image.className = "thumb img-circle";
image.bind({
targetProperty: "src",
sourceProperty: "image"
});
stackLayout.addChild(image);
var label = new Label();
label.className = "list-group-item-text";
label.style.width = "100%";
label.textWrap = true;
label.bind({
targetProperty: "text",
sourceProperty: "title",
expression: "(title === null || title === undefined ? 'New' : title + '\\\'s') + ' Scrapbook Page'"
});
stackLayout.addChild(label);
return stackLayout;
};
listView.on(ListView.itemTapEvent, function(args) {
onItemTap(this, args.index);
}.bind(listView));
this.addChild(listView);
this.bindData = function () {
listView.bind({
sourceProperty: "$value",
targetProperty: "items",
twoWay: "true"
}, this._items);
};
var onItemTap = function(args, index) {
this.notify({
eventName: "itemTap",
object: this,
index: index
});
}.bind(this);
}
return ScrapbookList;
})(GridLayout);
ScrapbookList.itemTapEvent = "itemTap";
exports.ScrapbookList = ScrapbookList; | mikebranstein/NativeScriptInAction | AppendixB/PetScrapbook/app/views/shared/scrapbook-list/scrapbook-list.js | JavaScript | mit | 3,048 |
<?php
/**
* @package toolkit
*/
/**
* The Datasource class provides functionality to mainly process any parameters
* that the fields will use in filters find the relevant Entries and return these Entries
* data as XML so that XSLT can be applied on it to create your website. In Symphony,
* there are four Datasource types provided, Section, Author, Navigation and Dynamic
* XML. Section is the mostly commonly used Datasource, which allows the filtering
* and searching for Entries in a Section to be returned as XML. Navigation datasources
* expose the Symphony Navigation structure of the Pages in the installation. Authors
* expose the Symphony Authors that are registered as users of the backend. Finally,
* the Dynamic XML datasource allows XML pages to be retrieved. This is especially
* helpful for working with Restful XML API's. Datasources are saved through the
* Symphony backend, which uses a Datasource template defined in
* `TEMPLATE . /datasource.tpl`.
*/
class DataSource
{
/**
* A constant that represents if this filter is an AND filter in which
* an Entry must match all these filters. This filter is triggered when
* the filter string contains a ` + `.
*
* @since Symphony 2.3.2
* @var integer
*/
const FILTER_AND = 1;
/**
* A constant that represents if this filter is an OR filter in which an
* entry can match any or all of these filters
*
* @since Symphony 2.3.2
* @var integer
*/
const FILTER_OR = 2;
/**
* Holds all the environment variables which include parameters set by
* other Datasources or Events.
* @var array
*/
protected $_env = array();
/**
* If true, this datasource only will be outputting parameters from the
* Entries, and no actual content.
* @var boolean
*/
protected $_param_output_only;
/**
* An array of datasource dependancies. These are datasources that must
* run first for this datasource to be able to execute correctly
* @var array
*/
protected $_dependencies = array();
/**
* When there is no entries found by the Datasource, this parameter will
* be set to true, which will inject the default Symphony 'No records found'
* message into the datasource's result
* @var boolean
*/
protected $_force_empty_result = false;
/**
* When there is a negating parameter, this parameter will
* be set to true, which will inject the default Symphony 'Results Negated'
* message into the datasource's result
* @var boolean
*/
protected $_negate_result = false;
/**
* Constructor for the datasource sets the parent, if `$process_params` is set,
* the `$env` variable will be run through `Datasource::processParameters`.
*
* @see toolkit.Datasource#processParameters()
* @param array $env
* The environment variables from the Frontend class which includes
* any params set by Symphony or Events or by other Datasources
* @param boolean $process_params
* If set to true, `Datasource::processParameters` will be called. By default
* this is true
* @throws FrontendPageNotFoundException
*/
public function __construct(array $env = null, $process_params = true)
{
// Support old the __construct (for the moment anyway).
// The old signature was array/array/boolean
// The new signature is array/boolean
$arguments = func_get_args();
if (count($arguments) == 3 && is_bool($arguments[1]) && is_bool($arguments[2])) {
$env = $arguments[0];
$process_params = $arguments[1];
}
if ($process_params) {
$this->processParameters($env);
}
}
/**
* This function is required in order to edit it in the datasource editor page.
* Do not overload this function if you are creating a custom datasource. It is only
* used by the datasource editor. If this is set to false, which is default, the
* Datasource's `about()` information will be displayed.
*
* @return boolean
* True if the Datasource can be edited, false otherwise. Defaults to false
*/
public function allowEditorToParse()
{
return false;
}
/**
* This function is required in order to identify what section this Datasource is for. It
* is used in the datasource editor. It must remain intact. Do not overload this function in
* custom events. Other datasources may return a string here defining their datasource
* type when they do not query a section.
*
* @return mixed
*/
public function getSource()
{
return null;
}
/**
* Accessor function to return this Datasource's dependencies
*
* @return array
*/
public function getDependencies()
{
return $this->_dependencies;
}
/**
* Returns an associative array of information about a datasource.
*
* @return array
*/
public function about()
{
return array();
}
/**
* @deprecated This function has been renamed to `execute` as of
* Symphony 2.3.1, please use `execute()` instead. This function will
* be removed in Symphony 2.5
* @see execute()
*/
public function grab(array &$param_pool = null)
{
return $this->execute($param_pool);
}
/**
* The meat of the Datasource, this function includes the datasource
* type's file that will preform the logic to return the data for this datasource
* It is passed the current parameters.
*
* @param array $param_pool
* The current parameter pool that this Datasource can use when filtering
* and finding Entries or data.
* @return XMLElement
* The XMLElement to add into the XML for a page.
*/
public function execute(array &$param_pool = null)
{
$result = new XMLElement($this->dsParamROOTELEMENT);
try {
$result = $this->execute($param_pool);
} catch (FrontendPageNotFoundException $e) {
// Work around. This ensures the 404 page is displayed and
// is not picked up by the default catch() statement below
FrontendPageNotFoundExceptionHandler::render($e);
} catch (Exception $e) {
$result->appendChild(new XMLElement('error', $e->getMessage()));
return $result;
}
if ($this->_force_empty_result) {
$result = $this->emptyXMLSet();
}
if ($this->_negate_result) {
$result = $this->negateXMLSet();
}
return $result;
}
/**
* By default, all Symphony filters are considering to be AND filters, that is
* they are all used and Entries must match each filter to be included. It is
* possible to use OR filtering in a field by using an + to separate the values.
* eg. If the filter is test1 + test2, this will match any entries where this field
* is test1 OR test2. This function is run on each filter (ie. each field) in a
* datasource
*
* @param string $value
* The filter string for a field.
* @return integer
* DataSource::FILTER_OR or DataSource::FILTER_AND
*/
public function __determineFilterType($value)
{
return (preg_match('/\s+\+\s+/', $value) ? DataSource::FILTER_AND : DataSource::FILTER_OR);
}
/**
* If there is no results to return this function calls `Datasource::__noRecordsFound`
* which appends an XMLElement to the current root element.
*
* @param XMLElement $xml
* The root element XMLElement for this datasource. By default, this will
* the handle of the datasource, as defined by `$this->dsParamROOTELEMENT`
* @return XMLElement
*/
public function emptyXMLSet(XMLElement $xml = null)
{
if (is_null($xml)) {
$xml = new XMLElement($this->dsParamROOTELEMENT);
}
$xml->appendChild($this->__noRecordsFound());
return $xml;
}
/**
* If the datasource has been negated this function calls `Datasource::__negateResult`
* which appends an XMLElement to the current root element.
*
* @param XMLElement $xml
* The root element XMLElement for this datasource. By default, this will
* the handle of the datasource, as defined by `$this->dsParamROOTELEMENT`
* @return XMLElement
*/
public function negateXMLSet(XMLElement $xml = null)
{
if (is_null($xml)) {
$xml = new XMLElement($this->dsParamROOTELEMENT);
}
$xml->appendChild($this->__negateResult());
return $xml;
}
/**
* Returns an error XMLElement with 'No records found' text
*
* @return XMLElement
*/
public function __noRecordsFound()
{
return new XMLElement('error', __('No records found.'));
}
/**
* Returns an error XMLElement with 'Result Negated' text
*
* @return XMLElement
*/
public function __negateResult()
{
$error = new XMLElement('error', __("Data source not executed, forbidden parameter was found."), array(
'forbidden-param' => $this->dsParamNEGATEPARAM
));
return $error;
}
/**
* This function will iterates over the filters and replace any parameters with their
* actual values. All other Datasource variables such as sorting, ordering and
* pagination variables are also set by this function
*
* @param array $env
* The environment variables from the Frontend class which includes
* any params set by Symphony or Events or by other Datasources
* @throws FrontendPageNotFoundException
*/
public function processParameters(array $env = null)
{
if ($env) {
$this->_env = $env;
}
if ((isset($this->_env) && is_array($this->_env)) && isset($this->dsParamFILTERS) && is_array($this->dsParamFILTERS) && !empty($this->dsParamFILTERS)) {
foreach ($this->dsParamFILTERS as $key => $value) {
$value = stripslashes($value);
$new_value = $this->__processParametersInString($value, $this->_env);
// If a filter gets evaluated to nothing, eg. ` + ` or ``, then remove
// the filter. RE: #1759
if (strlen(trim($new_value)) == 0 || !preg_match('/\w+/', $new_value)) {
unset($this->dsParamFILTERS[$key]);
} else {
$this->dsParamFILTERS[$key] = $new_value;
}
}
}
if (isset($this->dsParamORDER)) {
$this->dsParamORDER = $this->__processParametersInString($this->dsParamORDER, $this->_env);
}
if (isset($this->dsParamSORT)) {
$this->dsParamSORT = $this->__processParametersInString($this->dsParamSORT, $this->_env);
}
if (isset($this->dsParamSTARTPAGE)) {
$this->dsParamSTARTPAGE = $this->__processParametersInString($this->dsParamSTARTPAGE, $this->_env);
if ($this->dsParamSTARTPAGE == '') {
$this->dsParamSTARTPAGE = '1';
}
}
if (isset($this->dsParamLIMIT)) {
$this->dsParamLIMIT = $this->__processParametersInString($this->dsParamLIMIT, $this->_env);
}
if (
isset($this->dsParamREQUIREDPARAM)
&& strlen(trim($this->dsParamREQUIREDPARAM)) > 0
&& $this->__processParametersInString(trim($this->dsParamREQUIREDPARAM), $this->_env, false) == ''
) {
$this->_force_empty_result = true; // don't output any XML
$this->dsParamPARAMOUTPUT = null; // don't output any parameters
$this->dsParamINCLUDEDELEMENTS = null; // don't query any fields in this section
return;
}
if (
isset($this->dsParamNEGATEPARAM)
&& strlen(trim($this->dsParamNEGATEPARAM)) > 0
&& $this->__processParametersInString(trim($this->dsParamNEGATEPARAM), $this->_env, false) != ''
) {
$this->_negate_result = true; // don't output any XML
$this->dsParamPARAMOUTPUT = null; // don't output any parameters
$this->dsParamINCLUDEDELEMENTS = null; // don't query any fields in this section
return;
}
$this->_param_output_only = ((!isset($this->dsParamINCLUDEDELEMENTS) || !is_array($this->dsParamINCLUDEDELEMENTS) || empty($this->dsParamINCLUDEDELEMENTS)) && !isset($this->dsParamGROUP));
if (isset($this->dsParamREDIRECTONEMPTY) && $this->dsParamREDIRECTONEMPTY == 'yes' && $this->_force_empty_result) {
throw new FrontendPageNotFoundException;
}
}
/**
* This function will parse a string (usually a URL) and fully evaluate any
* parameters (defined by {$param}) to return the absolute string value.
*
* @since Symphony 2.3
* @param string $url
* The string (usually a URL) that contains the parameters (or doesn't)
* @return string
* The parsed URL
*/
public function parseParamURL($url = null)
{
if (!isset($url)) {
return null;
}
// urlencode parameters
$params = array();
if (preg_match_all('@{([^}]+)}@i', $url, $matches, PREG_SET_ORDER)) {
foreach ($matches as $m) {
$params[$m[1]] = array(
'param' => preg_replace('/:encoded$/', null, $m[1]),
'encode' => preg_match('/:encoded$/', $m[1])
);
}
}
foreach ($params as $key => $info) {
$replacement = $this->__processParametersInString($info['param'], $this->_env, false);
if ($info['encode'] == true) {
$replacement = urlencode($replacement);
}
$url = str_replace("{{$key}}", $replacement, $url);
}
return $url;
}
/**
* This function will replace any parameters in a string with their value.
* Parameters are defined by being prefixed by a `$` character. In certain
* situations, the parameter will be surrounded by `{}`, which Symphony
* takes to mean, evaluate this parameter to a value, other times it will be
* omitted which is usually used to indicate that this parameter exists
*
* @param string $value
* The string with the parameters that need to be evaluated
* @param array $env
* The environment variables from the Frontend class which includes
* any params set by Symphony or Events or by other Datasources
* @param boolean $includeParenthesis
* Parameters will sometimes not be surrounded by `{}`. If this is the case
* setting this parameter to false will make this function automatically add
* them to the parameter. By default this is true, which means all parameters
* in the string already are surrounded by `{}`
* @param boolean $escape
* If set to true, the resulting value will passed through `urlencode` before
* being returned. By default this is `false`
* @return string
* The string with all parameters evaluated. If a parameter is not found, it will
* not be replaced and remain in the `$value`.
*/
public function __processParametersInString($value, array $env, $includeParenthesis = true, $escape = false)
{
if (trim($value) == '') {
return null;
}
if (!$includeParenthesis) {
$value = '{'.$value.'}';
}
if (preg_match_all('@{([^}]+)}@i', $value, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
list($source, $cleaned) = $match;
$replacement = null;
$bits = preg_split('/:/', $cleaned, -1, PREG_SPLIT_NO_EMPTY);
foreach ($bits as $param) {
if ($param{0} != '$') {
$replacement = $param;
break;
}
$param = trim($param, '$');
$replacement = Datasource::findParameterInEnv($param, $env);
if (is_array($replacement)) {
$replacement = array_map(array('Datasource', 'escapeCommas'), $replacement);
if (count($replacement) > 1) {
$replacement = implode(',', $replacement);
} else {
$replacement = end($replacement);
}
}
if (!empty($replacement)) {
break;
}
}
if ($escape == true) {
$replacement = urlencode($replacement);
}
$value = str_replace($source, $replacement, $value);
}
}
return $value;
}
/**
* Using regexp, this escapes any commas in the given string
*
* @param string $string
* The string to escape the commas in
* @return string
*/
public static function escapeCommas($string)
{
return preg_replace('/(?<!\\\\),/', "\\,", $string);
}
/**
* Used in conjunction with escapeCommas, this function will remove
* the escaping pattern applied to the string (and commas)
*
* @param string $string
* The string with the escaped commas in it to remove
* @return string
*/
public static function removeEscapedCommas($string)
{
return preg_replace('/(?<!\\\\)\\\\,/', ',', $string);
}
/**
* Parameters can exist in three different facets of Symphony; in the URL,
* in the parameter pool or as an Symphony param. This function will attempt
* to find a parameter in those three areas and return the value. If it is not found
* null is returned
*
* @param string $needle
* The parameter name
* @param array $env
* The environment variables from the Frontend class which includes
* any params set by Symphony or Events or by other Datasources
* @return mixed
* If the value is not found, null, otherwise a string or an array is returned
*/
public static function findParameterInEnv($needle, $env)
{
if (isset($env['env']['url'][$needle])) {
return $env['env']['url'][$needle];
}
if (isset($env['env']['pool'][$needle])) {
return $env['env']['pool'][$needle];
}
if (isset($env['param'][$needle])) {
return $env['param'][$needle];
}
return null;
}
}
require_once TOOLKIT . '/data-sources/class.datasource.author.php';
require_once TOOLKIT . '/data-sources/class.datasource.section.php';
require_once TOOLKIT . '/data-sources/class.datasource.static.php';
require_once TOOLKIT . '/data-sources/class.datasource.dynamic_xml.php';
require_once TOOLKIT . '/data-sources/class.datasource.navigation.php';
| jdsimcoe/symphony-boilerplate | symphony/lib/toolkit/class.datasource.php | PHP | mit | 19,238 |
NAME = airdock/redis
VERSION = dev-2.8
.PHONY: all clean build tag_latest release debug run run_client
all: build
clean:
@CID=$(shell docker ps -a | awk '{ print $$1 " " $$2 }' | grep $(NAME) | awk '{ print $$1 }'); if [ ! -z "$$CID" ]; then echo "Removing container which reference $(NAME)"; for container in $(CID); do docker rm -f $$container; done; fi;
@if docker images $(NAME) | awk '{ print $$2 }' | grep -q -F $(VERSION); then docker rmi -f $(NAME):$(VERSION); fi
@if docker images $(NAME) | awk '{ print $$2 }' | grep -q -F latest; then docker rmi -f $(NAME):latest; fi
build: clean
docker build -t $(NAME):$(VERSION) --rm .
tag_latest:
@docker tag $(NAME):$(VERSION) $(NAME):latest
release: build tag_latest
docker push $(NAME)
@echo "Create a tag v-$(VERSION)"
@git tag v-$(VERSION)
@git push origin v-$(VERSION)
debug:
docker run -t -i $(NAME):$(VERSION)
run:
@echo "IPAddress =" $$(docker inspect --format '{{.NetworkSettings.IPAddress}}' $$(docker run -d -p 6379:6379 --name redis $(NAME):$(VERSION)))
run_client:
docker run -it --rm --link redis:redis $(NAME):$(VERSION) bash -c 'redis-cli -h redis'
| airdock-io/docker-redis | 2.8/Makefile | Makefile | mit | 1,137 |
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const double EPS = 1e-9;
inline char DBLCMP(double d)
{
if (fabs(d) < EPS) return 0;
return d>0 ? 1 : -1;
}
struct spoint
{
double x, y, z;
spoint() {}
spoint(double xx, double yy, double zz): x(xx), y(yy), z(zz) {}
void read()
{scanf("%lf%lf%lf", &x, &y, &z);}
};
spoint operator - (const spoint &v1, const spoint &v2)
{return spoint(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z);}
double dot(const spoint &v1, const spoint &v2)
{return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z;}
double norm(const spoint &v)
{return sqrt(v.x*v.x+v.y*v.y+v.z*v.z);}
double dis(const spoint &p1, const spoint &p2)
{return norm(p2-p1);}
spoint c, n, s, v, p;
double r, t1, t2, i, j, k;
//ax+b=0
//0 for no solution, 1 for one solution, 2 for infinitive solution
char lneq(double a, double b, double &x)
{
if (DBLCMP(a) == 0)
{
if (DBLCMP(b) == 0) return 2;
return 0;
}
x = -b/a;
return 1;
}
//ax^2+bx+c=0, a!=0
//0 for no solution, 1 for one solution, 2 for 2 solutions
//x1 <= x2
char qdeq(double a, double b, double c, double &x1, double &x2)
{
double delta = b*b-4*a*c;
if (delta < 0) return 0;
x1 = (-b+sqrt(delta))/(2*a);
x2 = (-b-sqrt(delta))/(2*a);
if (x1 > x2) swap(x1, x2);
return DBLCMP(delta) ? 2 : 1;
}
int main()
{
c.read();
n.read();
scanf("%lf", &r);
//printf("##%f\n", dis(spoint(0,0,0), spoint(1,1,1)));
s.read();
v.read();
i = -5.0*n.z; j = dot(n, v); k = dot(n, s-c);
if (DBLCMP(i)==0)
{
char sta = lneq(j, k, t1);
if (sta==0 || sta==2 || DBLCMP(t1) <= 0)
{
puts("MISSED");
return 0;
}
p.x = s.x+v.x*t1;
p.y = s.y+v.y*t1;
p.z = s.z+v.z*t1-5.0*t1*t1;
if (DBLCMP(dis(p, c)-r) < 0)
{
puts("HIT");
return 0;
}
puts("MISSED");
return 0;
}
if (!qdeq(i, j, k, t1, t2))
{
puts("MISSED");
return 0;
}
if (DBLCMP(t1) > 0)
{
p.x = s.x+v.x*t1;
p.y = s.y+v.y*t1;
p.z = s.z+v.z*t1-5.0*t1*t1;
if (DBLCMP(dis(p, c)-r) < 0)
{
puts("HIT");
return 0;
}
}
if (DBLCMP(t2) > 0)
{
p.x = s.x+v.x*t2;
p.y = s.y+v.y*t2;
p.z = s.z+v.z*t2-5.0*t2*t2;
if (DBLCMP(dis(p, c)-r) < 0)
{
puts("HIT");
return 0;
}
}
puts("MISSED");
return 0;
}
| jffifa/algo-solution | ural/1093.cpp | C++ | mit | 2,211 |
<?php
/**
* Examples of ShareCouners usage
* @author Dominik Bułaj <[email protected]>
*/
include '../src/SharesCounter.php';
include '../src/Networks.php';
include '../src/Exception.php';
$url = 'http://www.huffingtonpost.com';
// 1. return shares from Facebook and Twitter
$shares = new \SharesCounter\SharesCounter($url);
$counts = $shares->getShares([\SharesCounter\Networks::NETWORK_FACEBOOK, \SharesCounter\Networks::NETWORK_TWITTER]);
var_dump($counts);
// 2. return shares from all available networks
$shares = new \SharesCounter\SharesCounter($url);
$counts = $shares->getShares([]);
var_dump($counts);
// 3. return shares from disabled by default network
$url = 'http://www.moy-rebenok.ru';
$shares = new \SharesCounter\SharesCounter($url);
$counts = $shares->getShares([\SharesCounter\Networks::NETWORK_VK, \SharesCounter\Networks::NETWORK_ODNOKLASSNIKI]);
var_dump($counts);
// 4. wykop.pl
$url = 'http://pokazywarka.pl/margaryna/';
$shares = new \SharesCounter\SharesCounter($url);
$counts = $shares->getShares([\SharesCounter\Networks::NETWORK_WYKOP]);
var_dump($counts);
// 4. helper method - return list of available networks
$networks = new \SharesCounter\Networks();
$availableNetworks = $networks->getAvailableNetworks();
var_export($availableNetworks); | dominikbulaj/shares-counter-php | examples/index.php | PHP | mit | 1,282 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCharactersLangTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Create the characters_lang table
Schema::create('characters_lang', function($table)
{
$default_locale = \Config::get('app.locale');
$locales = \Config::get('app.locales', array($default_locale));
$table->increments('id');
$table->mediumInteger('character_id');
$table->string('firstname')->nullable();
$table->string('lastname')->nullable();
$table->string('nickname')->nullable();
$table->string('overview')->nullable();
$table->enum('locale', $locales);
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Drop the characters_lang table
Schema::dropIfExists('characters_lang');
}
}
| Truemedia/regeneration-character | src/database/migrations/2015_05_16_174527_create_characters_lang_table.php | PHP | mit | 981 |
<!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' xml:lang='en' lang='en'><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<title>124-10-7.smi.png.html</title>
</head>
<body>ID124-10-7<br/>
<img border="0" src="124-10-7.smi.png" alt="124-10-7.smi.png"></img><br/>
<br/>
<table border="1">
<tr>
<td></td><td>ID</td><td>Formula</td><td>FW</td><td>DSSTox_CID</td><td>DSSTox_RID</td><td>DSSTox_GSID</td><td>DSSTox_FileID_Sort</td><td>TS_ChemName</td><td>TS_ChemName_Synonyms</td><td>TS_CASRN</td><td>CASRN_ChemName_Relationship</td><td>TS_Description</td><td>ChemNote</td><td>STRUCTURE_Shown</td><td>STRUCTURE_Formula</td><td>STRUCTURE_MW</td><td>STRUCTURE_ChemType</td><td>STRUCTURE_DefinedOrganicForm</td><td>STRUCTURE_IUPAC</td><td>STRUCTURE_SMILES</td><td>STRUCTURE_SMILES_Desalt</td><td>Substance_modify_yyyymmdd</td></tr>
<tr>
<td>124-10-7</td><td>4886</td><td>C15H30O2</td><td>242.3975</td><td>7019</td><td>78281</td><td>27019</td><td>2964</td><td>Methyl tetradecanoate</td><td>Methyl tetradecanoate (Tetradecanoic acid, methyl ester) (Methyl myristate)</td><td>124-10-7</td><td>primary</td><td>single chemical compound</td><td></td><td>tested chemical</td><td>C15H30O2</td><td>242.3975</td><td>defined organic</td><td>parent</td><td>methyl tetradecanoate</td><td>O=C(CCCCCCCCCCCCC)OC</td><td>O=C(CCCCCCCCCCCCC)OC</td><td>20080429</td></tr>
</table>
<br/><br/><font size="-2">(Page generated on Wed Sep 17 03:57:12 2014 by <a href="http://www.embl.de/~gpau/hwriter/index.html">hwriter</a> 1.3)</font><br/>
</body></html> | andrewdefries/ToxCast | Figure3/Tox21_nnm/WorkHere/124-10-7.smi.png.html | HTML | mit | 1,675 |
import React, {Component} from 'react';
import {Typeahead} from 'react-bootstrap-typeahead';
import {inject, observer} from 'mobx-react';
import {action, toJS, autorunAsync} from 'mobx';
import myClient from '../agents/client'
require('react-bootstrap-typeahead/css/ClearButton.css');
require('react-bootstrap-typeahead/css/Loader.css');
require('react-bootstrap-typeahead/css/Token.css');
require('react-bootstrap-typeahead/css/Typeahead.css');
@inject('controlsStore', 'designStore')
@observer
export default class EroTypeahead extends Component {
constructor(props) {
super(props);
}
state = {
options: []
};
// this will keep updating the next -ERO options as the ERO changes;
disposeOfEroOptionsUpdate = autorunAsync('ero options update', () => {
let ep = this.props.controlsStore.editPipe;
let submitEro = toJS(ep.ero.hops);
// keep track of the last hop; if we've reached Z we shouldn't keep going
let lastHop = ep.a;
if (ep.ero.hops.length > 0) {
lastHop = ep.ero.hops[ep.ero.hops.length - 1];
} else {
// if there's _nothing_ in our ERO then ask for options from pipe.a
submitEro.push(ep.a);
}
// if this is the last hop, don't provide any options
if (lastHop === ep.z) {
this.setState({options: []});
return;
}
myClient.submit('POST', '/api/pce/nextHopsForEro', submitEro)
.then(
action((response) => {
let nextHops = JSON.parse(response);
if (nextHops.length > 0) {
let opts = [];
nextHops.map(h => {
let entry = {
id: h.urn,
label: h.urn + ' through ' + h.through + ' to ' + h.to,
through: h.through,
to: h.to
};
opts.push(entry);
});
this.setState({options: opts});
}
}));
}, 500);
componentWillUnmount() {
this.disposeOfEroOptionsUpdate();
}
onTypeaheadSelection = selection => {
if (selection.length === 0) {
return;
}
let wasAnOption = false;
let through = '';
let urn = '';
let to = '';
this.state.options.map(opt => {
if (opt.label === selection) {
wasAnOption = true;
through = opt.through;
urn = opt.id;
to = opt.to;
}
});
if (wasAnOption) {
let ep = this.props.controlsStore.editPipe;
let ero = [];
ep.manual.ero.map(e => {
ero.push(e);
});
ero.push(through);
ero.push(urn);
ero.push(to);
this.props.controlsStore.setParamsForEditPipe({
ero: {
hops: ero
},
manual: {ero: ero}
});
this.typeAhead.getInstance().clear();
}
};
render() {
return (
<Typeahead
minLength={0}
ref={(ref) => {
this.typeAhead = ref;
}}
placeholder='choose from selection'
options={this.state.options}
onInputChange={this.onTypeaheadSelection}
clearButton
/>
);
}
} | haniotak/oscars-frontend | src/main/js/components/eroTypeahead.js | JavaScript | mit | 3,673 |
'use strict';
var convert = require('./convert'),
func = convert('lt', require('../lt'));
func.placeholder = require('./placeholder');
module.exports = func;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2x0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFWO0lBQ0EsT0FBTyxRQUFRLElBQVIsRUFBYyxRQUFRLE9BQVIsQ0FBZCxDQUFQOztBQUVKLEtBQUssV0FBTCxHQUFtQixRQUFRLGVBQVIsQ0FBbkI7QUFDQSxPQUFPLE9BQVAsR0FBaUIsSUFBakIiLCJmaWxlIjoibHQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgY29udmVydCA9IHJlcXVpcmUoJy4vY29udmVydCcpLFxuICAgIGZ1bmMgPSBjb252ZXJ0KCdsdCcsIHJlcXVpcmUoJy4uL2x0JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19 | justin-lai/hackd.in | compiled/client/lib/lodash/fp/lt.js | JavaScript | mit | 778 |
<?php
/**
* UserAccount
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package blueprint
* @subpackage model
* @author Your name here
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class UserAccount extends BaseUserAccount
{
}
| zenkovnick/pfr | lib/model/doctrine/UserAccount.class.php | PHP | mit | 299 |
# Rounded Button Twitch Chat

This CSS file overrides the Twitch chat popout window to make the chat slightly more visually appealing. It was created to be used with the OBS
plugin Linux Browser, and presumably will work with the default Browser source for Mac and Windows.
## Instructions For Use
1. Add a (Linux) Browser source to a scene
2. Set the URL to `https://www.twitch.tv/{yourchannel}/chat`
3. Select this CSS file for the custom CSS
4. Adjust page size, zoom, and crop until only the chat area is visible
5. Add a Chroma Key filter
6. Set the Key Color Type to Custom and change the Key Color to `#123123`
7. Adjust the similarity, smoothness, and key color spillreduction to your liking (1, 35, 100 are what I found to work best)
8. Sit back and enjoy!
## Notes
### Dark Theme
Check the comments in the file for recommended hex values for a dark theme!
### Badges
To add badges back into the chat, simply comment out or delete the last section of the file:
.badges {
/* Hide badges */
position:absolute!important;
visibility:hidden;
}
### Browser Sizing
What I found works well is 150% zoom and a minimum width of 450px. From here, add a crop filter with 76px top and 168px bottom.
This should perfectly frame your chat without losing any space.
| WolfgangAxel/Random-Projects | Streaming/Rounded Button Twitch Chat/README.md | Markdown | mit | 1,418 |
purescript-three
================
Purescript bindings for Threejs
# Build purescript-three
```
bower install
pulp build
bower link
```
# Build examples
```
cd examples/
bower link purescript-three
pulp browserify --main Examples.CircleToSquare --to output/circleToSquare.js
pulp browserify --main Examples.LineArray --to output/lineArray.js
pulp browserify --main Examples.MotionStretch --to output/motionStretch.js
pulp browserify --main Examples.SimpleCube --to output/simpleCube.js
pulp browserify --main Examples.SimpleLine --to output/simpleLine.js
open resources/*.html // in your favorite browser
```
| anthoq88/purescript-three | README.md | Markdown | mit | 615 |
TOP_DIR = ../..
LIB_DIR = lib/
DEPLOY_RUNTIME ?= /kb/runtime
TARGET ?= /kb/deployment
include $(TOP_DIR)/tools/Makefile.common
SPEC_FILE = handle_mngr.spec
SERVICE_NAME = HandleMngr
SERVICE_CAPS = HandleMngr
SERVICE_PORT = 9001
SERVICE_DIR = handle_mngr
SERVICE_CONFIG = HandleMngr
ifeq ($(SELF_URL),)
SELF_URL = http://localhost:$(SERVICE_PORT)
endif
SERVICE_PSGI = $(SERVICE_NAME).psgi
TPAGE_ARGS = --define kb_runas_user=$(SERVICE_USER) --define kb_top=$(TARGET) --define kb_runtime=$(DEPLOY_RUNTIME) --define kb_service_name=$(SERVICE_NAME) --define kb_service_config_stanza=$(SERVICE_CONFIG) --define kb_service_dir=$(SERVICE_DIR) --define kb_service_port=$(SERVICE_PORT) --define kb_psgi=$(SERVICE_PSGI)
# to wrap scripts and deploy them to $(TARGET)/bin using tools in
# the dev_container. right now, these vars are defined in
# Makefile.common, so it's redundant here.
TOOLS_DIR = $(TOP_DIR)/tools
WRAP_PERL_TOOL = wrap_perl
WRAP_PERL_SCRIPT = bash $(TOOLS_DIR)/$(WRAP_PERL_TOOL).sh
SRC_PERL = $(wildcard scripts/*.pl)
# You can change these if you are putting your tests somewhere
# else or if you are not using the standard .t suffix
CLIENT_TESTS = $(wildcard client-tests/*.t)
SCRIPTS_TESTS = $(wildcard script-tests/*.t)
SERVER_TESTS = $(wildcard server-tests/*.t)
# This is a very client-centric view of release engineering.
# We assume our primary product for the community is the client
# libraries, command line interfaces, and the related documentation
# from which specific science applications can be built.
#
# A service is composed of a client and a server, each of which
# should be independently deployable. Clients are composed of
# an application programming interface (API) and a command line
# interface (CLI). In our make targets, deploy-service deploys
# the server, deploy-client deploys the application
# programming interface libraries, and deploy-scripts deploys
# the command line interface (usually scripts written in a
# scripting language but java executables also qualify), and the
# deploy target would be equivelant to deploying a service (client
# libs, scripts, and server).
#
# Because the deployment of the server side code depends on the
# specific software module being deployed, the strategy needs
# to be one that leaves this decision to the module developer.
# This is done by having the deploy target depend on the
# deploy-service target. The module developer who chooses for
# good reason not to deploy the server with the client simply
# manages this dependancy accordingly. One option is to have
# a deploy-service target that does nothing, the other is to
# remove the dependancy from the deploy target.
#
# A smiliar naming convention is used for tests.
default:
# Distribution Section
#
# This section deals with the packaging of source code into a
# distributable form. This is different from a deployable form
# as our deployments tend to be kbase specific. To create a
# distribution, we have to consider the distribution mechanisms.
# For starters, we will consider cpan style packages for perl
# code, we will consider egg for python, npm for javascript,
# and it is not clear at this time what is right for java.
#
# In all cases, it is important not to implement into these
# targets the actual distribution. What these targets deal
# with is creating the distributable object (.tar.gz, .jar,
# etc) and placing it in the top level directory of the module
# distrubution directory.
#
# Use <module_name>/distribution as the top level distribution
# directory
dist: dist-cpan dist-egg dist-npm dist-java dist-r
dist-cpan: dist-cpan-client dist-cpan-service
dist-egg: dist-egg-client dist-egg-service
# In this case, it is not clear what npm service would mean,
# unless we are talking about a service backend implemented
# in javascript, which I can imagine happing. So the target
# is here, even though we don't have support for javascript
# on the back end of the compiler at this time.
dist-npm: dist-npm-client dist-npm-service
dist-java: dist-java-client dist-java-service
# in this case, I'm using the word client just for consistency
# sake. What we mean by client is an R library. At this time
# the meaning of a r-service is not understood. It can be
# added at a later time if there is a good reason.
dist-r: dist-r-client
dist-cpan-client:
echo "cpan client distribution not supported"
dist-cpan-service:
echo "cpan service distribution not supported"
dist-egg-client:
echo "egg client distribution not supported"
dist-egg-service:
echo "egg service distribution not supported"
dist-npm-client:
echo "npm client distribution not supported"
dist-npm-service:
echo "npm service distribution not supported"
dist-java-client:
echo "java client distribution not supported"
dist-java-service:
echo "java service distribuiton not supported"
dist-r-client:
echo "r client lib distribution not supported"
# Test Section
test: test-client test-scripts test-service
@echo "running client and script tests"
# test-all is deprecated.
# test-all: test-client test-scripts test-service
#
# test-client: This is a test of a client library. If it is a
# client-server module, then it should be run against a running
# server. You can say that this also tests the server, and I
# agree. You can add a test-service dependancy to the test-client
# target if it makes sense to you. This test example assumes there is
# already a tested running server.
test-client:
# run each test
for t in $(CLIENT_TESTS) ; do \
if [ -f $$t ] ; then \
$(DEPLOY_RUNTIME)/bin/perl $$t ; \
if [ $$? -ne 0 ] ; then \
exit 1 ; \
fi \
fi \
done
# test-scripts: A script test should test the command line scripts. If
# the script is a client in a client-server architecture, then there
# should be tests against a running server. You can add a test-service
# dependency to the test-client target. You could also add a
# deploy-service and start-server dependancy to the test-scripts
# target if it makes sense to you. Future versions of the makefiles
# for services will move in this direction.
test-scripts:
# run each test
for t in $(SCRIPT_TESTS) ; do \
if [ -f $$t ] ; then \
$(DEPLOY_RUNTIME)/bin/perl $$t ; \
if [ $$? -ne 0 ] ; then \
exit 1 ; \
fi \
fi \
done
# test-service: A server test should not rely on the client libraries
# or scripts--you should not have a test-service target that depends
# on the test-client or test-scripts targets. Otherwise, a circular
# dependency graph could result.
test-service:
# run each test
for t in $(SERVER_TESTS) ; do \
if [ -f $$t ] ; then \
$(DEPLOY_RUNTIME)/bin/perl $$t ; \
if [ $$? -ne 0 ] ; then \
exit 1 ; \
fi \
fi \
done
# Deployment:
#
# We are assuming our primary products to the community are
# client side application programming interface libraries and a
# command line interface (scripts). The deployment of client
# artifacts should not be dependent on deployment of a server,
# although we recommend deploying the server code with the
# client code when the deploy target is executed. If you have
# good reason not to deploy the server at the same time as the
# client, just delete the dependancy on deploy-service. It is
# important to note that you must have a deploy-service target
# even if there is no server side code to deploy.
deploy: deploy-client deploy-service
# deploy-all deploys client *and* server. This target is deprecated
# and should be replaced by the deploy target.
deploy-all: deploy-client deploy-service
# deploy-client should deploy the client artifacts, mainly
# the application programming interface libraries, command
# line scripts, and associated reference documentation.
deploy-client: deploy-libs deploy-scripts deploy-docs
# The deploy-libs and deploy-scripts targets are used to recognize
# and delineate the client types, mainly a set of libraries that
# implement an application programming interface and a set of
# command line scripts that provide command-based execution of
# individual API functions and aggregated sets of API functions.
deploy-libs: build-libs
rsync --exclude '*.bak*' -arv lib/. $(TARGET)/lib/.
# Deploying scripts needs some special care. They need to run
# in a certain runtime environment. Users should not have
# to modify their user environments to run kbase scripts, other
# than just sourcing a single user-env script. The creation
# of this user-env script is the responsibility of the code
# that builds all the kbase modules. In the code below, we
# run a script in the dev_container tools directory that
# wraps perl scripts. The name of the perl wrapper script is
# kept in the WRAP_PERL_SCRIPT make variable. This script
# requires some information that is passed to it by way
# of exported environment variables in the bash script below.
#
# What does it mean to wrap a perl script? To wrap a perl
# script means that a bash script is created that sets
# all required environment variables and then calls the perl
# script using the perl interperter in the kbase runtime.
# For this to work, both the actual script and the newly
# created shell script have to be deployed. When a perl
# script is wrapped, it is first copied to TARGET/plbin.
# The shell script can now be created because the necessary
# environment variables are known and the location of the
# script is known.
deploy-scripts:
export KB_TOP=$(TARGET); \
export KB_RUNTIME=$(DEPLOY_RUNTIME); \
export KB_PERL_PATH=$(TARGET)/lib bash ; \
for src in $(SRC_PERL) ; do \
basefile=`basename $$src`; \
base=`basename $$src .pl`; \
echo install $$src $$base ; \
cp $$src $(TARGET)/plbin ; \
$(WRAP_PERL_SCRIPT) "$(TARGET)/plbin/$$basefile" $(TARGET)/bin/$$base ; \
done
# Deploying a service refers to to deploying the capability
# to run a service. Becuase service code is often deployed
# as part of the libs, meaning service code gets deployed
# when deploy-libs is called, the deploy-service target is
# generally concerned with the service start and stop scripts.
# The deploy-cfg target is defined in the common rules file
# located at $TOP_DIR/tools/Makefile.common.rules and included
# at the end of this file.
deploy-service: deploy-cfg
mkdir -p $(TARGET)/services/$(SERVICE_DIR)
$(TPAGE) $(TPAGE_ARGS) service/start_service.tt > $(TARGET)/services/$(SERVICE_DIR)/start_service
chmod +x $(TARGET)/services/$(SERVICE_DIR)/start_service
$(TPAGE) $(TPAGE_ARGS) service/stop_service.tt > $(TARGET)/services/$(SERVICE_DIR)/stop_service
chmod +x $(TARGET)/services/$(SERVICE_DIR)/stop_service
$(TPAGE) $(TPAGE_ARGS) service/upstart.tt > service/$(SERVICE_NAME).conf
chmod +x service/$(SERVICE_NAME).conf
$(TPAGE) $(TPAGE_ARGS) service/constants.tt > $(TARGET)/lib/Bio/KBase/HandleMngrConstants.pm
echo "done executing deploy-service target"
deploy-upstart: deploy-service
-cp service/$(SERVICE_NAME).conf /etc/init/
echo "done executing deploy-upstart target"
# Deploying docs here refers to the deployment of documentation
# of the API. We'll include a description of deploying documentation
# of command line interface scripts when we have a better understanding of
# how to standardize and automate CLI documentation.
deploy-docs: build-docs
-mkdir -p $(TARGET)/services/$(SERVICE_DIR)/webroot/.
cp docs/*.html $(TARGET)/services/$(SERVICE_DIR)/webroot/.
# The location of the Client.pm file depends on the --client param
# that is provided to the compile_typespec command. The
# compile_typespec command is called in the build-libs target.
build-docs: compile-docs
-mkdir -p docs
pod2html --infile=lib/Bio/KBase/$(SERVICE_NAME)/$(SERVICE_CAPS)Client.pm --outfile=docs/$(SERVICE_NAME).html
# Use the compile-docs target if you want to unlink the generation of
# the docs from the generation of the libs. Not recommended, but there
# could be a reason for it that I'm not seeing.
# The compile-docs target should depend on build-libs so that we are
# assured of having a set of documentation that is based on the latest
# type spec.
compile-docs: build-libs
# build-libs should be dependent on the type specification and the
# type compiler. Building the libs in this way means that you don't
# need to put automatically generated code in a source code version
# control repository (e.g., cvs, git). It also ensures that you always
# have the most up-to-date libs and documentation if your compile-docs
# target depends on the compiled libs.
build-libs:
kb-sdk compile $(SPEC_FILE) \
--out $(LIB_DIR) \
--plpsginame $(SERVICE_CAPS).psgi \
--plimplname Bio::KBase::$(SERVICE_CAPS)::$(SERVICE_CAPS)Impl \
--plsrvname Bio::KBase::$(SERVICE_CAPS)::$(SERVICE_CAPS)Server \
--plclname Bio::KBase::$(SERVICE_CAPS)::$(SERVICE_CAPS)Client \
--pyclname biokbase/$(SERVICE_CAPS)/Client \
--jsclname javascript/$(SERVICE_CAPS)/Client \
--url $(SELF_URL)
# the Makefile.common.rules contains a set of rules that can be used
# in this setup. Because it is included last, it has the effect of
# shadowing any targets defined above. So lease be aware of the
# set of targets in the common rules file.
include $(TOP_DIR)/tools/Makefile.common.rules
| kbase/handle_mngr | Makefile | Makefile | mit | 13,184 |
<?php
use PDFfiller\OAuth2\Client\Provider\Token;
$provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php';
$e = Token::one($provider, 3329);
dd($e);
| pdffiller/pdffiller-php-api-client | examples/token/3_get_token.php | PHP | mit | 164 |
package sql.fredy.sqltools;
/**
XLSExport exports the result of a query into a XLS-file. To do this it is
using HSSF from the Apache POI Project: http://jakarta.apache.org/poi
Version 1.0 Date 7. aug. 2003 Author Fredy Fischer
XLSExport is part of the Admin-Suite
Once instantiated there are the following steps to go to get a XLS-file out
of a query
XLSExport xe = new XLSExport(java.sql.Connection con)
xe.setQuery(java.lang.String query) please set herewith the the query to get
its results as XLS-file
int xe.createXLS(java.lang.String fileName) this will then create the
XLS-File. If this file already exists, it will be overwritten!
it returns the number of rows written to the File
2015-11-16 Creating an additional Worksheet containing the SQL-Query
Admin is a Tool around SQL to do basic jobs for DB-Administrations, like: -
create/ drop tables - create indices - perform sql-statements - simple form -
a guided query and a other usefull things in DB-arena
Copyright (c) 2017 Fredy Fischer, [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import sql.fredy.share.t_connect;
import java.io.InputStream;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.*;
import java.util.logging.*;
import java.util.Date;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.record.*;
import org.apache.poi.hssf.model.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import java.util.ArrayList;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
public class XLSExport {
private Logger logger;
Connection con = null;
/**
* Get the value of con.
*
* @return value of con.
*/
public Connection getCon() {
return con;
}
/**
* Set the value of con.
*
* @param v Value to assign to con.
*/
public void setCon(Connection v) {
this.con = v;
}
String query=null;
/**
* Get the value of query.
*
* @return value of query.
*/
public String getQuery() {
return query;
}
/**
* Set the value of query.
*
* @param v Value to assign to query.
*/
public void setQuery(String v) {
this.query = v;
}
java.sql.SQLException exception;
/**
* Get the value of exception.
*
* @return value of exception.
*/
public java.sql.SQLException getException() {
return exception;
}
/**
* Set the value of exception.
*
* @param v Value to assign to exception.
*/
public void setException(java.sql.SQLException v) {
this.exception = v;
}
private PreparedStatement pstmt = null;
/*
is this file xlsx or xls?
we detect this out of the filename extension
*/
private boolean xlsx = false;
private void checkXlsx(String fileName) {
String[] extension = fileName.split("\\.");
int l = extension.length - 1;
String fileType = extension[l].toLowerCase();
if ("xlsx".equals(fileType)) {
setXlsx(true);
}
}
/*
we need to check, if the extension of the Filename is either xls or xlsx if not,
we set to xlsx as default
*/
private String fixFileName(String f) {
String prefix = "", postfix = "";
String fixed = f;
int i = f.lastIndexOf(".");
// no postfix at all set
if (i < 0) {
fixed = f + ".xlsx";
} else {
prefix = f.substring(0, i);
postfix = f.substring(i + 1);
logger.log(Level.FINE, "Prefix: " + prefix + " Postfix: " + postfix);
if ((postfix.equalsIgnoreCase("xlsx")) || (postfix.equalsIgnoreCase("xls"))) {
// nothing to do
} else {
postfix = "xlsx";
}
fixed = prefix + "." + postfix;
}
logger.log(Level.INFO, "Filename: " + fixed);
return fixed;
}
/**
* Create the XLS-File named fileName
*
* @param fileName is the Name (incl. Path) of the XLS-file to create
*
*
*/
public int createXLS(String fileName) {
// I need to have a query to process
if ((getQuery() == null) && (getPstmt() == null)) {
logger.log(Level.WARNING, "Need to have a query to process");
return 0;
}
// I also need to have a file to write into
if (fileName == null) {
logger.log(Level.WARNING, "Need to know where to write into");
return 0;
}
fileName = fixFileName(fileName);
checkXlsx(fileName);
// I need to have a connection to the RDBMS
if (getCon() == null) {
logger.log(Level.WARNING, "Need to have a connection to process");
return 0;
}
//Statement stmt = null;
ResultSet resultSet = null;
ResultSetMetaData rsmd = null;
try {
// first we have to create the Statement
if (getPstmt() == null) {
pstmt = getCon().prepareStatement(getQuery());
}
//stmt = getCon().createStatement();
} catch (SQLException sqle1) {
setException(sqle1);
logger.log(Level.WARNING, "Can not create Statement. Message: "
+ sqle1.getMessage().toString());
return 0;
}
logger.log(Level.FINE, "FileName: " + fileName);
logger.log(Level.FINE, "Query : " + getQuery());
logger.log(Level.FINE, "Starting export...");
// create an empty sheet
Workbook wb;
Sheet sheet;
Sheet sqlsheet;
CreationHelper createHelper = null;
//XSSFSheet xsheet;
//HSSFSheet sheet;
if (isXlsx()) {
wb = new SXSSFWorkbook();
createHelper = wb.getCreationHelper();
} else {
wb = new HSSFWorkbook();
createHelper = wb.getCreationHelper();
}
sheet = wb.createSheet("Data Export");
// create a second sheet just containing the SQL Statement
sqlsheet = wb.createSheet("SQL Statement");
Row sqlrow = sqlsheet.createRow(0);
Cell sqltext = sqlrow.createCell(0);
try {
if ( getQuery() != null ) {
sqltext.setCellValue(getQuery());
} else {
sqltext.setCellValue(pstmt.toString());
}
} catch (Exception lex) {
}
CellStyle style = wb.createCellStyle();
style.setWrapText(true);
sqltext.setCellStyle(style);
Row r = null;
int row = 0; // row number
int col = 0; // column number
int columnCount = 0;
try {
//resultSet = stmt.executeQuery(getQuery());
resultSet = pstmt.executeQuery();
logger.log(Level.FINE, "query executed");
} catch (SQLException sqle2) {
setException(sqle2);
logger.log(Level.WARNING, "Can not execute query. Message: "
+ sqle2.getMessage().toString());
return 0;
}
// create Header in XLS-file
ArrayList<String> head = new ArrayList();
try {
rsmd = resultSet.getMetaData();
logger.log(Level.FINE, "Got MetaData of the resultset");
columnCount = rsmd.getColumnCount();
logger.log(Level.FINE, Integer.toString(columnCount)
+ " Columns in this resultset");
r = sheet.createRow(row); // titlerow
if ((!isXlsx()) && (columnCount > 255)) {
columnCount = 255;
}
for (int i = 0; i < columnCount; i++) {
// we create the cell
Cell cell = r.createCell(col);
// set the value of the cell
cell.setCellValue(rsmd.getColumnName(i + 1));
head.add(rsmd.getColumnName(i + 1));
// then we align center
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// now we make it bold
//HSSFFont f = wb.createFont();
Font headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(headerFont);
//cellStyle.setFont(f);
// adapt this font to the cell
cell.setCellStyle(cellStyle);
col++;
}
} catch (SQLException sqle3) {
setException(sqle3);
logger.log(Level.WARNING, "Can not create XLS-Header. Message: "
+ sqle3.getMessage().toString());
return 0;
}
// looping the resultSet
int wbCounter = 0;
try {
while (resultSet.next()) {
// this is the next row
col = 0; // put column counter back to 0 to start at the next row
row++; // next row
// create a new sheet if more then 60'000 Rows and xls file
if ((!isXlsx()) && (row % 65530 == 0)) {
wbCounter++;
row = 0;
sheet = wb.createSheet("Data Export " + Integer.toString(wbCounter));
logger.log(Level.INFO, "created a further page because of a huge amount of data");
// create the head
r = sheet.createRow(row); // titlerow
for (int i = 0; i < head.size(); i++) {
// we create the cell
Cell cell = r.createCell(col);
// set the value of the cell
cell.setCellValue((String) head.get(i));
// then we align center
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// now we make it bold
//HSSFFont f = wb.createFont();
Font headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(headerFont);
//cellStyle.setFont(f);
// adapt this font to the cell
cell.setCellStyle(cellStyle);
col++;
}
row++;
}
try {
r = sheet.createRow(row);
} catch (Exception e) {
logger.log(Level.WARNING, "Error while creating row number " + row + " " + e.getMessage());
wbCounter++;
row = 0;
sheet = wb.createSheet("Data Export " + Integer.toString(wbCounter));
logger.log(Level.WARNING, "created a further page in the hope it helps...");
// create the head
r = sheet.createRow(row); // titlerow
for (int i = 0; i < head.size(); i++) {
// we create the cell
Cell cell = r.createCell(col);
// set the value of the cell
cell.setCellValue((String) head.get(i));
// then we align center
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// now we make it bold
//HSSFFont f = wb.createFont();
Font headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(headerFont);
//cellStyle.setFont(f);
// adapt this font to the cell
cell.setCellStyle(cellStyle);
col++;
}
row++;
}
col = 0; // put column counter back to 0 to start at the next row
String previousMessage = "";
for (int i = 0; i < columnCount; i++) {
try {
// depending on the type, create the cell
switch (rsmd.getColumnType(i + 1)) {
case java.sql.Types.INTEGER:
r.createCell(col).setCellValue(resultSet.getInt(i + 1));
break;
case java.sql.Types.FLOAT:
r.createCell(col).setCellValue(resultSet.getFloat(i + 1));
break;
case java.sql.Types.DOUBLE:
r.createCell(col).setCellValue(resultSet.getDouble(i + 1));
break;
case java.sql.Types.DECIMAL:
r.createCell(col).setCellValue(resultSet.getFloat(i + 1));
break;
case java.sql.Types.NUMERIC:
r.createCell(col).setCellValue(resultSet.getFloat(i + 1));
break;
case java.sql.Types.BIGINT:
r.createCell(col).setCellValue(resultSet.getInt(i + 1));
break;
case java.sql.Types.TINYINT:
r.createCell(col).setCellValue(resultSet.getInt(i + 1));
break;
case java.sql.Types.SMALLINT:
r.createCell(col).setCellValue(resultSet.getInt(i + 1));
break;
case java.sql.Types.DATE:
// first we get the date
java.sql.Date dat = resultSet.getDate(i + 1);
java.util.Date date = new java.util.Date(dat.getTime());
r.createCell(col).setCellValue(date);
break;
case java.sql.Types.TIMESTAMP:
// first we get the date
java.sql.Timestamp ts = resultSet.getTimestamp(i + 1);
Cell c = r.createCell(col);
try {
c.setCellValue(ts);
// r.createCell(col).setCellValue(ts);
// Date Format
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/mm/dd hh:mm:ss"));
c.setCellStyle(cellStyle);
} catch (Exception e) {
c.setCellValue(" ");
}
break;
case java.sql.Types.TIME:
// first we get the date
java.sql.Time time = resultSet.getTime(i + 1);
r.createCell(col).setCellValue(time);
break;
case java.sql.Types.BIT:
boolean b1 = resultSet.getBoolean(i + 1);
r.createCell(col).setCellValue(b1);
break;
case java.sql.Types.BOOLEAN:
boolean b2 = resultSet.getBoolean(i + 1);
r.createCell(col).setCellValue(b2);
break;
case java.sql.Types.CHAR:
r.createCell(col).setCellValue(resultSet.getString(i + 1));
break;
case java.sql.Types.NVARCHAR:
r.createCell(col).setCellValue(resultSet.getString(i + 1));
break;
case java.sql.Types.VARCHAR:
try {
r.createCell(col).setCellValue(resultSet.getString(i + 1));
} catch (Exception e) {
r.createCell(col).setCellValue(" ");
logger.log(Level.WARNING, "Exception while writing column {0} row {3} type: {1} Message: {2}", new Object[]{col, rsmd.getColumnType(i + 1), e.getMessage(), row});
}
break;
default:
r.createCell(col).setCellValue(resultSet.getString(i + 1));
break;
}
} catch (Exception e) {
//e.printStackTrace();
if (resultSet.wasNull()) {
r.createCell(col).setCellValue(" ");
} else {
logger.log(Level.WARNING, "Unhandled type at column {0}, row {3} type: {1}. Filling up with blank {2}", new Object[]{col, rsmd.getColumnType(i + 1), e.getMessage(), row});
r.createCell(col).setCellValue(" ");
}
}
col++;
}
}
//pstmt.close();
} catch (SQLException sqle3) {
setException(sqle3);
logger.log(Level.WARNING, "Exception while writing data into sheet. Message: "
+ sqle3.getMessage().toString());
}
try {
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(fileName);
wb.write(fileOut);
fileOut.close();
logger.log(Level.INFO, "File created");
logger.log(Level.INFO, "Wrote: {0} lines into XLS-File", Integer.toString(row));
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while writing xls-File: " + e.getMessage().toString());
}
return row;
}
public XLSExport(Connection con) {
logger = Logger.getLogger("sql.fredy.sqltools");
setCon(con);
}
public XLSExport() {
logger = Logger.getLogger("sql.fredy.sqltools");
}
public static void main(String args[]) {
String host = "localhost";
String user = System.getProperty("user.name");
String schema = "%";
String database = null;
String password = null;
String query = null;
String file = null;
System.out.println("XLSExport\n"
+ "----------\n"
+ "Syntax: java sql.fredy.sqltools.XLSExport\n"
+ " Parameters: -h Host (default: localhost)\n"
+ " -u User (default: "
+ System.getProperty("user.name") + ")\n"
+ " -p Password\n"
+ " -q Query\n"
+ " -Q Filename of the file containing the Query\n"
+ " -d database\n"
+ " -f File to write into (.xls or xlsx)\n");
int i = 0;
while (i < args.length) {
if (args[i].equals("-h")) {
i++;
host = args[i];
}
if (args[i].equals("-u")) {
i++;
user = args[i];
}
if (args[i].equals("-p")) {
i++;
password = args[i];
}
if (args[i].equals("-d")) {
i++;
database = args[i];
}
if (args[i].equals("-q")) {
i++;
query = args[i];
}
if (args[i].equals("-Q")) {
i++;
sql.fredy.io.ReadFile rf = new sql.fredy.io.ReadFile(args[i]);
query = rf.getText();
}
if (args[i].equals("-f")) {
i++;
file = args[i];
}
i++;
};
t_connect tc = new t_connect(host, user, password, database);
XLSExport xe = new XLSExport(tc.con);
xe.setQuery(query);
xe.createXLS(file);
tc.close();
}
/**
* @return the xlsx
*/
public boolean isXlsx() {
return xlsx;
}
/**
* @param xlsx the xlsx to set
*/
public void setXlsx(boolean xlsx) {
this.xlsx = xlsx;
}
/**
* @return the pstmt
*/
public PreparedStatement getPstmt() {
return pstmt;
}
/**
* @param pstmt the pstmt to set
*/
public void setPstmt(PreparedStatement pstmt) {
this.pstmt = pstmt;
}
}
| hulmen/SQLAdmin | src/fredy/sqltools/XLSExport.java | Java | mit | 23,048 |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# 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.
"""
TODO...
"""
__all__ = ['GreedyPlayer']
import random
from jdhp.tictactoe.player.abstract import Player
class GreedyPlayer(Player):
"""
TODO...
"""
def play(self, game, state):
"""
TODO...
"""
action_list = game.getSetOfValidActions(state)
choosen_action = None
# Choose actions that lead to immediate victory...
for action in action_list:
next_state = game.nextState(state, action, self)
if game.hasWon(self, next_state):
choosen_action = action
break
# ... otherwise choose randomly
if choosen_action is None:
#print("randomly choose action") # debug
choosen_action = random.choice(action_list)
return choosen_action
| jeremiedecock/tictactoe-py | jdhp/tictactoe/player/greedy.py | Python | mit | 1,951 |
/*
* Copyright (c) 2015. Vin @ vinexs.com (MIT License)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.vinexs.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.LinearLayout;
@SuppressWarnings("unused")
public class ScalableLinearLayout extends LinearLayout {
private ScaleGestureDetector scaleDetector;
private float scaleFactor = 1.f;
private float maxScaleFactor = 1.5f;
private float minScaleFactor = 0.5f;
public ScalableLinearLayout(Context context) {
super(context);
scaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
public ScalableLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
scaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
// Let the ScaleGestureDetector inspect all events.
scaleDetector.onTouchEvent(event);
return true;
}
@Override
public void dispatchDraw(Canvas canvas) {
canvas.save();
canvas.scale(scaleFactor, scaleFactor);
super.dispatchDraw(canvas);
canvas.restore();
}
public ScalableLinearLayout setMaxScale(float scale) {
maxScaleFactor = scale;
return this;
}
public ScalableLinearLayout setMinScale(float scale) {
minScaleFactor = scale;
return this;
}
public ScaleGestureDetector getScaleGestureDetector() {
return scaleDetector;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(minScaleFactor, Math.min(scaleFactor, maxScaleFactor));
invalidate();
return true;
}
}
}
| vinexs/extend-enhance-base | eeb-core/src/main/java/com/vinexs/view/ScalableLinearLayout.java | Java | mit | 3,281 |
/* ******* TAGS ******* */
body {
margin: 0;
padding: 32px;
font-family: Arial, Helvetica, sans-serif;
font-size: 13px;
color: #333333;
}
/* ******* COMPONENTS ******* */
/* Gridlist */
.gridlist {
margin: 0;
}
.gridlist .control .icon {
vertical-align: top;
} | SerDIDG/BattlelogServersBlacklist | src/styles/options.css | CSS | mit | 293 |
//
// DRHMotorUnitData.h
// TAFPlotter
//
// Created by Lee Walsh on 9/01/2014.
// Copyright (c) 2014 Lee Walsh. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface DRHMotorUnitData : NSObject <NSCoding>{
NSNumber *unitNumber;
NSNumber *unitSet;
NSString *unitType;
NSNumber *onsetTime;
NSNumber *peakTime;
NSNumber *endTime;
NSNumber *inspTime;
NSNumber *onsetFreq;
NSNumber *peakFreq;
NSNumber *endFreq;
NSNumber *tonicFreq;
NSNumber *normOnsetTime;
NSNumber *normPeakTime;
NSNumber *normEndTime;
}
@property NSNumber *unitNumber;
@property NSNumber *unitSet;
@property NSString *unitType;
@property NSNumber *onsetTime;
@property NSNumber *peakTime;
@property NSNumber *endTime;
@property NSNumber *inspTime;
@property NSNumber *onsetFreq;
@property NSNumber *peakFreq;
@property NSNumber *endFreq;
@property NSNumber *tonicFreq;
@property NSNumber *normOnsetTime;
@property NSNumber *normPeakTime;
@property NSNumber *normEndTime;
-(DRHMotorUnitData *)initWith:(NSDictionary *)unitData;
+(DRHMotorUnitData *)unitWith:(NSDictionary *)unitData;
-(DRHMotorUnitData *)initBlank;
+(DRHMotorUnitData *)blankUnit;
@end
| Tanglo/TAFPLOTer | TAFPlotter/DRHMotorUnitData.h | C | mit | 1,203 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DollarTracker.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DollarTracker.Core")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4fa07611-8eb7-4660-826c-5ac7c85c07c8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| alphaCoder/DollarTracker | DollarTracker.Net/DollarTracker.Core/Properties/AssemblyInfo.cs | C# | mit | 1,412 |
__author__ = 'besta'
class BestaPlayer:
def __init__(self, fichier, player):
self.fichier = fichier
self.grille = self.getFirstGrid()
self.best_hit = 0
self.players = player
def getFirstGrid(self):
"""
Implements function to get the first grid.
:return: the grid.
"""
li = []
with open(self.fichier, 'r') as fi:
for line in fi.readlines():
li.append(line)
return li
def updateGrid(self):
"""
Implements function to update the grid to alter n-1
round values
"""
with open(self.fichier, 'r') as fi:
for line in fi.readlines():
i = 0
for car in line:
j = 0
if car != '\n':
self.grille[i][j] = car
j += 1
i += 1
def grilleEmpty(self):
"""
Implement function to check if the grid is empty.
"""
for line in self.grille:
for car in line[:len(line) - 1]:
if car != '0':
return False
return True
def checkLines(self, player, inARow):
"""
Implements function to check the current lines setup to evaluate best combinaison.
:param player: check for your numbers (your player number) or those of your opponent.
:param inARow: how many tokens in a row (3 or 2).
:return: true or false
"""
count = 0
flag = False
for line_number, line in enumerate(self.grille):
count = 0
for car_pos, car in enumerate(line[:len(line) - 1]):
if int(car) == player and not flag:
count = 1
flag = True
elif int(car) == player and flag:
count += 1
if count == inARow:
if car_pos - inARow >= 0 and self.canPlayLine(line_number, car_pos - inARow):
return True, car_pos - inARow
if car_pos + 1 <= 6 and self.canPlayLine(line_number, car_pos + 1):
return True, car_pos + 1
else:
count = 0
return False, 0
def canPlayLine(self, line, col):
"""
Function to check if we can fill the line with a token.
:param line: which line
:param col: which column
:return: true or false
"""
if line == 5:
return self.grille[line][col] == '0'
else:
return self.grille[line][col] == '0' and self.grille[line + 1][col] != '0'
def changeColumnInLines(self):
"""
Implements function to transform columns in lines to make tests eaiser.
:return: a reverse matrice
"""
column = []
for x in xrange(7):
col = ''
for y in xrange(6):
col += self.grille[y][x]
column.append(col)
return column
def checkColumns(self, player, inARow):
"""
Implements function to check the current columns setup to evaluate best combinaison.
:param player: check for your numbers (your player number) or those of your opponent.
:param inARow: how many tokens in a row (3 or 2).
:return: true or false
"""
column = self.changeColumnInLines()
count = 0
flag = False
for col_number, line in enumerate(column):
count = 0
for car_pos, car in enumerate(line):
if int(car) == player and not flag:
count = 1
flag = True
elif int(car) == player and flag:
count += 1
if count == inARow and car_pos - inARow >= 0 and self.grille[car_pos - inARow][col_number] == '0':
return True, col_number
else:
count = 0
return False, 0
def checkDiagonalLeftToRight(self, player, inARow):
"""
Implements function to check the current diagonal to evaluate best combinaison.
:param player: check for your numbers or opponent ones.
:param inARow: how many tokens in a row (3 or 2).
:return:
"""
x = 3
flag = False
while x < 6:
count = 0
x_int = x
y_int = 0
while x_int >= 0:
if int(self.grille[x_int][y_int]) == player and not flag:
count = 1
flag = True
elif int(self.grille[x_int][y_int]) == player and flag:
count += 1
if count == inARow and y_int + 1 <= 6 and x_int - 1 >= 0 and self.grille[x_int][y_int + 1] != '0':
return True, y_int + 1
else:
count = 0
flag = False
x_int -= 1
y_int += 1
x += 1
y = 1
flag = False
while y <= 3:
count = 0
x_int = 5
y_int = y
while y_int <= 6 and x_int >= 0:
if int(self.grille[x_int][y_int]) == player and not flag:
count = 1
flag = True
elif int(self.grille[x_int][y_int]) == player and flag:
count += 1
if count == inARow and y_int + 1 <= 6 and x_int - 1 >= 0 and self.grille[x_int][y + 1] != '0':
return True, y_int + 1
else:
count = 0
flage = False
x_int -= 1
y_int += 1
y += 1
return False, 0
def checkDiagonalRightToLeft(self, player, inARow):
"""
Implements function to check the current diagonal to evaluate best combinaison.
:param player: check for your numbers or opponent ones.
:param inARow: how many tokens in a row (3 or 2).
:return:
"""
x = 3
flag = False
while x < 6:
count = 0
x_int = x
y_int = 6
while x_int >= 0:
if int(self.grille[x_int][y_int]) == player and not flag:
count = 1
flag = True
elif int(self.grille[x_int][y_int]) == player and flag:
count += 1
if count == inARow and y_int - 1 >= 0 and x_int - 1 >= 0 and self.grille[x_int][y_int - 1] != '0':
return True, y_int - 1
else:
count = 0
flag = False
x_int -= 1
y_int -= 1
x += 1
y = 5
flag = False
while y <= 3:
count = 0
x_int = 5
y_int = y
while y_int >= 3 and x_int >= 0:
if int(self.grille[x_int][y_int]) == player and not flag:
count = 1
flag = True
elif int(self.grille[x_int][y_int]) == player and flag:
count += 1
if count == inARow and y_int - 1 >= 0 and x_int - 1 >= 0 and self.grille[x_int][y - 1] != '0':
return True, y_int - 1
else:
count = 0
flage = False
x_int -= 1
y_int -= 1
y -= 1
return False, 0
def checkDiagonals(self, player, inARow):
"""
Calls two diagonal functional.
:return: an int, representing the column where to play or 0 and False if there is no pattern search.
"""
check = self.checkDiagonalLeftToRight(player, inARow)
if check[0]:
return check
else:
return self.checkDiagonalRightToLeft(player, inARow)
def playSomeColumn(self, player, inARow):
"""
Call all function for a player and a number of tokens given.
:param player: which player
:param inARow: how many token
:return: true or false (col number if true)
"""
methods = {'checklines': self.checkLines, 'checkcolumn': self.checkColumns, 'checkdiagonal': self.checkDiagonals}
for key, function in methods.items():
which_col = function(player, inARow)
if which_col[0]:
return which_col
return False, 0
def findFirstColumnEmpty(self):
"""
Implements function to get the first column where a slot remain.
:return: the column
"""
for col in xrange(7):
if self.grille[0][col] == '0':
return col
return -1
def decideColumn(self):
"""
Implements main function : to decide what is the better hit to do.
:return: an int, representing the column where we play
"""
if self.grilleEmpty():
return 3
li_sequence = [3, 2, 1]
li_players = [self.players[0], self.players[1]]
for sequence in li_sequence:
for player in li_players:
choosen_col = self.playSomeColumn(player, sequence)
if choosen_col[0]:
return choosen_col[1]
return self.findFirstColumnEmpty()
| KeserOner/puissance4 | bestaplayer.py | Python | mit | 9,518 |
# Game Over screen.
class GameOver
def initialize(game)
end
def udpate
end
def draw
end
end | PhilCK/mermaid-game | game_over.rb | Ruby | mit | 102 |
Subsets and Splits