text:
layout: document
title: Stellungnahme Generalvikar Minifest
document_type: word
application: docs
folderish: false
parent: "MinistrantInnen-Fest vom 7. September 2014 in St. Gallen"
parentid: minifest
pinned: true
tile_size: 2.
document_creator: Liz Baker
document_creator_id: liz
---


text: Exercises from [Eloquent JavaScript](http://eloquentjavascript.net/) (third edition)

redpajama_set_name: RedPajamaGithub


text:
AliAnalysisTaskNetLambdaMCTrad *AddTaskNetLambdaMCTrad( Bool_t lSaveEventTree = kTRUE, Bool_t lSaveV0 = kTRUE, TString lExtraOptions = "", const TString lMasterJobSessionFlag = "")

{
    // Creates, configures and attaches to the train a cascades check task.
    // Get the pointer to the existing analysis manager via the static access method.
    //==============================================================================
    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        ::Error("AddTaskNetLambdaMCTrad", "No analysis manager to connect to.");
        return NULL;
    }

    // Check the analysis type using the event handlers connected to the analysis manager.
    //==============================================================================
    if (!mgr->GetInputEventHandler()) {
        ::Error("AddTaskNetLambdaMCTrad", "This task requires an input event handler");
        return NULL;
    }
    TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

    // Create and configure the task
    AliAnalysisTaskNetLambdaMCTrad *task = new AliAnalysisTaskNetLambdaMCTrad(lSaveEventTree, lSaveV0, "task", lExtraOptions);
    mgr->AddTask(task);
    TString outputFileName = AliAnalysisManager::GetCommonFileName();

//    outputFileName += ":PWGLF_StrVsMult";
//    if (mgr->GetMCtruthEventHandler()) outputFileName += "_MC";

    outputFileName = "Netlambdaresults.root";
//    Printf("Set OutputFileName : \n %s\n", outputFileName.Data() );

    AliAnalysisDataContainer *coutputList = mgr->CreateContainer("cList",
                                                                 TList::Class(),
                                                                 AliAnalysisManager::kOutputContainer,
                                                                 outputFileName );
//    AliAnalysisDataContainer *coutputListV0 = mgr->CreateContainer("cListV0",
//                                                                 TList::Class(),
//                                                                 AliAnalysisManager::kOutputContainer,
//                                                                 outputFileName );
//    AliAnalysisDataContainer *coutputListCascade = mgr->CreateContainer("cListCascade",
//                                                                 TList::Class(),
//                                                                 AliAnalysisManager::kOutputContainer,
//                                                                 outputFileName );
//    if( lSaveEventTree ){
//        AliAnalysisDataContainer *coutputTree = mgr->CreateContainer("cTreeEvent",
//                                                                     TTree::Class(),
//                                                                     AliAnalysisManager::kOutputContainer,
//                                                                     outputFileName );
//        coutputTree->SetSpecialOutput();
//    }
//    if( lSaveV0 ){
//        AliAnalysisDataContainer *coutputTreeV0 = mgr->CreateContainer("cTreeV0",
//                                                                       TTree::Class(),
//                                                                       AliAnalysisManager::kOutputContainer,
//                                                                       outputFileName );
//        coutputTreeV0->SetSpecialOutput();
//    }
//    if (lSaveCascade){
//        AliAnalysisDataContainer *coutputTreeCascade = mgr->CreateContainer("cTreeCascade",
//                                                                            TTree::Class(),
//                                                                            AliAnalysisManager::kOutputContainer,
//                                                                            outputFileName );
//        coutputTreeCascade->SetSpecialOutput();
//    }
    //This one you should merge in file-resident ways...

    //Recommendation: Tree as a single output slot
    mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(task, 1, coutputList);
//    mgr->ConnectOutput(task, 2, coutputListV0);
//    mgr->ConnectOutput(task, 3, coutputListCascade);
//
//    if ( lSaveEventTree ) mgr->ConnectOutput(task, 4, coutputTree);
//    if ( lSaveV0 )        mgr->ConnectOutput(task, 5, coutputTreeV0);
//    if ( lSaveCascade )   mgr->ConnectOutput(task, 6, coutputTreeCascade);

    return task;
}


text: build my own App


text:
from django.db import models

class User(models.Model):
    email = models.CharField(max_length=255)
    name = models.CharField(max_length=255)

    USERNAME_FIELD = 'email'


text:
//
// FindBar.cs
//
// Author:
//   Gabriel Burt <gabriel.burt@gmail.com>
//   Daniel Köb <daniel.koeb@peony.at>
//   Stephane Delcroix <sdelcroix@src.gnome.org>
//
// Copyright (C) 2007-2010 Novell, Inc.
// Copyright (C) 2007 Gabriel Burt
// Copyright (C) 2010 Daniel Köb
// Copyright (C) 2007-2008 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Text;
using System.Text.RegularExpressions;

using Gtk;

using Mono.Unix;

using FSpot.Core;
using FSpot.Query;

using Hyena;

namespace FSpot.Widgets {
	public class FindBar : HighlightedBox {
		private Entry entry;
		private string last_entry_text = String.Empty;
		private int open_parens = 0, close_parens = 0;
		private PhotoQuery query;
		private Term root_term = null;
		private HBox box;

		/*
		 * Properties
		 */
		public bool Completing {
			get {
				return (entry.Completion as LogicEntryCompletion).Completing;
			}
		}

		public Gtk.Entry Entry {
			get { return entry; }
		}

		public Term RootTerm  {
			get { return root_term; }
		}

		/*
		 * Constructor
		 */
		public FindBar (PhotoQuery query, TreeModel model) : base(new HBox())
		{
			this.query = query;
			box = Child as HBox;

			box.Spacing = 6;
			box.BorderWidth = 2;

			box.PackStart (new Label (Catalog.GetString ("Find:")), false, false, 0);

			entry = new Entry ();
			entry.Completion = new LogicEntryCompletion (entry, model);

			entry.TextInserted  += HandleEntryTextInserted;
			entry.TextDeleted   += HandleEntryTextDeleted;
			entry.KeyPressEvent += HandleEntryKeyPress;

			box.PackStart (entry, true, true, 0);

			Button clear_button = new Gtk.Button ();
			clear_button.Add (new Gtk.Image ("gtk-close", Gtk.IconSize.Button));
			clear_button.Clicked += HandleCloseButtonClicked;
			clear_button.Relief = Gtk.ReliefStyle.None;
			box.PackStart (clear_button, false, false, 0);
		}

		/*
		 * Event Handlers
		 */

		private void HandleCloseButtonClicked (object sender, EventArgs args)
		{
			Clear ();
		}

		private void HandleEntryTextInserted (object sender, TextInsertedArgs args)
		{
			//Log.DebugFormat ("inserting {0}, ( = {1}  ) = {2}", args.Text, open_parens, close_parens);

			//int start = args.Position - args.Length;

			for (int i = 0; i < args.Text.Length; i++) {
				char c = args.Text [i];
				if (c == '(')
					open_parens++;
				else if (c == ')')
					close_parens++;
			}

			int pos = entry.Position + 1;
			int close_parens_needed = open_parens - close_parens;
			for (int i = 0; i < close_parens_needed; i++) {
				entry.TextInserted -= HandleEntryTextInserted;
				entry.InsertText (")", ref pos);
				close_parens++;
				entry.TextInserted += HandleEntryTextInserted;
				pos++;
			}
			//Log.DebugFormat ("done w/ insert, {0}, ( = {1}  ) = {2}", args.Text, open_parens, close_parens);
			last_entry_text = entry.Text;

			QueueUpdate ();
		}

		private void HandleEntryTextDeleted (object sender, TextDeletedArgs args)
		{
			int length = args.EndPos - args.StartPos;
			//Log.DebugFormat ("start {0} end {1} len {2} last {3}", args.StartPos, args.EndPos, length, last_entry_text);
			string txt = length < 0 ? last_entry_text : last_entry_text.Substring (args.StartPos, length);

			for (int i = 0; i < txt.Length; i++) {
				if (txt [i] == '(')
					open_parens--;
				else if (txt [i] == ')')
					close_parens--;
			}

			last_entry_text = entry.Text;

			QueueUpdate ();
		}

		private void HandleEntryKeyPress (object sender, KeyPressEventArgs args)
		{
			//bool shift = ModifierType.ShiftMask == (args.Event.State & ModifierType.ShiftMask);

			switch (args.Event.Key) {
			case (Gdk.Key.Escape):
				Clear ();
				args.RetVal = true;
				break;

			case (Gdk.Key.Tab):
				// If we are at the end of the entry box, let the normal Tab handler do its job
				if (entry.Position == entry.Text.Length) {
					args.RetVal = false;
					return;
				}

				// Go until the current character is an open paren
				while (entry.Position < entry.Text.Length && entry.Text [entry.Position] != '(')
					entry.Position++;

				// Put the cursor right after the open paren
				entry.Position++;

				args.RetVal = true;
				break;

			default:
				args.RetVal = false;
				break;
			}
		}

		/*
		 * Helper methods.
		 */

		private void Clear ()
		{
			entry.Text = String.Empty;
			Hide ();
		}

		// OPS The operators we support, case insensitive
		//private static string op_str = "(?'Ops' or | and |, | \\s+ )";
		private static string op_str = "(?'Ops' "+ Catalog.GetString ("or") + " | "+ Catalog.GetString ("and")  + " |, )";

		// Match literals, eg tags or other text to search on
		private static string literal_str = "[^{0}{1}]+?";
		//private static string not_literal_str = "not\\s*\\((?'NotTag'[^{0}{1}]+)\\)";

		// Match a group surrounded by parenthesis and one or more terms separated by operators
		private static string term_str = "(((?'Open'{0})(?'Pre'[^{0}{1}]*?))+((?'Close-Open'{1})(?'Post'[^{0}{1}]*?))+)*?(?(Open)(?!))";

		// Match a group surrounded by parenthesis and one or more terms separated by operators, surrounded by not()
		//private static string not_term_str = String.Format("not\\s*(?'NotTerm'{0})", term_str);

		// Match a simple term or a group term or a not(group term)
		//private static string comb_term_str = String.Format ("(?'Term'{0}|{2}|{1})", simple_term_str, term_str, not_term_str);
		private static string comb_term_str = String.Format ("(?'Term'{0}|{1})|not\\s*\\((?'NotTerm'{0})\\)|not\\s*(?'NotTerm'{1})", literal_str, term_str);

		// Match a single term or a set of terms separated by operators
		private static string regex_str = String.Format ("^((?'Terms'{0}){1})*(?'Terms'{0})$", comb_term_str, op_str);

		private static Regex term_regex = new Regex (
							  String.Format (regex_str, "\\(", "\\)"),
							  RegexOptions.IgnoreCase | RegexOptions.Compiled
						  );

		// Breaking the query the user typed into something useful involves running
		// it through the above regular expression recursively until it is broken down
		// into literals and operators that we can use to generate SQL queries.
		private bool ConstructQuery (Term parent, int depth, string txt)
		{
			return ConstructQuery(parent, depth, txt, false);
		}

		private bool ConstructQuery (Term parent, int depth, string txt, bool negated)
		{
			if (string.IsNullOrEmpty(txt))
				return true;

			string indent = String.Format ("{0," + depth*2 + "}", " ");

			//Log.DebugFormat (indent + "Have text: {0}", txt);

			// Match the query the user typed against our regular expression
			Match match = term_regex.Match (txt);

			if (!match.Success) {
				//Log.Debug (indent + "Failed to match.");
				return false;
			}

			bool op_valid = true;
			string op = String.Empty;

			// For the moment at least we don't support operator precedence, so we require
			// that only a single operator is used for any given term unless it is made unambiguous
			// by using parenthesis.
			foreach (Capture capture in match.Groups ["Ops"].Captures) {
				if (op == String.Empty)
					op = capture.Value;
				else if (op != capture.Value) {
					op_valid = false;
					break;
				}
			}

			if (!op_valid) {
				Log.Information (indent + "Ambiguous operator sequence.  Use parenthesis to explicitly define evaluation order.");
				return false;
			}

			if (match.Groups ["Terms"].Captures.Count == 1 && match.Groups["NotTerm"].Captures.Count != 1) {
				//Log.DebugFormat (indent + "Unbreakable term: {0}", match.Groups ["Terms"].Captures [0]);
				string literal;
				bool is_negated = false;
				Tag tag = null;

				if (match.Groups ["NotTag"].Captures.Count == 1) {
					literal = match.Groups ["NotTag"].Captures [0].Value;
					is_negated = true;
				} else {
					literal = match.Groups ["Terms"].Captures [0].Value;
				}

				is_negated = is_negated || negated;

				tag = App.Instance.Database.Tags.GetTagByName (literal);

				// New OR term so we can match against both tag and text search
				parent = new OrTerm(parent, null);

				// If the literal is the name of a tag, include it in the OR
				//AbstractLiteral term = null;
				if (tag != null) {
					new Literal (parent, tag, null);
				}

				// Always include the literal text in the search (path, comment, etc)
				new TextLiteral (parent, literal);

				// If the term was negated, negate the OR parent term
				if (is_negated) {
					parent = parent.Invert(true);
				}

				if (RootTerm == null)
					root_term = parent;

				return true;
			} else {
				Term us = null;
				if (op != null && op != String.Empty) {
					us = Term.TermFromOperator (op, parent, null);
					if (RootTerm == null)
						root_term = us;
				}

				foreach (Capture capture in match.Groups ["Term"].Captures) {
					string subterm = capture.Value.Trim ();

					if (subterm == null || subterm.Length == 0)
						continue;

					// Strip leading/trailing parens
					if (subterm [0] == '(' && subterm [subterm.Length - 1] == ')') {
						subterm = subterm.Remove (subterm.Length - 1, 1);
						subterm = subterm.Remove (0, 1);
					}

					//Log.DebugFormat (indent + "Breaking subterm apart: {0}", subterm);

					if (!ConstructQuery (us, depth + 1, subterm, negated))
						return false;
				}

				foreach (Capture capture in match.Groups ["NotTerm"].Captures) {
					string subterm = capture.Value.Trim ();

					if (subterm == null || subterm.Length == 0)
						continue;

					// Strip leading/trailing parens
					if (subterm [0] == '(' && subterm [subterm.Length - 1] == ')') {
						subterm = subterm.Remove (subterm.Length - 1, 1);
						subterm = subterm.Remove (0, 1);
					}

					//Log.DebugFormat (indent + "Breaking not subterm apart: {0}", subterm);

					if (!ConstructQuery (us, depth + 1, subterm, true))
						return false;
				}

				if (negated && us != null) {
					if (us == RootTerm)
						root_term = us.Invert(false);
					else
						us.Invert(false);
				}

				return true;
			}
		}

		private bool updating = false;
		private uint update_timeout_id = 0;
		private void QueueUpdate ()
		{
			if (updating || update_timeout_id != 0) {
				lock(this) {
					// If there is a timer set and we are not yet handling its timeout, then remove the timer
					// so we delay its trigger for another 500ms.
					if (!updating && update_timeout_id != 0)
						GLib.Source.Remove (update_timeout_id);

					// Assuming we're not currently handling a timeout, add a new timer
					if (!updating)
						update_timeout_id = GLib.Timeout.Add(500, OnUpdateTimer);
				}
			} else {
				// If we are not updating and there isn't a timer already set, then there is
				// no risk of race condition with the  timeout handler.
				update_timeout_id = GLib.Timeout.Add(500, OnUpdateTimer);
			}
		}

		private bool OnUpdateTimer ()
		{
			lock(this) {
				updating = true;
			}

			Update();

			lock(this) {
				updating = false;
				update_timeout_id = 0;
			}

			return false;
		}

		private void Update ()
		{
			// Clear the last root term
			root_term = null;

			if (ParensValid () && ConstructQuery (null, 0, entry.Text)) {
				if (RootTerm != null) {
					//Log.DebugFormat("rootTerm = {0}", RootTerm);
					if (!(RootTerm is AndTerm)) {
						// A little hacky, here to make sure the root term is a AndTerm which will
						// ensure we handle the Hidden tag properly
						AndTerm root_parent = new AndTerm(null, null);
						RootTerm.Parent = root_parent;
						root_term = root_parent;
					}

					//Log.DebugFormat("rootTerm = {0}", RootTerm);
					if (!(RootTerm is AndTerm)) {
						// A little hacky, here to make sure the root term is a AndTerm which will
						// ensure we handle the Hidden tag properly
						AndTerm root_parent = new AndTerm(null, null);
						RootTerm.Parent = root_parent;
						root_term = root_parent;
					}
					//Log.DebugFormat ("condition = {0}", RootTerm.SqlCondition ());
					query.TagTerm = new ConditionWrapper (RootTerm.SqlCondition ());
				} else {
					query.TagTerm = null;
					//Log.Debug ("root term is null");
				}
			}
		}

		private bool ParensValid ()
		{
			for (int i = 0; i < entry.Text.Length; i++) {
				if (entry.Text [i] == '(' || entry.Text [i] == ')') {
					int pair_pos = ParenPairPosition (entry.Text, i);

					if (pair_pos == -1)
						return false;
				}
			}

			return true;
		}

		/*
		 * Static Utility Methods
		 */
		private static int ParenPairPosition (string txt, int pos)
		{
			char one = txt [pos];
			bool open = (one == '(');
			char two = (open) ? ')' : '(';

			//int level = 0;
			int num = (open) ? txt.Length - pos - 1: pos;

			int sames = 0;
			for (int i = 0; i < num; i++) {
				if (open)
					pos++;
				else
					pos--;

				if (pos < 0 || pos > txt.Length - 1)
					return -1;

				if (txt [pos] == one)
					sames++;
				else if (txt [pos] == two) {
					if (sames == 0)
						return pos;
					sames--;
				}
			}

			return -1;
		}

		/*private static string ReverseString (string txt)
		{
		    char [] txt_a = txt.ToCharArray ();
		    System.Reverse (txt_a);
		    return new String (txt_a);
		}*/
	}

	public class LogicEntryCompletion : EntryCompletion {
		private Entry entry;

		private bool completing = false;
		public bool Completing {
			get { return completing; }
		}

		public LogicEntryCompletion (Entry entry, TreeModel tree_model)
		{
			this.entry = entry;

			Model = new DependentListStore(tree_model);

			InlineCompletion = false;
			MinimumKeyLength = 1;
			TextColumn = 1;
			PopupSetWidth = false;
			MatchFunc = LogicEntryCompletionMatchFunc;
			MatchSelected += HandleMatchSelected;

			// Insert these when appropriate..
			//InsertActionText (0, "or");
			//InsertActionText (1, "and");
			// HandleAction...
		}

		[GLib.ConnectBefore]
		private void HandleMatchSelected (object sender, MatchSelectedArgs args)
		{
			string name = args.Model.GetValue (args.Iter, TextColumn) as string;
			//Log.DebugFormat ("match selected..{0}", name);

			int pos = entry.Position;
			string updated_text = completion_logic.ReplaceKey (entry.Text, name, ref pos);

			completing = true;
			entry.Text = updated_text;
			entry.Position = pos;
			completing = false;

			args.RetVal = true;
			//Log.Debug ("done w/ match selected");
		}

		private CompletionLogic completion_logic = new CompletionLogic ();
		public bool LogicEntryCompletionMatchFunc (EntryCompletion completion, string key, TreeIter iter)
		{
			if (Completing)
				return false;

			key = key == null ? null : key.Normalize(NormalizationForm.FormC);
			string name = completion.Model.GetValue (iter, completion.TextColumn) as string;
			int pos = entry.Position - 1;
			return completion_logic.MatchFunc (name, key, pos);
		}
	}

	public class CompletionLogic
	{
		string last_key = String.Empty;
		string transformed_key = String.Empty;
		int start = 0;

		private static string or_op = " " + Catalog.GetString ("or") + " ";
		private static string and_op = " " + Catalog.GetString ("and") + " ";

		private static int or_op_len = or_op.Length;
		private static int and_op_len = and_op.Length;

		public bool MatchFunc (string name, string key, int pos)
		{
			// If this is the fist comparison for this key, convert the key (which is the entire search string)
			// into just the part that is relevant to completing this tag name.
			if (key != last_key) {
				last_key = key;

				if (key == null || key.Length == 0 || pos < 0 || pos > key.Length - 1)
					transformed_key = String.Empty;
				else if (key [pos] == '(' || key [pos] == ')' || key [pos] == ',')
					transformed_key = String.Empty;
				else {
					start = 0;
					for (int i = pos; i >= 0; i--) {
						if (key [i] == ')' || key [i] == '(' ||
						   (i >= and_op_len - 1 && String.Compare (key.Substring (i - and_op_len + 1, and_op_len), and_op, true) == 0) ||
						   (i >= or_op_len - 1 && String.Compare (key.Substring (i - or_op_len + 1, or_op_len), or_op, true) == 0)) {
							//Log.DebugFormat ("have start break char at {0}", i);
							start = i + 1;
							break;
						}
					}

					int end = key.Length - 1;
					for (int j = pos; j < key.Length; j++) {
						if (key [j] == ')' || key [j] == '(' ||
						   (key.Length >= j + and_op_len && String.Compare (key.Substring (j, and_op_len), and_op, true) == 0) ||
						   (key.Length >= j + or_op_len && String.Compare (key.Substring (j, or_op_len), or_op, true) == 0)) {
							end = j - 1;
							break;
						}
					}

					//Log.DebugFormat ("start = {0} end = {1}", start, end);

					int len = end - start + 1;
					if (len > 0 && start < last_key.Length)
						transformed_key = last_key.Substring (start, end - start + 1);
					else
						transformed_key = String.Empty;
				}
				//Log.DebugFormat ("transformed key {0} into {1}", key, transformed_key);
			}

			if (transformed_key == String.Empty)
				return false;

			// Ignore null or names that are too short
			if (name == null || name.Length <= transformed_key.Length)
				return false;

			//Log.DebugFormat ("entered = {0} compared to {1}", transformed_key, name);

			// Try to match key and name case insensitive
			if (String.Compare (transformed_key, name.Substring (0, transformed_key.Length), true) == 0) {
				return true;
			}

			// Try to match with diacritics removed from name
			string simplified_name = StringUtil.SearchKey (name.Substring (0, transformed_key.Length));
			//Log.DebugFormat ("entered = {0} compared to {1}", transformed_key, simplified_name);
			return (String.Compare (transformed_key, simplified_name, true) == 0);
		}

		public string ReplaceKey (string query, string name, ref int pos)
		{
			// do some sanity checks first
			if (start > query.Length) {
				Log.Error ("ReplaceKey: start > query.length");
				return query;
			}
			// move caret after inserted name, even if it was not
			// at the end of the key
			pos = start + name.Length;
			return query.Substring (0, start) + name + query.Substring (start + transformed_key.Length);
		}
	}
}


text:
<!doctype html>

    <title>Code coverage report for modules/slider/Slider.vue</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / modules/slider/ Slider.vue

        47.62%
        Statements
        20/42

        62.5%
        Branches
        10/16

        75%
        Functions
        9/12

        42.86%
        Lines
        15/35

        1 branch
        Ignored

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203

1×
1×

8×

8×

8×
8×

8×

8×
8×
8×
8×

7×

8×

8×

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//

/**
 * @class Slider
 * @module 操作类组件
 * @extends Base
 * @Constructor
 * @since 0.0.1
 * @demo slider|slider.vue
 * @show true
 */
import SwBase from '../Base.vue'
import SwDrag from '../drag/Drag.vue'
export default {
    name: 'SwSlider',
    extends: SwBase,
    components: {SwDrag},
    data(){
        return {
            showTipMode: this.tipMode === 'default',
            currentProgress: this.progress || this.range[0],
            tipVisible: this.tipStay || false
        }
    },
    methods:{
        handleDrag(position){
            let newProgress, nowSec

            this.preX = position.start.x
            this.X = position.move.x
            this.distance = this.X - this.preX

            this.prevProgressWidth = this.newProgressWidth + this.distance

            if(this.prevProgressWidth <= 0) this.prevProgressWidth = 0
            if(this.prevProgressWidth >= this.sliderLength) this.prevProgressWidth = this.sliderLength
            nowSec = Math.round(this.prevProgressWidth / this.eachSection, 0)
            this.prevProgressWidth = this.eachSection * nowSec

            newProgress = this.prevProgressWidth/this.sliderLength * this.rangeDiff + this.range[0]

            this.setSliderPosition(this.prevProgressWidth + 'px')

            this.tipVisible = true
            this.currentProgress = parseInt(newProgress)
        },
        handleDrop(){
            if(!this.tipStay){
                this.tipVisible = false
            }
            this.newProgressWidth = this.prevProgressWidth
            this.$emit('slide-end',this.currentProgress)
        },
        getNewProgressWidth(currentProgress){ // 保留2位小数
            return this.sliderLength * (Math.round((currentProgress-this.range[0])/this.rangeDiff*100)/100)
        },
        setSliderPosition(distance){
            this.$refs.sliderProgress.style.width = distance
            this.$refs.sliderBtn.style.left = distance
        }
    },
    computed:{
        rangeDiff(){
            return this.range[1]-this.range[0]
        }
    },
    mounted(){
        this.sliderLength = parseInt(this.$refs.sliderLine.offsetWidth)
        this.eachSection = this.sliderLength/this.rangeDiff * this.duration
        this.newProgressWidth = this.getNewProgressWidth(this.currentProgress)
        this.setSliderPosition(this.newProgressWidth + 'px')
    },
    watch: {
        progress(val){
            this.currentProgress = val
            this.newProgressWidth = this.getNewProgressWidth(val)
            this.setSliderPosition(this.newProgressWidth + 'px')
        }
    },
    props:{
        /**
         * 样式前缀
         * @property classPrefix
         * @type String
         * @default 'slider'
         * */
        classPrefix: {
            type: String,
            default: 'slider'
        },
        /**
         * 初始进度
         * @property progress
         * @type Number
         * @default 0
         * */
        progress: {
            type: Number,
            default: 0
        },
        /**
         * 进度提示的位置
         * @property placement
         * @type String
         * @default 'top'
         * */
        placement: {
            type: String,
            default: 'top'
        },
        /**
         * 范围,可传固定范围的数组如:[25,50]
         * @property range
         * @type Array
         * @default [0,100]
         * */
        range: {
            type: Array,
            default: function () {
                return [0,100]
            },
            validator(val){
                return val.length === 2 && val[0] <= val[1]
            }
        },
        /**
         * 是否在进度条前后显示范围
         * @property showRange
         * @type Boolean
         * @default false
         * */
        showRange: {
            type: Boolean,
            default: false
        },
        /**
         * 显示提示的模式,可选[default,tooltip]
         * @property tipMode
         * @type String
         * @default 'default'
         * */
        tipMode: {
            type: String,
            default: 'default'
        },
        /**
         * 每次移动的固定距离
         * @property duration
         * @type Number
         * @default 1
         * */
        duration: {
            type: Number,
            default: 1
        },
        /**
         * 初始及松开按钮时是否显示tooltip
         * @property tipStay
         * @type Boolean
         * @default false
         * */
        tipStay: {
            type: Boolean,
            default: false
        },
        /**
         * 进度条是否只读
         * @property disabled
         * @type Boolean
         * @default false
         * */
        disabled: Boolean,
        classMapping: {
            type: Object,
            default: function() {
                return {
                    'disabled': 'disabled',
                    'top': 'tip-top',
                    'bottom': 'tip-bottom'
                }
            }
        }

    }
}

  Code coverage
  generated by istanbul at Tue Aug 08 2017 11:52:03 GMT+0800 (CST)


text:
'''
New Test For rootvolume bill spending check
@author Zhaohao
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.billing_operations as bill_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.vm_operations as vm_ops
import zstackwoodpecker.operations.net_operations as net_ops
import threading
import random
import time
import os

test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_state.TestStateDict()
vm = None
billing_resource = 'rootvolume'
offset_unit_dict=['sec','min','hou','day','week','month','year']
time_unit_dict=['s','m','h','d','w','mon']
resource_unit_dict={"M":1024 * float(1024), "G":1024**2 * float(1024), "T":1024**3 * float(1024)}
vm_max = 10
round_max = 10
round_sum = vm_max * round_max
def test():
	# test_stub.update_billing_symbol()
	success_round = 0
	for i in range(0,vm_max):
		test_util.test_logger("clear data in RootVolumeUsageVO and PriceVO")
		test_stub.resource_price_clear(billing_resource)
		test_util.test_logger("=====SPENDING CHECK VM %s=====" % str(i+1))
		bill_rootvolume = test_stub.RootVolumeBilling()
		time_unit = random.choice(time_unit_dict)
		price = str(random.randint(0,9999))
		resource_unit = random.choice(resource_unit_dict.keys())
        	bill_rootvolume.set_timeUnit(time_unit)
		bill_rootvolume.set_price(price)
		bill_rootvolume.set_resourceUnit(resource_unit)
		test_util.test_logger("create rootvolume billing\n price=%s, timeUnit=%s, resourceUnit=%s" % (price, time_unit, resource_unit))
		bill_rootvolume.create_resource_type()

		test_util.test_logger("create vm instance")
		global vm
        	vm = test_stub.create_vm_billing("test_vmm", test_stub.set_vm_resource()[0], None,\
							test_stub.set_vm_resource()[1], test_stub.set_vm_resource()[2])

		rootVolumeSize = res_ops.query_resource(res_ops.VM_INSTANCE, \
					res_ops.gen_query_conditions('uuid', '=',\
					                        vm.get_vm().uuid))[0].allVolumes[0].size / resource_unit_dict[resource_unit]
		test_util.test_logger("@@@@debug %s %s" %(resource_unit, rootVolumeSize))

		test_util.test_logger("====check vm spending====")
		for r in range(0,round_max):
			test_util.test_logger("===spending check round %s-%s===" % (str(i+1), str(r+1)))
			if test_stub.check(bill_rootvolume, billing_resource, random.choice(offset_unit_dict), random.randint(0,3), rootVolumeSize):
				success_round += 1
			else:
				test_util.test_fail("check vm billing spending finished\n success: %s/%s" % (success_round, round_sum))
	test_util.test_pass("check root volume billing finished\n success: %s/%s" % (success_round,round_sum))

def error_cleanup():
	global vm
	if vm:
		vm.clean()

def env_recover():
	global vm
	if vm:
		vm.clean()
	resourcePrices = test_stub.query_resource_price()
	if resourcePrices:
		for resourceprice in resourcePrices:
			test_stub.delete_price(resourceprice.uuid)


text:
package net.malisis.core.client.gui;

/**
 * @author Ordinastie
 *
 */
public enum ComponentPosition
{
	TOP(true), RIGHT(false), LEFT(false), BOTTOM(true);

	private boolean horizontal;

	private ComponentPosition(boolean horizontal)
	{
		this.horizontal = horizontal;
	}

	public boolean isHorizontal()
	{
		return horizontal;
	}

	public boolean isVertical()
	{
		return !horizontal;
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phyllosticta coralliobola Bubák & Kabát

### Remarks
null


text:
const path = require('path')
const spawnSync = require('child_process').spawnSync || require('spawn-sync')

exports.get = function get (algo, seed, p, count) {
  const args = [algo]

  const buffer = Buffer.allocUnsafe(8)
  for (let i = 0; i < seed.length; i += 2) {
    buffer.writeUInt32BE(seed[i], 0)
    buffer.writeUInt32BE(seed[i + 1], 4)
    args.push(buffer.toString('hex'))
  }

  if (p) args.push(p.toString(10))
  args.push(count.toString(10))

  const data = spawnSync(path.join(__dirname, 'xorshift'), args)
  if (data.error) throw data.error

  return Buffer.from(data.stdout.toString().slice(0, -1), 'hex') // cut \n
}


text:
/* 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.
 */

package com.camunda.bpm.demo.async_on_error;

import java.util.List;

import javax.inject.Named;

import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.engine.impl.ManagementServiceImpl;
import org.camunda.bpm.engine.impl.ProcessInstantiationBuilderImpl;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandExecutor;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.runtime.ProcessInstanceWithVariables;
import org.camunda.bpm.engine.runtime.ProcessInstantiationBuilder;

/**
 * @author Falko Menge
 */
@Named
public class AsyncOnError {

  public AsyncOnErrorActivityBehavior getAsyncOnErrorActivityBehavior(JavaDelegate delegate) {
    return new AsyncOnErrorActivityBehavior(delegate);
  }

  public static ProcessInstanceWithVariables startProcessInstance(ProcessEngine processEngine, ProcessInstantiationBuilder processInstantiationBuilder) {
    // ensure we are not participating in any open TX, which would be marked for rollback only by exceptions
    CommandExecutor commandExecutor = getCommandExecutorTxRequiresNew(processEngine);

    // start process and suspend jobs created at start
    Command<ProcessInstanceWithVariables> cmd = new StartProcessInstanceAndSuspendJobsCmd((ProcessInstantiationBuilderImpl) processInstantiationBuilder);
    ProcessInstanceWithVariables processInstance = commandExecutor.execute(cmd);

    // initialize ManagementService to enforce new TX
    ManagementServiceImpl managementService = getManagementService(commandExecutor);
    // query jobs
    List<Job> jobs = managementService.createJobQuery()
      .processInstanceId(processInstance.getId())
      .suspended()
      .list();
    for (Job job : jobs) {
      try {
        // try to run jobs synchronously
        managementService.executeJob(job.getId());
      } catch (Exception e) {
        // if it fails hand over to Job Executor to retry asynchronously
        managementService.activateJobById(job.getId());
      }
    }
    return processInstance;
  }

  private static ManagementServiceImpl getManagementService(CommandExecutor commandExecutor) {
    ManagementServiceImpl managementService = new ManagementServiceImpl();
    managementService.setCommandExecutor(commandExecutor);
    return managementService;
  }

  private static CommandExecutor getCommandExecutorTxRequiresNew(ProcessEngine processEngine) {
    return ((ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration()).getCommandExecutorTxRequiresNew();
  }

}


text:
package sdk

// DefaultValues contains default user values for init DB
type DefaultValues struct {
	DefaultGroupName string
}

// ConfigUser struct.
type ConfigUser struct {
	URLUI  string `json:"url.ui"`
	URLAPI string `json:"url.api"`
}

type APIConfig struct {
	DefaultRunRetentionPolicy string `json:"default_run_retention_policy"`
}

type TCPServer struct {
	Addr               string `toml:"addr" default:"" comment:"Listen address without port, example: 127.0.0.1" json:"addr"`
	Port               int    `toml:"port" default:"8090" json:"port"`
	GlobalTCPRateLimit int64  `toml:"globalTCPRateLimit" default:"2097152" comment:"Rate limit (B/s) for incoming logs" json:"globalTCPRateLimit"`
}


text:
<?php

namespace AwesomeBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Message
 *
 * @ORM\Table(name="messages")
 * @ORM\Entity(repositoryClass="AwesomeBundle\Repository\MessageRepository")
 */
class Message
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="content", type="string", length=255)
     */
    private $content;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime")
     */
    private $created;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated", type="datetime")
     */
    private $updated;

    /**
     * @ORM\ManyToOne(targetEntity="Ticket", cascade={"persist"})
     * @ORM\JoinColumn(name="ticket_id", referencedColumnName="id", nullable=false)
     */
    private $ticket;

    /**
     * @ORM\ManyToOne(targetEntity="User", cascade={"persist"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $user;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set content
     *
     * @param string $content
     *
     * @return Message
     */
    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * Get content
     *
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     *
     * @return Message
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     *
     * @return Message
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Set ticket
     *
     * @param \AwesomeBundle\Entity\Ticket $ticket
     *
     * @return Message
     */
    public function setTicket(\AwesomeBundle\Entity\Ticket $ticket = null)
    {
        $this->ticket = $ticket;

        return $this;
    }

    /**
     * Get ticket
     *
     * @return \AwesomeBundle\Entity\Ticket
     */
    public function getTicket()
    {
        return $this->ticket;
    }

    /**
     * Set user
     *
     * @param \AwesomeBundle\Entity\User $user
     *
     * @return Message
     */
    public function setUser(\AwesomeBundle\Entity\User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \AwesomeBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}


text:
'use strict';

var argusNamespace = angular.module('argusNamespace', [
    'ngResource'
]);

argusNamespace.controller('NamespaceCtrl', ['Storage', '$scope', 'growl', 'Namespace',
                                         function (Storage, $scope, growl, Namespace) {

	$scope.searchText = Storage.get("namespace-searchText") == null ? "" : Storage.get("namespace-searchText");
	$scope.addnamespaceflag=false;
    $scope.namespaces = Namespace.query();

    $scope.updateNamespace = function(namespace){
    	 //if ($scope.isAlertDirty()) { TODO: uncomment this
    	var userNames=namespace.usernames.toString();
    	namespace.usernames=(userNames && userNames.length>0)? userNames.split(','):[];

    		Namespace.update({namespaceId: namespace.id}, namespace, function (result) {
                 growl.success(('Updated namespace "') + namespace.qualifier + '"');

                 for(var i=0; i<$scope.namespaces.length;i++){
                	var oldNamespace = $scope.namespaces[i];
                	if(oldNamespace.id==result.id){
                		$scope.namespaces[i]=result;
                		break;
                	}

                 }

             }, function (error) {
            	 growl.error('Failed to update namespace "' + namespace.qualifier + '"' + (error && error.data && error.data.message)?error.data.message:error.statusText);
             });
         //}
    };

    $scope.saveNamespace = function () {

    	 var newNamespace = {};
    	 var userNames = $scope.users;

    	 newNamespace.qualifier=$scope.qulifier;
    	 newNamespace.usernames=(userNames && userNames.length>0)? userNames.split(','):[];

    	 Namespace.save(newNamespace, function (result) {
    		 $scope.namespaces.push(result);
    		 $scope.qulifier="";
    		 $scope.users="";

    		 growl.success('Created namespace "' + newNamespace.qualifier + '"');

             }, function (error) {
            	 growl.error('Failed to create "' + newNamespace.qualifier + '"' + (error && error.data && error.data.message)?error.data.message:error.statusText);
             });
    };

    $scope.$watch('searchText', function(newValue, oldValue) {
    	newValue = newValue == null ? "" : newValue;
    	Storage.set("namespace-searchText", newValue);
    });

}]);

argusNamespace.factory('Namespace', ['$resource', 'CONFIG',
                                 function ($resource, CONFIG) {
	return $resource(CONFIG.wsUrl + 'namespace/:namespaceId', {}, {
        update: {method: 'PUT'}
    });

 }]);

/*
argusNamespace.factory('NamespaceUsers', ['$resource', 'CONFIG',
                                     function ($resource, CONFIG) {
                                         return $resource(CONFIG.wsUrl + 'namespace/:namespaceId/users');
                                     }]);
*/


text:
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Umbraco.CodeGen.Configuration;
using Umbraco.CodeGen.Generators.Annotated;
using Umbraco.CodeGen.Generators.BaseSupportedAnnotated;
using Umbraco.CodeGen.Parsers;
using ImportsGenerator = Umbraco.CodeGen.Generators.BaseSupportedAnnotated.ImportsGenerator;

namespace Umbraco.CodeGen.Generators
{
    [Parser(typeof(AnnotatedParserFactory))]
    [Description("Models depend on CodeGen for metadata. Requires Umbraco.Core.Models namespace usage to stay in base class, making naming less restricted.")]
    public class BaseSupportedAnnotatedCodeGeneratorFactory : CodeGeneratorFactory
    {
        public override CodeGeneratorBase Create(ContentTypeConfiguration configuration, IEnumerable<DataTypeDefinition> dataTypes)
        {
            if (configuration.ContentTypeName == "DocumentType")
                return CreateDocTypeGenerator(configuration, dataTypes);
            return CreateMediaTypeGenerator(configuration, dataTypes);
        }

        public CodeGeneratorBase CreateDocTypeGenerator(ContentTypeConfiguration configuration, IEnumerable<DataTypeDefinition> dataTypes)
        {
            return CreateGenerators(
                configuration,
                dataTypes,
                "DocumentType",
                new DocumentTypeInfoGenerator(configuration)
                );
        }

        public CodeGeneratorBase CreateMediaTypeGenerator(ContentTypeConfiguration configuration, IEnumerable<DataTypeDefinition> dataTypes)
        {
            return CreateGenerators(
                configuration,
                dataTypes,
                "MediaType",
                new CommonInfoGenerator(configuration)
                );
        }

        private static CodeGeneratorBase CreateGenerators(
            ContentTypeConfiguration configuration,
            IEnumerable<DataTypeDefinition> dataTypes,
            string attributeName,
            CodeGeneratorBase infoGenerator)
        {
            return new NamespaceGenerator(
                configuration,
                new ImportsGenerator(configuration),
                new ClassGenerator(configuration,
                    new CompositeCodeGenerator(
                        configuration,
                        new EntityNameGenerator(configuration),
                        new AttributeCodeGenerator(
                            attributeName,
                            configuration,
                            infoGenerator,
                            new StructureGenerator(configuration)
                            )
                        ),
                    new BaseSupportedAnnotated.CtorGenerator(configuration),
                    new PropertiesGenerator(
                        configuration,
                        new PublicPropertyDeclarationGenerator(
                            configuration,
                            dataTypes.ToList(),
                            new EntityNameGenerator(configuration),
                            new AttributeCodeGenerator(
                                "GenericProperty",
                                configuration,
                                new PropertyInfoGenerator(configuration, dataTypes.ToList())
                                ),
                            new BaseSupportedAnnotated.PropertyBodyGenerator(configuration)
                            )
                        )
                    )
                );
        }
    }
}


text:
import os
from os.path import dirname, abspath, basename, join
import sys
import logging
import argparse
import json
import subprocess
import shutil
import stat
import re
from github import Github, GithubException
from jinja2 import FileSystemLoader, StrictUndefined
from jinja2.environment import Environment

ROOT = abspath(dirname(dirname(dirname(dirname(__file__)))))
sys.path.insert(0, ROOT)

import examples_lib as lib
from examples_lib import SUPPORTED_TOOLCHAINS

userlog = logging.getLogger("Update")

# Set logging level
userlog.setLevel(logging.DEBUG)

# Everything is output to the log file
logfile = os.path.join(os.getcwd(), 'update.log')
fh = logging.FileHandler(logfile)
fh.setLevel(logging.DEBUG)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)

formatter = logging.Formatter('%(name)s: %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)

# add the handlers to the logger
userlog.addHandler(fh)
userlog.addHandler(ch)

def run_cmd(command, exit_on_failure=False):
    """ Run a system command returning a status result

    This is just a wrapper for the run_cmd_with_output() function, but
    only returns the status of the call.

    Args:
    command - system command as a list of tokens
    exit_on_failure - If True exit the program on failure (default = False)

    Returns:
    return_code - True/False indicating the success/failure of the command
    """
    return_code, _ = run_cmd_with_output(command, exit_on_failure)
    return return_code

def run_cmd_with_output(command, exit_on_failure=False):
    """ Run a system command returning a status result and any command output

    Passes a command to the system and returns a True/False result once the
    command has been executed, indicating success/failure. If the command was
    successful then the output from the command is returned to the caller.
    Commands are passed as a string.
    E.g. The command 'git remote -v' would be passed in as "git remote -v"

    Args:
    command - system command as a string
    exit_on_failure - If True exit the program on failure (default = False)

    Returns:
    return_code - True/False indicating the success/failure of the command
    output - The output of the command if it was successful, else empty string
    """
    text = '[Exec] ' + command
    userlog.debug(text)
    returncode = 0
    output = ""
    try:
        output = subprocess.check_output(command, shell=True)
    except subprocess.CalledProcessError as e:
        text = "The command " + str(command) + "failed with return code: " + str(e.returncode)
        userlog.warning(text)
        returncode = e.returncode
        if exit_on_failure:
            sys.exit(1)
    return returncode, output

def rmtree_readonly(directory):
    """ Deletes a readonly directory tree.

    Args:
    directory - tree to delete
    """
    def remove_readonly(func, path, _):
        os.chmod(path, stat.S_IWRITE)
        func(path)

    shutil.rmtree(directory, onerror=remove_readonly)

def find_all_examples(path):
    """ Search the path for examples

    Description:

    Searches the path specified for sub-example folders, ie those containing an
    mbed-os.lib file. If found adds the path to the sub-example to a list which is
    then returned.

    Args:
    path - path to search.
    examples - (returned) list of paths to example directories.

    """
    examples = []
    for root, dirs, files in os.walk(path):
        if 'mbed-os.lib' in files:
            examples += [root]

    return examples

def upgrade_single_example(example, tag, directory, ref):
    """ Update the mbed-os version for a single example

    Description:

    Updates the mbed-os.lib file in the example specified to correspond to the
    version specified by the GitHub tag supplied. Also deals with
    multiple sub-examples in the GitHub repo, updating them in the same way.

    Args:
    example - json example object containing the GitHub repo to update.
    tag - GitHub tag corresponding to a version of mbed-os to upgrade to.
    directory - directory path for the example.
    ref - SHA corresponding to the supplied tag
    returns - True if the upgrade was successful, False otherwise.

    """
    cwd = os.getcwd()
    os.chdir(directory)

    return_code = False

    if os.path.isfile("mbed-os.lib"):
        # Rename command will fail on some OS's if the target file already exist,
        # so ensure if it does, it is deleted first.
        if os.path.isfile("mbed-os.lib_bak"):
            os.remove("mbed-os.lib_bak")

        os.rename("mbed-os.lib", "mbed-os.lib_bak")
    else:
        userlog.error("Failed to backup mbed-os.lib prior to updating.")
        return False

    # mbed-os.lib file contains one line with the following format
    # e.g. https://github.com/ARMmbed/mbed-os/#0789928ee7f2db08a419fa4a032fffd9bd477aa7
    lib_re = re.compile('https://github.com/ARMmbed/mbed-os/#[A-Za-z0-9]+')
    updated = False

    # Scan through mbed-os.lib line by line
    with open('mbed-os.lib_bak', 'r') as ip, open('mbed-os.lib', 'w') as op:
        for line in ip:

            opline = line

            regexp = lib_re.match(line)
            if regexp:
                opline = 'https://github.com/ARMmbed/mbed-os/#' + ref
                updated = True

            op.write(opline)

    if updated:
        # Setup and run the git add command
        cmd = "git add mbed-os.lib"
        return_code = run_cmd(cmd)

    os.chdir(cwd)
    return not return_code

def prepare_fork(arm_example):
    """ Synchronises a cloned fork to ensure it is up to date with the original.

    Description:

    This function sets a fork of an ARMmbed repo to be up to date with the
    repo it was forked from. It does this by hard resetting to the ARMmbed
    master branch.

    Args:
    arm_example - Full GitHub repo path for original example

    """

    logstr = "In: " + os.getcwd()
    userlog.debug(logstr)

    for cmd in ["git remote add armmbed " + str(arm_example),
                "git fetch armmbed",
                "git reset --hard armmbed/master",
                "git push -f origin"]:
        run_cmd(cmd, exit_on_failure=True)

def prepare_branch(src, dst):
    """ Set up at branch ready for use in updating examples

    Description:

    This function checks whether or not the supplied dst branch exists.
    If it does not, the branch is created from the src and pushed to the origin.
    The branch is then switched to.

    Args:
    src - branch to create the dst branch from
    dst - branch to update

    """

    userlog.debug("Preparing branch: %s", dst)

    # Check if branch already exists or not.
    # We can use the 'git branch -r' command. This returns all the remote branches for
    # the current repo.
    # The output consists of a list of lines of the form:
    # origin/<branch>
    # From these we need to extract just the branch names to a list and then check if
    # the specified dst exists in that list
    branches = []
    cmd = "git branch -r"
    _, output = run_cmd_with_output(cmd, exit_on_failure=True)

    branches = [line.split('/')[1] for line in output.split('\n') if 'origin' in line and not '->' in line]

    if not dst in branches:

        # OOB branch does not exist thus create it, first ensuring we are on
        # the src branch and then check it out

        for cmd in ["git checkout " + str(src),
                    "git checkout -b " + str(dst),
                    "git push -u origin " + str(dst)]:

            run_cmd(cmd, exit_on_failure=True)

    else:
        cmd = "git checkout " + str(dst)
        run_cmd(cmd, exit_on_failure=True)

def upgrade_example(github, example, tag, ref, user, src, dst, template):
    """ Upgrade all versions of mbed-os.lib found in the specified example repo

    Description:

    Clone a version of the example specified and upgrade all versions of
    mbed-os.lib found within its tree.  The version cloned and how it
    is upgraded depends on the user, src and dst settings.
    1) user == None
       The destination branch will be updated with the version of mbed-os
       idenfied by the tag. If the destination branch does not exist then it
       will be created from the source branch.

    2) user != None
       The master branch of a fork of the example will be updated with the
       version of mbed-os identified by the tag.

    Args:
    github - GitHub instance to allow internal git commands to be run
    example - json example object containing the GitHub repo to update.
    tag - GitHub tag corresponding to a version of mbed-os to upgrade to.
    ref - SHA corresponding to the tag
    user - GitHub user name
    src - branch to create the dst branch from
    dst - branch to update

    returns True if the upgrade was successful, False otherwise
    """

    # If a user has not been specified then branch update will be used and thus
    # the git user will be ARMmbed.
    if not user:
        user = 'ARMmbed'

    ret = False
    userlog.info("Updating example '%s'", example['name'])
    userlog.debug("User: %s", user)
    userlog.debug("Src branch: %s", (src or "None"))
    userlog.debug("Dst branch: %s", (dst or "None"))

    cwd = os.getcwd()

    update_repo = "https://github.com/" + user + '/' + example['name']
    userlog.debug("Update repository: %s", update_repo)

    # Clone the example repo
    clone_cmd = "git clone " +  str(update_repo)
    return_code = run_cmd(clone_cmd)

    if not return_code:

        # Find all examples
        example_directories = find_all_examples(example['name'])

        os.chdir(example['name'])

        # If the user is ARMmbed then a branch is used.
        if user == 'ARMmbed':
            prepare_branch(src, dst)
        else:
            prepare_fork(example['github'])

        for example_directory in example_directories:
            if not upgrade_single_example(example, tag, os.path.relpath(example_directory, example['name']), ref):
                os.chdir(cwd)
                return False

        # Setup and run the commit command
        commit_cmd = "git commit -m \"Updating mbed-os to " + tag + "\""
        return_code = run_cmd(commit_cmd)
        if not return_code:

            # Setup and run the push command
            push_cmd = "git push origin"
            return_code = run_cmd(push_cmd)

            if not return_code:
                # If the user is not ARMmbed then a fork is being used
                if user != 'ARMmbed':

                    upstream_repo = 'ARMmbed/'+ example['name']
                    userlog.debug("Upstream repository: %s", upstream_repo)
                    # Check access to mbed-os repo
                    try:
                        repo = github.get_repo(upstream_repo, False)

                    except:
                        userlog.error("Upstream repo: %s, does not exist - skipping", upstream_repo)
                        return False

                    jinja_loader = FileSystemLoader(template)
                    jinja_environment = Environment(loader=jinja_loader,
                                                    undefined=StrictUndefined)
                    pr_body = jinja_environment.get_template("pr.tmpl").render(tag=tag)

                    # Raise a PR from release-candidate to master
                    user_fork = user + ':master'
                    try:
                        pr = repo.create_pull(title='Updating mbed-os to ' + tag, head=user_fork, base='master', body=pr_body)
                        ret = True
                    except GithubException as e:
                        # Default to False
                         userlog.error("Pull request creation failed with error: %s", e)
                else:
                    ret = True
            else:
                userlog.error("Git push command failed.")
        else:
            userlog.error("Git commit command failed.")
    else:
        userlog.error("Git clone %s failed", update_repo)

    os.chdir(cwd)
    return ret

def create_work_directory(path):
    """ Create a new directory specified in 'path', overwrite if the directory already
        exists.

    Args:
    path - directory path to be created.

    """
    if os.path.exists(path):
        userlog.info("'%s' directory already exists. Deleting...", path)
        rmtree_readonly(path)

    os.makedirs(path)

def check_update_status(examples, github, tag):
    """ Check the status of previously raised update pull requests

    Args:
    examples - list of examples which should have had PRs raised against them.
    github - github rest API instance
    tag - release tag used for the update

    """

    for example in examples:

        repo_name = ''.join(['ARMmbed/', example['name']])
        try:
            repo = github.get_repo(repo_name, False)

        except Exception as exc:
            text = "Cannot access: " + str(repo_name)
            userlog.error(text)
            userlog.exception(exc)
            sys.exit(1)

        # Create the full repository filter component
        org_str = ''.join(['repo:ARMmbed/', example['name']])
        filt = ' '.join([org_str, 'is:pr', tag])
        merged = False

        issues = github.search_issues(query=(filt))
        pr_list = [repo.get_pull(issue.number) for issue in issues]

        # Should only be one matching PR but just in case, go through paginated list
        for pr in pr_list:
            if pr.merged:
                userlog.info("%s - '%s': MERGED", example['name'], pr.title)
            elif pr.state == 'open':
                userlog.info("%s - '%s': PENDING", example['name'], pr.title)
            elif pr.state == 'closed':
                userlog.info("%s - '%s': CLOSED NOT MERGED", example['name'], pr.title)
            else:
                userlog.error("%s: Cannot find a pull request for %s", example['name'], tag)

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description=__doc__,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-c', '--config_file', help="Path to the configuration file (default is 'examples.json')", default='examples.json')
    parser.add_argument('-T', '--github_token', help="GitHub token for secure access")

    exclusive = parser.add_mutually_exclusive_group(required=True)
    exclusive.add_argument('-f', '--fork', help="Update a fork", action='store_true')
    exclusive.add_argument('-b', '--branch', help="Update a branch", action='store_true')
    exclusive.add_argument('-s', '--status', help="Show examples update status", action='store_true')

    args = parser.parse_args()

    # Load the config file
    with open(os.path.join(os.path.dirname(__file__), args.config_file)) as config:
        if not config:
            userlog.error("Failed to load config file '%s'", args.config_file)
            sys.exit(1)
        json_data = json.load(config)

    github = Github(args.github_token)
    config = json_data['update-config']
    tag = config['tag']

    user = None
    src = "master"
    dst = None

    if args.status:

        # This option should only be called after an update has been performed
        check_update_status(json_data['examples'], github, tag)
        exit(0)

    # Create working directory
    create_work_directory('examples')

    if args.fork:
        user = config['via-fork']['github-user']
    elif args.branch:
        src = config['via-branch']['src-branch']
        dst = config['via-branch']['dst-branch']
    else:
        userlog.error("Must specify either -f or -b command line option")
        exit(1)

    # Get the github sha corresponding to the specified mbed-os tag
    cmd = "git rev-list -1 " + tag
    return_code, ref = run_cmd_with_output(cmd)

    if return_code:
        userlog.error("Could not obtain SHA for tag: %s",  tag)
        sys.exit(1)

    # Loop through the examples
    failures = []
    successes = []
    results = {}
    template = dirname(abspath(__file__))

    os.chdir('examples')

    for example in json_data['examples']:
        # Determine if this example should be updated and if so update any found
        # mbed-os.lib files.

        result = upgrade_example(github, example, tag, ref, user, src, dst, template)

        if result:
            successes += [example['name']]
        else:
            failures += [example['name']]

    os.chdir('../')

    # Finish the script and report the results
    userlog.info("Finished updating examples")
    if successes:
        for success in successes:
            userlog.info(" SUCCEEDED: %s", success)

    if failures:
        for fail in failures:
            userlog.info(" FAILED: %s", fail)


text:
///////////////////////////////////////////////////////////////////////////////////////////////
//
//    This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
//    Copyright (c) 2005-2008, Jim Heising
//    All rights reserved.
//
//    Redistribution and use in source and binary forms, with or without modification,
//    are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright notice,
//      this list of conditions and the following disclaimer in the documentation and/or
//      other materials provided with the distribution.
//
//    * Neither the name of Jim Heising nor the names of its contributors may be
//      used to endorse or promote products derived from this software without specific prior
//      written permission.
//
//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//    IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//    POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////

/*=====================================================================

  File:        PipeClientChannel.cs

=====================================================================*/

using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Channels;
using System.Threading;

namespace NET.Remoting
{
    public class PipeClientChannel: IChannelSender
    {
        // pipe:// prefix
        private const String  ChannelScheme = "pipe";

        private const int     DefaultChannelPriority=1;
        private const String  DefaultChannelName = "Pipe";

        private int m_ChannelPriority;
        private String m_ChannelName;
        private String m_pipeName = null;

        private IClientChannelSinkProvider _clientSinkProvider; // client sink chain provider

        public PipeClientChannel()
        {
            InitDefaults();
            InitProperties(null);
            InitProviders(null);
        }

        public PipeClientChannel(
                                  IDictionary properties,
                                  IClientChannelSinkProvider clientProviderChain
                                 )
        {
            InitDefaults();
            InitProperties(properties);
            InitProviders(clientProviderChain);
        }

        internal void InitDefaults()
        {
         m_ChannelPriority = DefaultChannelPriority;
         m_ChannelName = DefaultChannelName;
        }

        internal void InitProperties(IDictionary properties)
        {

            if(properties != null)
            {
             foreach (DictionaryEntry entry in properties)
             {
               switch ((String) entry.Key)
               {
                 case "name": m_ChannelName = (String) entry.Value;
                   break;
                 case "priority": m_ChannelPriority = Convert.ToInt32(entry.Value);
                   break;
                 case "pipe": m_pipeName = (String) entry.Value;
                   break;
               }
             }
            }
        }

        void InitProviders(IClientChannelSinkProvider clientProviderChain)
        {
            _clientSinkProvider = clientProviderChain;

            if(_clientSinkProvider == null)
            {
              _clientSinkProvider = new BinaryClientFormatterSinkProvider();
            }

            IClientChannelSinkProvider tempSinkProvider = _clientSinkProvider;

            // Move to the end of provider list
            while (tempSinkProvider.Next != null)
             tempSinkProvider = tempSinkProvider.Next;

            // Append transport sink provider to end
            tempSinkProvider.Next = new PipeClientTransportSinkProvider();
        }

        // IChannel
        public String ChannelName { get { return(m_ChannelName); } }
        public int    ChannelPriority { get { return(m_ChannelPriority); } }

        public String Parse(String url, out string uri)
        {
            return(PipeConnection.Parse(url, out uri));
        }

        // IChannelSender
        public IMessageSink CreateMessageSink(String url, Object data, out String objuri)
        {
            DBG.Info(null, "CreateMessageSink: url = " + url);
            // Set the out parameters
            objuri = null;
            String chanuri = null;

            if (url != null) // Is this a well known object?
            {
                /*
                String urlCompare = String.ToLower(url);

                // Starts with pipe:// ?
                if (urlCompare.StartsWith(ChannelScheme) == false)
                {
                    return null;
                }
                */

                // Parse returns null if this is not one of the pipe channel url's
                chanuri = Parse(url, out objuri);
            }
            else if(data != null)
            {
                IChannelDataStore cds = data as IChannelDataStore;
                if(cds != null)
                {
                    DBG.Info(null, "ChannelUris[0] = " + cds.ChannelUris[0]);
                    //Console.WriteLine("Channel Uri {0}", cds.ChannelUris[0]);

                    chanuri = Parse(cds.ChannelUris[0], out objuri);
                    DBG.Info(null, "CreateMessageSink: chanuri = " + chanuri + ", objuri = " + objuri);
                    if(chanuri != null)
                        url = cds.ChannelUris[0];
                }
            }

            if (null != chanuri)
            {
                if (url == null)
                    url = chanuri;

                DBG.Info(null, "CreateMessageSink: delegating w/ url = " + url);
                //Console.WriteLine("CreateMessageSink: delegating w/ url =  {0}", url);

                return (IMessageSink)_clientSinkProvider.CreateSink(this, url, data);
            }

            DBG.Info(null, "CreateMessageSink: ignoring request...");
            return null;
        } // CreateMessageSink

        public void Dispose()
        {
            // Nothing to do
        }
    }

    internal class PipeClientTransportSinkProvider : IClientChannelSinkProvider
    {
        internal PipeClientTransportSinkProvider()
        {
        }

        public IClientChannelSink CreateSink(IChannelSender channel,
                                             String url,
                                             Object data)
        {
            return new PipeClientTransportSink(url);
        }

        public IClientChannelSinkProvider Next
        {
            get { return null; }
            set { throw new NotSupportedException(); }
        }
    }

    internal class PipeClientTransportSink : IClientChannelSink
    {
        private String _pipeName;
        private PipeConnectionPool _pipeConnectionPool=null;
        private int _defaultRetryCount = 2;

        private WaitCallback callback;

        internal PipeClientTransportSink(String url)
        {
            String objuri = null;
            String chanuri = PipeConnection.Parse(url, out objuri);

            DBG.Info(null, "PipeClientTransportSink: creating pipe on uri: " + chanuri);
            //Console.WriteLine("PipeClientTransportSink {0}", chanuri);

            _pipeName = chanuri;
            _pipeConnectionPool = PipeConnectionPoolManager.LookupPool(_pipeName);

            callback = new WaitCallback(this.ReceiveCallback);
        }

        public IDictionary Properties
        {
            get { return(null); }
        }

        public void AsyncProcessRequest(IClientChannelSinkStack stack,
                                        IMessage msg,
                                        ITransportHeaders headers,
                                        Stream stream)
        {
            DBG.Info(null, "Async: Send the message across the pipe");

            PipeConnection _pipe = SendWithRetry(msg, headers, stream);

            IMethodCallMessage mcm = (IMethodCallMessage)msg;
            MethodBase methodBase = mcm.MethodBase;
            bool oneway = RemotingServices.IsOneWay(methodBase);

            if (oneway)
            {
                if (_pipeConnectionPool != null)
                {
                    _pipeConnectionPool.ReturnToPool(_pipe);
                }
                _pipe = null;
            }
            else
            {
                PipeConnectionCookie cookie = new PipeConnectionCookie();

                cookie.pipe = _pipe;
                cookie.sinkStack = stack;

                //TODO Switch to use Completion port
                ThreadPool.QueueUserWorkItem(callback, cookie);
            }
        }

        private void ReceiveCallback(Object state)
        {
            //Console.WriteLine("ReceiveCallback TID {0}", Thread.CurrentThread.GetHashCode());

            PipeConnectionCookie cookie = (PipeConnectionCookie)state;

            PipeConnection _pipe = cookie.pipe;
            IClientChannelSinkStack sinkStack = cookie.sinkStack;

            try
            {

                // Read response
                //
                _pipe.BeginReadMessage();

                ITransportHeaders responseHeaders = _pipe.ReadHeaders();
                responseHeaders["__CustomErrorsEnabled"] = false;

                Stream responseStream  = _pipe.ReadStream();
                _pipe.EndReadMessage();

                if (_pipeConnectionPool != null)
                {
                    _pipeConnectionPool.ReturnToPool(_pipe);
                }

                _pipe = null;

                sinkStack.AsyncProcessResponse(responseHeaders, responseStream);
            }
            catch (Exception e)
            {
                try
                {
                    if (sinkStack != null)
                        sinkStack.DispatchException(e);
                }
                catch(Exception )
                {
                    // Fatal Error.. ignore
                }
            }
        } // ReceiveCallback

        public void AsyncProcessResponse(IClientResponseChannelSinkStack stack,
                                         Object obj,
                                         ITransportHeaders headers,
                                         Stream stream)
        {
            throw new NotSupportedException();
        }

        public Stream GetRequestStream(IMessage msg, ITransportHeaders headers)
        {
            // we don't do any serialization here.
            return(null);
        }

        public void ProcessMessage(IMessage msg,
                                   ITransportHeaders reqHead,
                                   Stream reqStm,
                                   out ITransportHeaders respHead,
                                   out Stream respStm)
        {
            DBG.Info(null, "Being asked to process the serialized message!");
            //Console.WriteLine("ProcessMessage TID {0}", Thread.CurrentThread.GetHashCode());

            // Send the message across the pipe.
            PipeConnection _pipe = SendWithRetry(msg, reqHead, reqStm);
            respHead = null;
            respStm = null;
            // Read response
            if (_pipe != null)
            {
                _pipe.BeginReadMessage();
                respHead = _pipe.ReadHeaders();
                respHead["__CustomErrorsEnabled"] = false;
                respStm = _pipe.ReadStream();
                _pipe.EndReadMessage();

                if (_pipeConnectionPool != null)
                {
                    _pipeConnectionPool.ReturnToPool(_pipe);
                }

                _pipe = null;
            }
        }

        IClientChannelSink IClientChannelSink.NextChannelSink
        {
            get { return(null); }
        }

        public PipeConnection SendWithRetry(IMessage msg,
                                   ITransportHeaders reqHead,
                                   Stream reqStm)
        {
            IMethodCallMessage mcm = (IMethodCallMessage)msg;

            String uri = mcm.Uri;
            PipeConnection _pipe = null;

            int tryCount = _defaultRetryCount;
            long reqStmPosition = -1;

            if (reqStm.CanSeek == false)
                tryCount=1;
            else
                reqStmPosition = reqStm.Position;

            while ( tryCount>0)
            {
                try
                {
                    if (_pipeConnectionPool != null)
                    {
                        DBG.Info(null, "Look in pipe connection in pool");
                        _pipe = (PipeConnection)_pipeConnectionPool.Obtain();
                    }

                    // otherwise create a new connection
                    if (_pipe == null)
                    {
                        _pipe = new PipeConnection(_pipeName, false, IntPtr.Zero);
                    }

                    //Send with Retry
                    _pipe.BeginWriteMessage();
                    _pipe.WriteHeaders(uri, reqHead);
                    _pipe.Write(reqStm);
                    _pipe.EndWriteMessage();

                    tryCount=0;
                }
                catch(PipeIOException pe)
                {
                    pe=pe;
                    if (_pipe != null)
                    {
                        _pipe.Dispose();
                        _pipe = null;
                    }

                   tryCount--;
                   reqStm.Position = reqStmPosition;
                }
            }

            return _pipe;
        }
    }
}


text:
@interface PSReachabilityCenter : NSObject

+ (id)defaultCenter;

- (BOOL)isNetworkReachable;
- (BOOL)isNetworkReachableViaWWAN;

@end


text:
import {
  render
} from '@/content'

import {
  setApiBaseURL
} from '@/config'

setApiBaseURL('/base/test/fixtures/xhr/api.github.com')

describe('Content', () => {
  let root

  beforeEach(() => {
    root = document.body.appendChild(document.createElement('div'))
  })

  afterEach(() => {
    root.parentNode.removeChild(root)
    root = null
  })

  describe('render(root, options, callback)', () => {
    it('should work', (done) => {
      render(root, {}, () => done())
    })

    it('should render stylesheet', (done) => {
      render(root, {}, () => {
        expect(root.querySelector('style'))
          .to.be.an.instanceof(HTMLElement)
        done()
      })
    })

    it('should create a widget with className widget', (done) => {
      render(root, {}, () => {
        expect(root.querySelector('.widget'))
          .to.be.an.instanceof(HTMLElement)
        expect(root.querySelector('.widget.widget-lg'))
          .to.be.null
        done()
      })
    })

    it('should add widget-lg to widget.className when data-size is large', (done) => {
      render(root, {
        'data-size': 'large'
      }, () => {
        expect(root.querySelector('.widget.widget-lg'))
          .to.be.an.instanceof(HTMLElement)
        done()
      })
    })

    it('should append the button to widget when the necessary options are given', (done) => {
      render(root, {}, () => {
        expect(root.querySelector('.btn'))
          .to.be.an.instanceof(HTMLElement)
        done()
      })
    })

    it('should callback with widget', (done) => {
      render(root, {}, (widget) => {
        expect(widget)
          .to.be.an.instanceof(HTMLElement)
        done()
      })
    })

    it('should append the button with given href', (done) => {
      const options = {
        href: 'https://ntkme.github.com/'
      }
      render(root, options, () => {
        expect(root.querySelector('.btn').getAttribute('href'))
          .to.equal(options.href)
        done()
      })
    })

    it('should append the button with given href if hostname is FQDN', (done) => {
      const options = {
        href: 'https://github.com./ntkme'
      }
      render(root, options, () => {
        expect(root.querySelector('.btn').getAttribute('href'))
          .to.equal(options.href)
        done()
      })
    })

    it('should create an anchor without href if hostname is not under github.com', (done) => {
      render(root, {
        href: 'https://twitter.com/ntkme'
      }, () => {
        expect(root.querySelector('.btn').hasAttribute('href'))
          .to.be.false
        done()
      })
    })

    it('should create an anchor without href if url contains javascript', (done) => {
      Promise.all([
        'javascript:',
        'JAVASCRIPT:',
        'JavaScript:',
        ' javascript:',
        '   javascript:',
        '\tjavascript:',
        '\njavascript:',
        '\rjavascript:',
        '\fjavascript:'
      ].map(href => new Promise(resolve => {
        render(root, {
          href
        }, (widget) => {
          expect(widget.querySelector('.btn').hasAttribute('href'))
            .to.be.false
          resolve()
        })
      })))
        .then(() => done())
        .catch(done)
    })

    it('should create an anchor with target _top if url is a download link', (done) => {
      Promise.all([
        'https://github.com/ntkme/github-buttons/archive/master.zip',
        'https://gist.github.com/schacon/1/archive/3a641566d0a49014cea6f395e8be68c42b9e46d9.zip',
        'https://codeload.github.com/ntkme/github-buttons/zip/master',
        'https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip',
        'https://github.com/octocat/Hello-World/releases/latest/download/example.zip'
      ].map(href => new Promise(resolve => {
        render(root, {
          href
        }, (widget) => {
          expect(widget.querySelector('.btn').href)
            .to.equal(href)
          expect(widget.querySelector('.btn').target)
            .to.equal('_top')
          resolve()
        })
      })))
        .then(() => done())
        .catch(done)
    })

    it('should append the button with the default icon', (done) => {
      render(root, {}, () => {
        expect(root.querySelector('.btn').querySelector('.octicon.octicon-mark-github'))
          .to.be.an.instanceof(SVGElement)
        done()
      })
    })

    it('should append the button with given icon', (done) => {
      render(root, {
        'data-icon': 'octicon-star'
      }, () => {
        expect(root.querySelector('.btn').querySelector('.octicon.octicon-star'))
          .to.be.an.instanceof(SVGElement)
        done()
      })
    })

    it('should append the button with the default if given icon is invalid', (done) => {
      render(root, {
        'data-icon': 'null'
      }, () => {
        expect(root.querySelector('.btn').querySelector('.octicon.octicon-mark-github'))
          .to.be.an.instanceof(SVGElement)
        done()
      })
    })

    it('should append the button with given text', (done) => {
      const options = {
        'data-text': 'Follow'
      }
      render(root, options, () => {
        expect(root.querySelector('.btn').lastChild.textContent)
          .to.equal(options['data-text'])
        done()
      })
    })

    it('should append the button with given title', (done) => {
      const options = {
        title: 'test1234'
      }
      render(root, options, () => {
        expect(root.querySelector('.btn').title)
          .to.equal(options.title)
        done()
      })
    })

    it('should append the button with given aria label', (done) => {
      const options = {
        'aria-label': 'GitHub'
      }
      render(root, options, () => {
        expect(root.querySelector('.btn').getAttribute('aria-label'))
          .to.equal(options['aria-label'])
        done()
      })
    })

    it('should append the count when a known button type is given', (done) => {
      const options = {
        href: 'https://github.com/ntkme',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        expect(widget.querySelector('.social-count'))
          .to.be.an.instanceof(HTMLElement)
        done()
      })
    })

    it('should append the count for follow button', (done) => {
      const options = {
        href: 'https://github.com/ntkme',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme?tab=followers')
        expect(count.textContent)
          .to.equal('78')
        expect(count.getAttribute('aria-label'))
          .to.equal('78 followers on GitHub')
        done()
      })
    })

    it('should append the count for watch button', (done) => {
      const options = {
        href: 'https://github.com/ntkme/github-buttons/subscription',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme/github-buttons/watchers')
        expect(count.textContent)
          .to.equal('36')
        expect(count.getAttribute('aria-label'))
          .to.equal('36 subscribers on GitHub')
        done()
      })
    })

    it('should append the count for star button', (done) => {
      const options = {
        href: 'https://github.com/ntkme/github-buttons',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme/github-buttons/stargazers')
        expect(count.textContent)
          .to.equal('546')
        expect(count.getAttribute('aria-label'))
          .to.equal('546 stargazers on GitHub')
        done()
      })
    })

    it('should append the count for fork button', (done) => {
      const options = {
        href: 'https://github.com/ntkme/github-buttons/fork',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme/github-buttons/network/members')
        expect(count.textContent)
          .to.equal('94')
        expect(count.getAttribute('aria-label'))
          .to.equal('94 forks on GitHub')
        done()
      })
    })

    it('should append the count for issue button', (done) => {
      const options = {
        href: 'https://github.com/ntkme/github-buttons/issues',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme/github-buttons/issues')
        expect(count.textContent)
          .to.equal('1')
        expect(count.getAttribute('aria-label'))
          .to.equal('1 open issue on GitHub')
        done()
      })
    })

    it('should append the count for issue button when it links to new issue', (done) => {
      const options = {
        href: 'https://github.com/ntkme/github-buttons/issues/new',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme/github-buttons/issues')
        expect(count.textContent)
          .to.equal('1')
        expect(count.getAttribute('aria-label'))
          .to.equal('1 open issue on GitHub')
        done()
      })
    })

    it('should append the count for button whose link has a tailing slash', (done) => {
      const options = {
        href: 'https://github.com/ntkme/',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme?tab=followers')
        done()
      })
    })

    it('should append the count for button whose link has a query', (done) => {
      const options = {
        href: 'https://github.com/ntkme?tab=repositories',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme?tab=followers')
        done()
      })
    })

    it('should append the count for button whose link has a hash', (done) => {
      const options = {
        href: 'https://github.com/ntkme#github-buttons',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme?tab=followers')
        done()
      })
    })

    it('should append the count for button whose link has both a tailing slash and a query', (done) => {
      const options = {
        href: 'https://github.com/ntkme/?tab=repositories',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme?tab=followers')
        done()
      })
    })

    it('should append the count for button whose link has both a tailing slash and a hash', (done) => {
      const options = {
        href: 'https://github.com/ntkme/#github-buttons',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme?tab=followers')
        done()
      })
    })

    it('should append the count for button whose link has a tailing slash, a query, and a hash', (done) => {
      const options = {
        href: 'https://github.com/ntkme/?tab=repositories#github-buttons',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const count = widget.querySelector('.social-count')
        expect(count.href)
          .to.equal('https://github.com/ntkme?tab=followers')
        done()
      })
    })

    it('should not append the count for unknown button type', (done) => {
      const options = {
        href: 'https://github.com/',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        expect(widget.querySelector('.social-count'))
          .to.be.null
        done()
      })
    })

    it('should not append the count for sponsors button type', (done) => {
      const options = {
        href: 'https://github.com/sponsors',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        expect(widget.querySelector('.social-count'))
          .to.be.null
        done()
      })
    })

    it('should not append the count for sponsors button type', (done) => {
      const options = {
        href: 'https://github.com/sponsors/ntkme',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        expect(widget.querySelector('.social-count'))
          .to.be.null
        done()
      })
    })

    it('should append button without count when count has error', (done) => {
      const options = {
        href: 'https://github.com/404',
        'data-show-count': 'true'
      }
      render(root, options, (widget) => {
        const btn = widget.querySelector('.btn')
        expect(btn.href)
          .to.equal(options.href)
        expect(widget.querySelector('.social-count'))
          .to.be.null
        done()
      })
    })
  })
})