text:
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;

public class sophie {

  private static int size;
  private static double[] P;
  private static double[][] adjMatrix;
  private static HashMap<String, Integer> names;
  private static double best;
  private static DecimalFormat df;
  private static boolean[] visited;

  public static void main(String[] args) throws IOException {
    if (args.length == 0) {
      System.out.println("usage: ./sophie <file>");
      System.exit(0);
    }

    BufferedReader file = new BufferedReader(
      new FileReader(args[0]));

    df = new DecimalFormat("#.00");
    best = Double.POSITIVE_INFINITY;
    size = Integer.parseInt(file.readLine());
    P = new double[size];
    adjMatrix = new double[size][size];
    for (int i = 0; i < size; i++) {
      for (int j = 0; j < size; j++) {
        adjMatrix[i][j] = Double.POSITIVE_INFINITY;
      }
    }

    names = new HashMap<String, Integer>();
    for (int i = 0; i < size; i++) {
      String[] words = (file.readLine()).split("\\s+");
      names.put(words[0], i);
      double p = Double.parseDouble(words[1]);
      P[i] = p;
      adjMatrix[i][i] = 0;
    }
    int count = Integer.parseInt(file.readLine());
    for (int i = 0; i < count; i++) {
      String[] words = (file.readLine()).split("\\s+");
      int a = names.get(words[0]);
      int b = names.get(words[1]);
      int cost = Integer.parseInt(words[2]);
      adjMatrix[a][b] = adjMatrix[b][a] = cost;
    }

    /* All-pairs shortest paths */
    floydWarshall();

    /* Check for any unreachable locations */
    for (int i = 0; i < size; i++) {
      for (int j = i; j < size; j++) {
        if(adjMatrix[i][j] == Double.POSITIVE_INFINITY) {
          System.out.println("-1.00");
          System.exit(0);
        }
      }
    }

    /* Initialize visited vector */
    visited = new boolean[size];
    for (int i = 0; i < size; i++)
      visited[i] = false;
    visit(0, 0, 1);
    System.out.println(df.format(best));
  }

  private static double min(double a, double b) {
    if (b < a)
      return b;
    return a;
  }

  /*
  * Floyd-Warshall algorithm for all-pairs shortest pathes. This
  * unfortunately runs in O(n^3) time, however, actually performs better than
  * n consecutive calls to Dijkstra's algorithm because of its tight-looped
  * and short construction. (Source: Skiena - The Algorithm Design Manual 2e)
  */
  private static void floydWarshall() {
    for (int k = 0; k < size; k++) {
      for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
          if (i != j) {
            adjMatrix[i][j] = min(adjMatrix[i][j],
            adjMatrix[i][k] + adjMatrix[k][j]);
          }
        }
      }
    }
  }

  private static void visit(int node, double ev, double probability) {
    visited[node] = true;
    probability -= P[node];
    boolean end = true;
    for (int i = 1; i < size; i++) {
      if (visited[i] == false) {
        end = false;
        if ((ev + (probability*adjMatrix[node][i])) < best)
          visit(i, ev + (probability*adjMatrix[node][i]) , probability);
      }
    }
    visited[node] = false;

    if (end == true) {
      if (((ev < best) && (best != -1)) || (best < 0))
        best = ev;
    }
  }
}


text:
require 'rails_admin/config/base'
require 'rails_admin/config/hideable'

module RailsAdmin
  module Config
    module Sections
      # Configuration of the navigation view
      class Export < RailsAdmin::Config::Base
        include RailsAdmin::Config::HasFields

        def initialize(parent)
          super(parent)
          @fields = RailsAdmin::Config::Fields.factory(self)
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
[assembly: AssemblyTitle("TestAsm")]
[assembly: AssemblyProduct("TestAsm")]
[assembly: AssemblyCopyright("Copyright © 2016")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("994fa927-3e6f-4794-a442-5003ca450d2b")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]


text:
package javax.jms;

public class QueueRequestor {
    public Message request(Message message) {
        return null;
    }
}


text:
SET client_encoding TO 'UTF8';

CREATE OR REPLACE FUNCTION ag_get_barcodes (
    user_data_ refcursor
)
 RETURNS refcursor AS $body$
BEGIN

    open user_data_ for
        SELECT  barcode
        from    ag_kit_barcodes
        order by barcode;
    return user_data_;
end;
/*
begin;
select ag_get_barcodes('a');
fetch all in a;
commit;
*/

$body$
LANGUAGE PLPGSQL;


text:
from __future__ import unicode_literals
import os, sys

def replace_code(start, txt1, txt2, extn, search=None, force=False):
	"""replace all txt1 by txt2 in files with extension (extn)"""
	import webnotes.utils
	import os, re
	esc = webnotes.utils.make_esc('[]')
	if not search: search = esc(txt1)
	for wt in os.walk(start, followlinks=1):
		for fn in wt[2]:
			if fn.split('.')[-1]==extn:
				fpath = os.path.join(wt[0], fn)
				with open(fpath, 'r') as f:
					content = f.read()

				if re.search(search, content):
					res = search_replace_with_prompt(fpath, txt1, txt2, force)
					if res == 'skip':
						return 'skip'

def search_replace_with_prompt(fpath, txt1, txt2, force=False):
	""" Search and replace all txt1 by txt2 in the file with confirmation"""

	from termcolor import colored
	with open(fpath, 'r') as f:
		content = f.readlines()

	tmp = []
	for c in content:
		if c.find(txt1) != -1:
			print fpath
			print  colored(txt1, 'red').join(c[:-1].split(txt1))
			a = ''
			if force:
				c = c.replace(txt1, txt2)
			else:
				while a.lower() not in ['y', 'n', 'skip']:
					a = raw_input('Do you want to Change [y/n/skip]?')
				if a.lower() == 'y':
					c = c.replace(txt1, txt2)
				elif a.lower() == 'skip':
					return 'skip'
		tmp.append(c)

	with open(fpath, 'w') as f:
		f.write(''.join(tmp))
	print colored('Updated', 'green')

def pull(remote, branch, build=False):
	os.system('cd lib && git pull %s %s' % (remote, branch))
	os.system('cd app && git pull %s %s' % (remote, branch))
	if build: rebuild()

def rebuild():
	# build js / css
	from webnotes.utils import bundlejs
	bundlejs.bundle(False)

def apply_latest_patches():
	import webnotes.modules.patch_handler
	webnotes.modules.patch_handler.run_all()
	print '\n'.join(webnotes.modules.patch_handler.log_list)

def sync_all(force=0):
	import webnotes.model.sync
	webnotes.model.sync.sync_all(force)

def update_erpnext(remote='origin', branch='master'):
	pull(remote, branch)
	from webnotes.utils import execute_in_shell
	execute_in_shell("lib/wnf.py --patch_sync_build", verbose=1)

def patch_sync_build():
	patch_sync()
	rebuild()

def patch_sync():
	apply_latest_patches()

	import webnotes.modules.patch_handler
	for l in webnotes.modules.patch_handler.log_list:
		if "failed: STOPPED" in l:
			return

	sync_all()

	clear_cache()

def clear_cache():
	import webnotes.sessions
	webnotes.sessions.clear_cache()

def append_future_import():
	"""appends from __future__ import unicode_literals to py files if necessary"""
	import os
	import conf
	conf_path = os.path.abspath(conf.__file__)
	if conf_path.endswith("pyc"):
		conf_path = conf_path[:-1]

	base_path = os.path.dirname(conf_path)

	for path, folders, files in os.walk(base_path):
		for f in files:
			if f.endswith('.py'):
				file_path = os.path.join(path, f)
				with open(file_path, 'r') as pyfile:
					content = pyfile.read()
				future_import = 'from __future__ import unicode_literals'

				if future_import in content: continue

				content = content.split('\n')
				idx = -1
				for c in content:
					idx += 1
					if c and not c.startswith('#'):
						break
				content.insert(idx, future_import)
				content = "\n".join(content)
				with open(file_path, 'w') as pyfile:
					pyfile.write(content)

def setup_options():
	from optparse import OptionParser
	parser = OptionParser()

	# install
	parser.add_option('--install', nargs=2, metavar = "NEW_DB_NAME SOURCE_PATH",
						help="install db")

	parser.add_option('--install_fresh', nargs=1, metavar = "NEW_DB_NAME",
						help="install fresh db")

	# update
	parser.add_option("--update", help="Pull, run latest patches and sync all",
			nargs=2, metavar="ORIGIN BRANCH")

	parser.add_option("--backup", help="Takes backup of database in backup folder",
		default=False, action="store_true")

	# build
	parser.add_option("-b", "--build", default=False, action="store_true",
						help="minify + concat js files")
	parser.add_option("-w", "--watch", default=False, action="store_true",
						help="watch and minify + concat js files, if necessary")
	parser.add_option("--no_cms", default=False, action="store_true",
						help="do not build wn-web.js and wn-css.js")

	parser.add_option("-d", "--db",
						dest="db_name",
						help="Apply the patches on given db")
	parser.add_option("--password",
						help="Password for given db", nargs=1)

	parser.add_option("--clear_web", default=False, action="store_true",
						help="clear web cache")
	parser.add_option("--clear_cache", default=False, action="store_true",
						help="clear cache")
	parser.add_option("--clear_defaults", default=False, action="store_true",
						help="clear cache of defaults")

	parser.add_option("--domain", metavar="DOMAIN",
						help="store domain in Website Settings", nargs=1)

	# git
	parser.add_option("--status", default=False, action="store_true",
						help="git status")
	parser.add_option("--git", nargs=1, default=False,
						metavar = "git options",
						help="run git with options in both repos")
	parser.add_option("--pull", nargs=2, default=False,
						metavar = "remote branch",
						help="git pull (both repos)")

	parser.add_option("--commit", nargs=1, default=False,
						metavar = "commit both repos",
						help="git commit -a -m [comment]")
	parser.add_option("--push", nargs=2, default=False,
						metavar = "remote branch",
						help="git push (both repos) [remote] [branch]")
	parser.add_option("--checkout", nargs=1, default=False,
						metavar = "branch",
						help="git checkout [branch]")

	parser.add_option("-l", "--latest",
						action="store_true", dest="run_latest", default=False,
						help="Apply the latest patches")

	# patch
	parser.add_option("-p", "--patch", nargs=1, dest="patch_list", metavar='patch_module',
						action="append",
						help="Apply patch")
	parser.add_option("-f", "--force",
						action="store_true", dest="force", default=False,
						help="Force Apply all patches specified using option -p or --patch")
	parser.add_option('--reload_doc', nargs=3, metavar = "module doctype docname",
						help="reload doc")
	parser.add_option('--export_doc', nargs=2, metavar = "doctype docname",
						help="export doc")

	# diff
	parser.add_option('--diff_ref_file', nargs=0, \
						help="Get missing database records and mismatch properties, with file as reference")
	parser.add_option('--diff_ref_db', nargs=0, \
						help="Get missing .txt files and mismatch properties, with database as reference")

	# scheduler
	parser.add_option('--run_scheduler', default=False, action="store_true",
						help="Trigger scheduler")
	parser.add_option('--run_scheduler_event', nargs=1, metavar="[all|daily|weekly|monthly]",
						help="Run scheduler event")

	# misc
	parser.add_option("--replace", nargs=3, default=False,
						metavar = "search replace_by extension",
						help="file search-replace")

	parser.add_option("--sync_all", help="Synchronize all DocTypes using txt files",
			nargs=0)

	parser.add_option("--sync", help="Synchronize given DocType using txt file",
			nargs=2, metavar="module doctype (use their folder names)")

	parser.add_option("--patch_sync_build", action="store_true", default=False,
		help="run latest patches, sync all and rebuild js css")

	parser.add_option("--patch_sync", action="store_true", default=False,
		help="run latest patches, sync all")

	parser.add_option("--cleanup_data", help="Cleanup test data", default=False,
			action="store_true")

	parser.add_option("--append_future_import", default=False, action="store_true",
			help="append from __future__ import unicode literals to py files")

	parser.add_option("--test", help="Run test", metavar="MODULE",
			nargs=1)

	parser.add_option("--build_message_files", default=False, action="store_true",
		help="Build message files for translation")

	parser.add_option('--export_messages', nargs=2, metavar="LANG FILENAME",
		help="""Export all messages for a language to translation in a csv file.
		Example, lib/wnf.py --export_messages hi hindi.csv""")

	parser.add_option('--import_messages', nargs=2, metavar="LANG FILENAME",
		help="""Import messages for a language and make language files.
		Example, lib/wnf.py --import_messages hi hindi.csv""")

	parser.add_option('--google_translate', nargs=3, metavar="LANG INFILE OUTFILE",
		help="""Auto translate using Google Translate API""")

	parser.add_option('--translate', nargs=1, metavar="LANG",
		help="""Rebuild translation for the given langauge and
		use Google Translate to tranlate untranslated messages. use "all" """)

	return parser.parse_args()

def run():
	sys.path.append('.')
	sys.path.append('lib')
	sys.path.append('app')

	(options, args) = setup_options()

	# build
	if options.build:
		from webnotes.utils import bundlejs
		if options.no_cms:
			cms_make = False
		else:
			cms_make = True
		bundlejs.bundle(False, cms_make)
		return

	elif options.watch:
		from webnotes.utils import bundlejs
		bundlejs.watch(True)
		return

	# code replace
	elif options.replace:
		print options.replace
		replace_code('.', options.replace[0], options.replace[1], options.replace[2], force=options.force)
		return

	# git
	elif options.status:
		os.chdir('lib')
		os.system('git status')
		os.chdir('../app')
		os.system('git status')
		return

	elif options.git:
		os.chdir('lib')
		os.system('git %s' % options.git)
		os.chdir('../app')
		os.system('git %s' % options.git)
		return

	import webnotes
	import conf
	from webnotes.db import Database
	import webnotes.modules.patch_handler

	# connect
	if options.db_name is not None:
		if options.password:
			webnotes.connect(options.db_name, options.password)
		else:
			webnotes.connect(options.db_name)
	elif not any([options.install, options.pull, options.install_fresh]):
		webnotes.connect(conf.db_name)

	if options.pull:
		pull(options.pull[0], options.pull[1], build=True)

	elif options.commit:
		os.chdir('lib')
		os.system('git commit -a -m "%s"' % (options.commit))
		os.chdir('../app')
		os.system('git commit -a -m "%s"' % (options.commit))

	elif options.push:
		os.chdir('lib')
		os.system('git push %s %s' % (options.push[0], options.push[1]))
		os.chdir('../app')
		os.system('git push %s %s' % (options.push[0], options.push[1]))

	elif options.checkout:
		os.chdir('lib')
		os.system('git checkout %s' % options.checkout)
		os.chdir('../app')
		os.system('git checkout %s' % options.checkout)

	# patch
	elif options.patch_list:
		# clear log
		webnotes.modules.patch_handler.log_list = []

		# run individual patches
		for patch in options.patch_list:
			webnotes.modules.patch_handler.run_single(\
				patchmodule = patch, force = options.force)

		print '\n'.join(webnotes.modules.patch_handler.log_list)

		# reload
	elif options.reload_doc:
		webnotes.modules.patch_handler.reload_doc(\
			{"module":options.reload_doc[0], "dt":options.reload_doc[1], "dn":options.reload_doc[2]})
		print '\n'.join(webnotes.modules.patch_handler.log_list)

	elif options.export_doc:
		from webnotes.modules import export_doc
		export_doc(options.export_doc[0], options.export_doc[1])

	# run all pending
	elif options.run_latest:
		apply_latest_patches()

	elif options.install:
		from webnotes.install_lib.install import Installer
		inst = Installer('root')
		inst.import_from_db(options.install[0], source_path=options.install[1],
			verbose = 1)

	elif options.install_fresh:
		from webnotes.install_lib.install import Installer
		inst = Installer('root')
		inst.import_from_db(options.install_fresh, source_path="lib/conf/Framework.sql",
			verbose = 1)

	elif options.diff_ref_file is not None:
		import webnotes.modules.diff
		webnotes.modules.diff.diff_ref_file()

	elif options.diff_ref_db is not None:
		import webnotes.modules.diff
		webnotes.modules.diff.diff_ref_db()

	elif options.run_scheduler:
		import webnotes.utils.scheduler
		print webnotes.utils.scheduler.execute()

	elif options.run_scheduler_event is not None:
		import webnotes.utils.scheduler
		print webnotes.utils.scheduler.trigger('execute_' + options.run_scheduler_event)

	elif options.sync_all is not None:
		sync_all(options.force or 0)

	elif options.sync is not None:
		webnotes.reload_doc(options.sync[0], "doctype", options.sync[1])

	elif options.update:
		update_erpnext(options.update[0], options.update[1])

	elif options.patch_sync_build:
		patch_sync_build()

	elif options.patch_sync:
		patch_sync()

	elif options.cleanup_data:
		from utilities import cleanup_data
		cleanup_data.run()

	elif options.domain:
		webnotes.conn.set_value('Website Settings', None, 'subdomain', options.domain)
		webnotes.conn.commit()
		print "Domain set to", options.domain

	elif options.clear_web:
		# build wn-web.js and wn-web.css
		from website.helpers.make_web_include_files import make
		make()

		import webnotes.webutils
		webnotes.webutils.clear_cache()

	elif options.clear_cache:
		clear_cache()

	elif options.clear_defaults:
		import webnotes.defaults
		webnotes.defaults.clear_cache()
		webnotes.clear_cache()

	elif options.append_future_import:
		append_future_import()

	elif options.backup:
		from webnotes.utils.backups import scheduled_backup
		scheduled_backup(ignore_files = True)

	# print messages
	if webnotes.message_log:
		print '\n'.join(webnotes.message_log)

	if options.test is not None:
		module_name = options.test
		import unittest

		del sys.argv[1:]
		# is there a better way?
		exec ('from %s import *' % module_name) in globals()
		unittest.main()

	elif options.build_message_files:
		import webnotes.translate
		webnotes.translate.build_message_files()

	elif options.export_messages:
		import webnotes.translate
		webnotes.translate.export_messages(*options.export_messages)

	elif options.import_messages:
		import webnotes.translate
		webnotes.translate.import_messages(*options.import_messages)

	elif options.google_translate:
		from webnotes.translate import google_translate
		google_translate(*options.google_translate)

	elif options.translate:
		from webnotes.translate import build_message_files, \
			export_messages, google_translate, import_messages

		languages = [options.translate]
		if options.translate=="all":
			from startup import lang_list
			languages = lang_list

		print "Extracting messages..."
		build_message_files()
		for lang in languages:
			if lang != "en":
				filename = 'app/translations/'+lang+'.csv'
				print "For " + lang + ":"
				print "Compiling messages in one file..."
				export_messages(lang, '_lang_tmp.csv')
				print "Translating via Google Translate..."
				google_translate(lang, '_lang_tmp.csv', filename)
				print "Updating language files..."
				import_messages(lang, filename)
				print "Deleting temp files..."
				os.remove('_lang_tmp.csv')

if __name__=='__main__':
	run()


text:
// Copyright (C) 2008 The Android Open Source Project
//
// 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.google.gerrit.client.changes;

import static com.google.gerrit.client.FormatUtil.shortFormat;

import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.ui.AccountLinkPanel;
import com.google.gerrit.client.ui.BranchLink;
import com.google.gerrit.client.ui.ChangeLink;
import com.google.gerrit.client.ui.NavigationTable;
import com.google.gerrit.client.ui.NeedsSignInKeyCommand;
import com.google.gerrit.client.ui.ProjectLink;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.common.data.AccountInfoCache;
import com.google.gerrit.common.data.ChangeInfo;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ChangeTable extends NavigationTable<ChangeInfo> {
  private static final int C_STAR = 1;
  private static final int C_SUBJECT = 2;
  private static final int C_OWNER = 3;
  private static final int C_PROJECT = 4;
  private static final int C_BRANCH = 5;
  private static final int C_LAST_UPDATE = 6;
  private static final int COLUMNS = 7;

  private final List<Section> sections;
  private AccountInfoCache accountCache = AccountInfoCache.empty();

  public ChangeTable() {
    super(Util.C.changeItemHelp());

    if (Gerrit.isSignedIn()) {
      keysAction.add(new StarKeyCommand(0, 's', Util.C.changeTableStar()));
    }

    sections = new ArrayList<Section>();
    table.setText(0, C_STAR, "");
    table.setText(0, C_SUBJECT, Util.C.changeTableColumnSubject());
    table.setText(0, C_OWNER, Util.C.changeTableColumnOwner());
    table.setText(0, C_PROJECT, Util.C.changeTableColumnProject());
    table.setText(0, C_BRANCH, Util.C.changeTableColumnBranch());
    table.setText(0, C_LAST_UPDATE, Util.C.changeTableColumnLastUpdate());

    final FlexCellFormatter fmt = table.getFlexCellFormatter();
    fmt.addStyleName(0, C_STAR, Gerrit.RESOURCES.css().iconHeader());
    for (int i = C_SUBJECT; i < COLUMNS; i++) {
      fmt.addStyleName(0, i, Gerrit.RESOURCES.css().dataHeader());
    }

    table.addClickHandler(new ClickHandler() {
      @Override
      public void onClick(final ClickEvent event) {
        final Cell cell = table.getCellForEvent(event);
        if (cell == null) {
          return;
        }
        if (cell.getCellIndex() == C_STAR) {
          // Don't do anything (handled by star itself).
        } else if (cell.getCellIndex() == C_OWNER) {
          // Don't do anything.
        } else if (getRowItem(cell.getRowIndex()) != null) {
          movePointerTo(cell.getRowIndex());
        }
      }
    });
  }

  protected void onStarClick(final int row) {
    final ChangeInfo c = getRowItem(row);
    if (c != null && Gerrit.isSignedIn()) {
      ((StarredChanges.Icon) table.getWidget(row, C_STAR)).toggleStar();
    }
  }

  @Override
  protected Object getRowItemKey(final ChangeInfo item) {
    return item.getId();
  }

  @Override
  protected void onOpenRow(final int row) {
    final ChangeInfo c = getRowItem(row);
    Gerrit.display(PageLinks.toChange(c), new ChangeScreen(c));
  }

  private void insertNoneRow(final int row) {
    insertRow(row);
    table.setText(row, 0, Util.C.changeTableNone());
    final FlexCellFormatter fmt = table.getFlexCellFormatter();
    fmt.setColSpan(row, 0, COLUMNS);
    fmt.setStyleName(row, 0, Gerrit.RESOURCES.css().emptySection());
  }

  private void insertChangeRow(final int row) {
    insertRow(row);
    applyDataRowStyle(row);
  }

  @Override
  protected void applyDataRowStyle(final int row) {
    super.applyDataRowStyle(row);
    final CellFormatter fmt = table.getCellFormatter();
    fmt.addStyleName(row, C_STAR, Gerrit.RESOURCES.css().iconCell());
    for (int i = C_SUBJECT; i < COLUMNS; i++) {
      fmt.addStyleName(row, i, Gerrit.RESOURCES.css().dataCell());
    }
    fmt.addStyleName(row, C_SUBJECT, Gerrit.RESOURCES.css().cSUBJECT());
    fmt.addStyleName(row, C_OWNER, Gerrit.RESOURCES.css().cOWNER());
    fmt.addStyleName(row, C_LAST_UPDATE, Gerrit.RESOURCES.css().cLastUpdate());
  }

  private void populateChangeRow(final int row, final ChangeInfo c,
      final ChangeRowFormatter changeRowFormatter) {
    ChangeCache cache = ChangeCache.get(c.getId());
    cache.getChangeInfoCache().set(c);

    table.setWidget(row, C_ARROW, null);
    if (Gerrit.isSignedIn()) {
      table.setWidget(row, C_STAR, StarredChanges.createIcon(c.getId(), c.isStarred()));
    }

    String s = Util.cropSubject(c.getSubject());
    if (c.getStatus() != null && c.getStatus() != Change.Status.NEW) {
      s += " (" + c.getStatus().name() + ")";
    }
    if (changeRowFormatter != null) {
      removeChangeStyle(row, changeRowFormatter);
      final String rowStyle = changeRowFormatter.getRowStyle(c);
      if (rowStyle != null) {
        table.getRowFormatter().addStyleName(row, rowStyle);
      }
      s = changeRowFormatter.getDisplayText(c, s);
    }

    table.setWidget(row, C_SUBJECT, new TableChangeLink(s, c));
    table.setWidget(row, C_OWNER, link(c.getOwner()));
    table.setWidget(row, C_PROJECT, new ProjectLink(c.getProject().getKey(), c
        .getStatus()));
    table.setWidget(row, C_BRANCH, new BranchLink(c.getProject().getKey(), c
        .getStatus(), c.getBranch(), c.getTopic()));
    table.setText(row, C_LAST_UPDATE, shortFormat(c.getLastUpdatedOn()));

    setRowItem(row, c);
  }

  private void removeChangeStyle(int row,
      final ChangeRowFormatter changeRowFormatter) {
    final ChangeInfo oldChange = getRowItem(row);
    if (oldChange == null) {
      return;
    }

    final String oldRowStyle = changeRowFormatter.getRowStyle(oldChange);
    if (oldRowStyle != null) {
      table.getRowFormatter().removeStyleName(row, oldRowStyle);
    }
  }

  private AccountLinkPanel link(final Account.Id id) {
    return AccountLinkPanel.link(accountCache, id);
  }

  public void addSection(final Section s) {
    assert s.parent == null;

    if (s.titleText != null) {
      s.titleRow = table.getRowCount();
      table.setText(s.titleRow, 0, s.titleText);
      final FlexCellFormatter fmt = table.getFlexCellFormatter();
      fmt.setColSpan(s.titleRow, 0, COLUMNS);
      fmt.addStyleName(s.titleRow, 0, Gerrit.RESOURCES.css().sectionHeader());
    } else {
      s.titleRow = -1;
    }

    s.parent = this;
    s.dataBegin = table.getRowCount();
    insertNoneRow(s.dataBegin);
    sections.add(s);
  }

  public void setAccountInfoCache(final AccountInfoCache aic) {
    assert aic != null;
    accountCache = aic;
  }

  private int insertRow(final int beforeRow) {
    for (final Section s : sections) {
      if (beforeRow <= s.titleRow) {
        s.titleRow++;
      }
      if (beforeRow < s.dataBegin) {
        s.dataBegin++;
      }
    }
    return table.insertRow(beforeRow);
  }

  private void removeRow(final int row) {
    for (final Section s : sections) {
      if (row < s.titleRow) {
        s.titleRow--;
      }
      if (row < s.dataBegin) {
        s.dataBegin--;
      }
    }
    table.removeRow(row);
  }

  public class StarKeyCommand extends NeedsSignInKeyCommand {
    public StarKeyCommand(int mask, char key, String help) {
      super(mask, key, help);
    }

    @Override
    public void onKeyPress(final KeyPressEvent event) {
      onStarClick(getCurrentRow());
    }
  }

  private final class TableChangeLink extends ChangeLink {
    private TableChangeLink(final String text, final ChangeInfo c) {
      super(text, c);
    }

    @Override
    public void go() {
      movePointerTo(cid);
      super.go();
    }
  }

  public static class Section {
    String titleText;

    ChangeTable parent;
    final Account.Id ownerId;
    int titleRow = -1;
    int dataBegin;
    int rows;

    private ChangeRowFormatter changeRowFormatter;

    public Section() {
      this(null, null);
    }

    public Section(final String titleText) {
      this(titleText, null);
    }

    public Section(final String titleText, final Account.Id owner) {
      setTitleText(titleText);
      ownerId = owner;
    }

    public void setTitleText(final String text) {
      titleText = text;
      if (titleRow >= 0) {
        parent.table.setText(titleRow, 0, titleText);
      }
    }

    public void setChangeRowFormatter(final ChangeRowFormatter changeRowFormatter) {
      this.changeRowFormatter = changeRowFormatter;
    }

    public void display(final List<ChangeInfo> changeList) {
      final int sz = changeList != null ? changeList.size() : 0;
      final boolean hadData = rows > 0;

      if (hadData) {
        while (sz < rows) {
          parent.removeRow(dataBegin);
          rows--;
        }
      }

      if (sz == 0) {
        if (hadData) {
          parent.insertNoneRow(dataBegin);
        }
      } else {
        Set<Change.Id> cids = new HashSet<Change.Id>();

        if (!hadData) {
          parent.removeRow(dataBegin);
        }

        while (rows < sz) {
          parent.insertChangeRow(dataBegin + rows);
          rows++;
        }

        for (int i = 0; i < sz; i++) {
          ChangeInfo c = changeList.get(i);
          parent.populateChangeRow(dataBegin + i, c, changeRowFormatter);
          cids.add(c.getId());
        }
      }
    }
  }

  public static interface ChangeRowFormatter {
    /**
     * Returns the name of the CSS style that should be applied to the change
     * row.
     *
     * @param c the change for which the styling should be returned
     * @return the name of the CSS style that should be applied to the change
     *         row
     */
    String getRowStyle(ChangeInfo c);

    /**
     * Returns the text that should be displayed for the change.
     *
     * @param c the change for which the display text should be returned
     * @param displayText the current display text
     * @return the new display text
     */
    String getDisplayText(ChangeInfo c, String displayText);
  }
}


text: ierkan repository


text:
title: Session Handling
description: This tutorial will show you how to integrate Auth0 with angular2 to add session handling and logout to your web app.
budicon: 280
---

<%= include('../../../_includes/_package', {
  org: 'auth0-samples',
  repo: 'auth0-angularjs2-systemjs-sample',
  path: '03-Session-Handling',
  requirements: [
    'Angular 2.0.1'
  ]
}) %>

In the previous steps of this tutorial, we enabled user login with the `Lock` widget and then with `auth0.js`.

In this step, we will create a session for the user and also allow them to log out.

## Create Session

Once the user is authenticated, we need to create a client-side session for them so that our Angular 2 app knows that they are currently authenticated. To do this, we need to store the value of the `id_token` attribute that is returned in the Lock `authenticated` callback parameter.

**NOTE**: This example uses `localStorage`, but you can use any storage library.

```typescript
// auth.service.ts

@Injectable()
export class Auth {
  // Configure Auth0
  lock = new Auth0Lock('${account.clientId}', '${account.namespace}', {});

  constructor() {
    // Add callback for lock `authenticated` event
    this.lock.on("authenticated", (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);
    });
  }
  // ...
}
```

## Check Session

To check if a user is authenticated, we can use `tokenNotExpired` from [angular2-jwt](https://github.com/auth0/angular2-jwt) which allows us to check whether the user's JWT is expired or not. Since JWT is a "stateless" manner of doing user authentication, the best way to know if the user should be regarded as authenticated on the front end is to know whether the token is unexpired.

```typescript
// auth.service.ts

import { tokenNotExpired } from 'angular2-jwt';

// ...
public authenticated() {
  // Check if there's an unexpired JWT
  // It searches for an item in localStorage with key == 'id_token' by default
  return tokenNotExpired();
}
```

To use this service, inject `Auth` into your component:

```typescript
// app/app.component.ts

@Component({
    selector: 'my-app',
    providers: [ Auth ],
    templateUrl: 'app/app.template.html'
})

export class AppComponent {
  constructor(private auth: Auth) {}
}
```

and then use it in your component's template:

```html
  <!-- app/app.template.html -->
  <div class="navbar-header">
    <a class="navbar-brand" href="#">Auth0 - Angular 2</a>
    <button class="btn btn-primary btn-margin" (click)="auth.login()" *ngIf="!auth.authenticated()">Log In</button>
    <button class="btn btn-primary btn-margin" (click)="auth.logout()" *ngIf="auth.authenticated()">Log Out</button>
  </div>
```

## Logout

Since authentication with JWT is stateless, the only thing necessary for logging the user out is to remove their token from storage.

```typescript
// auth.service.ts

// ...
public logout() {
  // Remove token from localStorage
  localStorage.removeItem('id_token');
}
```


text:
import os
import sys

from orizuru.config import Config

from fabric.api import *

from fabric.colors import green, yellow, red
from fabric.utils import puts

import cuisine

from netaddr import IPNetwork as CIDR

metadata = Config(os.environ["CONFIGFILE"])

@roles('all_servers')
def stage4():
    metadata = Config(os.environ["CONFIGFILE"])

    if cuisine.file_exists("/tmp/.%s.lck" % sys._getframe().f_code.co_name):
        return

    run("""

cat >/etc/default/docker<<EOF
DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
EOF

service docker restart

sleep 10

""")

    run("docker ps")

    run("docker images")

    for container in sorted(metadata.containers):
        server = metadata.containers[container]["server"]
        container_ip = metadata.containers[container]["ip"]
        role = metadata.containers[container]["role"]

        #
        # only create a container on this host if the container belongs on it
        #
        if server == env.host_string:
            puts(green("creating/configuring container on server %s with ip %s for role %s" % (server, container_ip, role)))

            dockerfile = "/tmp/Dockerfile_orizuru_%s" % server

            cuisine.file_write(dockerfile,
"""
#
# orizuru base image for all Midonet and Openstack services
#
# VERSION               0.1.0
#

FROM %s:%s

MAINTAINER Alexander Gabert <alexander@midokura.com>

RUN sed -i 's,deb http://archive.ubuntu.com,deb %s/%s.archive.ubuntu.com,g;' /etc/apt/sources.list
RUN sed -i 's,deb-src http://archive.ubuntu.com,deb-src %s/%s.archive.ubuntu.com,g;' /etc/apt/sources.list

RUN sync

RUN cat /etc/apt/sources.list

RUN rm -rf /var/lib/apt/lists
RUN mkdir -p /var/lib/apt/lists/partial
RUN apt-get clean
RUN apt-get autoclean
RUN apt-get update 1>/dev/null
RUN DEBIAN_FRONTEND=noninteractive apt-get -y -u dist-upgrade 1>/dev/null

RUN DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server screen
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config

RUN DEBIAN_FRONTEND=noninteractive apt-get install -y %s

RUN mkdir -pv /var/run/screen
RUN chmod 0777 /var/run/screen

RUN chmod 0755 /usr/bin/screen
RUN mkdir -pv /var/run/sshd

RUN echo 'LANG="en_US.UTF-8"' | tee /etc/default/locale
RUN locale-gen en_US.UTF-8

RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

RUN mkdir -pv /root/.ssh
RUN chmod 0755 /root/.ssh

COPY /root/.ssh/authorized_keys /root/.ssh/authorized_keys

ENV NOTVISIBLE "in users profile"

RUN echo "export VISIBLE=now" >> /etc/profile

RUN sync

EXPOSE 22

CMD ["/usr/sbin/sshd", "-D"]

""" % (
        metadata.config["container_os"],
        metadata.config["container_os_version"],
        metadata.config["apt-cacher"],
        metadata.config["archive_country"],
        metadata.config["apt-cacher"],
        metadata.config["archive_country"],
        metadata.config["common_packages"]
        ))

            run("""

SERVER_NAME="%s"
CONTAINER_ROLE="%s"
DOCKERFILE="/tmp/Dockerfile_orizuru_${SERVER_NAME}"

cd "$(mktemp -d)"

cp "${DOCKERFILE}" Dockerfile

mkdir -pv root/.ssh

cat /root/.ssh/authorized_keys > root/.ssh/authorized_keys

echo nameserver 8.8.8.8 | tee /etc/resolv.conf

echo 1 > /proc/sys/net/ipv6/conf/all/disable_ipv6

docker images | grep "template_${SERVER_NAME}" || docker build --no-cache=true -t "template_${SERVER_NAME}" .

mkdir -pv /etc/rc.local.d

""" % (
        server,
        role
     ))

            cuisine.file_write("/etc/rc.local.d/docker_%s_%s" % (role, server),
"""#!/bin/bash
#
# adapted from https://docs.docker.com/articles/networking/#building-your-own-bridge
#

DOCKER_BRIDGE="dockertinc"
SERVER_NAME="%s"
CONTAINER_IP="%s"
CONTAINER_ROLE="%s"
CONTAINER_DEFAULT_GW="%s"
CONTAINER_NETMASK="%s"
CONTAINER_NETWORK="%s"
DOMAIN_NAME="%s"
SERVER_IP="%s"
FIP_BASE="%s"

MIDONET_API_IP="%s"
MIDONET_API_OUTER_IP="%s"

MTU_CONTAINER="%s"

CONTAINER_VETH="${RANDOM}"

NETNS_NAME="docker_${CONTAINER_VETH}_${CONTAINER_ROLE}_${SERVER_NAME}"

CONTAINER_VETH_A="${CONTAINER_VETH}A"
CONTAINER_VETH_B="${CONTAINER_VETH}B"

CONTAINER_ETC_HOSTS="/etc/hosts"

DEFAULT_GW_IFACE="$(ip route show | grep 'default via' | awk -Fdev '{print $2;}' | xargs -n1 echo)"

if [[ "${DEFAULT_GW_IFACE}" == "" ]]; then
    exit 1
fi

if [[ "$(ps axufwwwwwwwwwwwwwww | grep -v grep | grep -v SCREEN | grep -- "docker run -h ${CONTAINER_ROLE}_${SERVER_NAME}")" == "" ]]; then
    #
    # start the container in a screen session
    #
    screen -d -m -- docker run -h "${CONTAINER_ROLE}_${SERVER_NAME}" --privileged=true -i -t --rm --net="none" --name "${CONTAINER_VETH}_${CONTAINER_ROLE}_${SERVER_NAME}" "template_${SERVER_NAME}"

    for i in $(seq 1 120); do
        CONTAINER_ID="$(docker ps | grep "${CONTAINER_VETH}_${CONTAINER_ROLE}_${SERVER_NAME}" | awk '{print $1;}')"

        if [[ "" == "${CONTAINER_ID}" ]]; then
            sleep 1
        else
            break
        fi
    done

    if [[ "" == "${CONTAINER_ID}" ]]; then
        echo "container failed to spawn."
        exit 1
    fi

    CONTAINER_PID="$(docker inspect -f '{{.State.Pid}}' "${CONTAINER_ID}")"

    if [[ "${CONTAINER_PID}" == "" ]]; then
        echo "container failed to spawn."
        exit 1
    fi

    #
    # link the network namespace of the spawned container to make it a non-anonymous ip namespace
    #
    mkdir -p "/var/run/netns"
    ln -s "/proc/${CONTAINER_PID}/ns/net" "/var/run/netns/${NETNS_NAME}"

    #
    # add the veth pair for this container
    #
    ip link add "${CONTAINER_VETH_A}" type veth peer name "${CONTAINER_VETH_B}"

    #
    # add one side of the pair to our master bridge for the container network on this host (routed by tinc)
    #
    brctl addif "${DOCKER_BRIDGE}" "${CONTAINER_VETH_A}"

    #
    # set up networking for the container in our main namespace
    #
    ip link set "${CONTAINER_VETH_A}" up
    ip link set dev "${CONTAINER_VETH_A}" mtu "${MTU_CONTAINER}"

    #
    # set up networking in the container namespace
    #
    ip link set "${CONTAINER_VETH_B}" netns "${NETNS_NAME}"
    ip netns exec "${NETNS_NAME}" ip link set dev "${CONTAINER_VETH_B}" name eth0
    ip netns exec "${NETNS_NAME}" ip link set eth0 up
    ip netns exec "${NETNS_NAME}" ip addr add "${CONTAINER_IP}/${CONTAINER_NETMASK}" dev eth0
    ip netns exec "${NETNS_NAME}" ip route add default via "${CONTAINER_DEFAULT_GW}"
    ip netns exec "${NETNS_NAME}" ip link set dev eth0 mtu "${MTU_CONTAINER}"

else
    CONTAINER_ID="$(docker ps | grep -v '^CONTAINER' | grep -- "${CONTAINER_ROLE}_${SERVER_NAME}" | awk '{print $1;}' | head -n1)"
fi

#
# the /etc/hosts could have been updated in the meantime, add it to the container even when its already running
#
CONTAINER_HOSTS_PATH="$(docker ps | grep -v ^CONTAINER | grep "^${CONTAINER_ID}" | awk '{print $1;}' | xargs -n1 --no-run-if-empty docker inspect --format "{{ .HostsPath }}")"
cat "${CONTAINER_ETC_HOSTS}" >"${CONTAINER_HOSTS_PATH}"

""" % (
        server,
        container_ip,
        role,
        CIDR(metadata.servers[server]["dockernet"])[1],
        CIDR(metadata.servers[server]["dockernet"]).netmask,
        CIDR(metadata.servers[server]["dockernet"])[0],
        metadata.config["domain"],
        metadata.servers[server]["ip"],
        metadata.config["fip_base"],
        metadata.containers[metadata.roles["container_midonet_api"][0]]["ip"],
        metadata.servers[metadata.roles["midonet_api"][0]]["ip"],
        metadata.config["mtu_container"]
    ))

            cuisine.file_write("/etc/rc.local.d/docker_%s_%s_NAT" % (role, server),
"""#!/bin/bash
#
# adapted from https://docs.docker.com/articles/networking/#building-your-own-bridge
#

DOCKER_BRIDGE="dockertinc"
SERVER_NAME="%s"
CONTAINER_IP="%s"
CONTAINER_ROLE="%s"
CONTAINER_DEFAULT_GW="%s"
CONTAINER_NETMASK="%s"
CONTAINER_NETWORK="%s"
DOMAIN_NAME="%s"
SERVER_IP="%s"
FIP_BASE="%s"

MIDONET_API_IP="%s"
MIDONET_API_OUTER_IP="%s"

CONTAINER_VETH="${RANDOM}"

NETNS_NAME="docker_${CONTAINER_VETH}_${CONTAINER_ROLE}_${SERVER_NAME}"

CONTAINER_VETH_A="${CONTAINER_VETH}A"
CONTAINER_VETH_B="${CONTAINER_VETH}B"

CONTAINER_ETC_HOSTS="/etc/hosts"

DEFAULT_GW_IFACE="$(ip route show | grep 'default via' | awk -Fdev '{print $2;}' | xargs -n1 echo)"

if [[ "${DEFAULT_GW_IFACE}" == "" ]]; then
    exit 1
fi

DEFAULT_GW_IFACE_IP="$(ip addr show dev ${DEFAULT_GW_IFACE} | grep 'inet ' | awk '{print $2;}' | awk -F'/' '{print $1;}' | xargs -n1 echo | head -n1)"

#
# SNAT the private ips talking to the outside world via this box (we need this for fakeuplink)
#
iptables -t nat --list -n -v | grep -A999999 'Chain POSTROUTING' | grep 'MASQUERADE' | grep "${DEFAULT_GW_IFACE}" | grep "${CONTAINER_IP}" | grep "0.0.0.0" || \
    iptables -t nat -I POSTROUTING -o "${DEFAULT_GW_IFACE}" -s "${CONTAINER_IP}/32" -j MASQUERADE

#
# do not SNAT if we talk to private networks
# we achieve this by inserting the rule before the masquerade rule that came above
#
for RFC1918 in "10.0.0.0/8" "172.16.0.0/12" "192.168.0.0/16"; do
    iptables -t nat --list -n -v | grep -A999999 'Chain POSTROUTING' | grep 'ACCEPT' | grep "${DEFAULT_GW_IFACE}" | grep "${CONTAINER_IP}" | grep "${RFC1918}" || \
        iptables -t nat -I POSTROUTING -o "${DEFAULT_GW_IFACE}" -s "${CONTAINER_IP}/32" -d "${RFC1918}" -j ACCEPT
done

""" % (
        server,
        container_ip,
        role,
        CIDR(metadata.servers[server]["dockernet"])[1],
        CIDR(metadata.servers[server]["dockernet"]).netmask,
        CIDR(metadata.servers[server]["dockernet"])[0],
        metadata.config["domain"],
        metadata.servers[server]["ip"],
        metadata.config["fip_base"],
        metadata.containers[metadata.roles["container_midonet_api"][0]]["ip"],
        metadata.servers[metadata.roles["midonet_api"][0]]["ip"]
    ))

            run("""
if [[ "%s" == "True" ]] ; then set -x; fi

SERVER_NAME="%s"
CONTAINER_ROLE="%s"

chmod 0755 /etc/rc.local.d/docker_${CONTAINER_ROLE}_${SERVER_NAME}
chmod 0755 /etc/rc.local.d/docker_${CONTAINER_ROLE}_${SERVER_NAME}_NAT

"/etc/rc.local.d/docker_${CONTAINER_ROLE}_${SERVER_NAME}"
"/etc/rc.local.d/docker_${CONTAINER_ROLE}_${SERVER_NAME}_NAT"

""" % (metadata.config["debug"], server, role))

    cuisine.file_write("/tmp/.%s.lck" % sys._getframe().f_code.co_name, "xoxo")

    puts(green("waiting for other servers to finish their container bootstrapping"))


text:
const gulp = require('gulp');
const del = require('del');
const compass = require('gulp-compass');
const tslint = require('gulp-tslint');
const watch = require('gulp-watch');
const tsc = require('gulp-typescript');
const inject = require('gulp-inject');
const sourcemaps = require('gulp-sourcemaps');
const runSequence = require('run-sequence');
const Config = new require('./gulpfile.config');
const config = new Config();
const fs = require('fs');

gulp.task('gen-ts-refs', function () {
    var target = gulp.src(config.appTypeScriptReferences);
    var sources = gulp.src([config.allTypeScript], {read: false});
    return target.pipe(inject(sources, {
        starttag: '//App exports',
        endtag: '//App exports - end',
        transform: function (filepath) {
            return '/// <reference path="..' + filepath + '" />';
        }
    })).pipe(gulp.dest(config.typings));
});

/**
 * Lint all custom TypeScript files.
 */
gulp.task('ts-lint', function () {
    return gulp.src(config.allTypeScript)
        .pipe(tslint())
        .pipe(tslint.report('prose'));
});

/**
 * Compile TypeScript and include references to library and app .d.ts files.
 */
gulp.task('compile-ts', function () {
    var sourceTsFiles = [config.allTypeScript,                //path to typescript files
        config.libraryTypeScriptDefinitions, //reference to library .d.ts files
        config.appTypeScriptReferences];     //reference to app.d.ts files

    var tsProject = tsc.createProject('tsconfig.json');

    var tsResult = gulp.src(sourceTsFiles)
        .pipe(sourcemaps.init())
        .pipe(tsc(tsProject));

    return tsResult.js
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('.'));
});

/**
 * Remove all generated JavaScript files from TypeScript compilation.
 */
gulp.task('clean-ts', function (cb) {
    var typeScriptGenFiles = [
        config.source +'**/*.js',    // path to all JS files auto gen'd by editor
        config.source +'**/*.js.map' // path to all sourcemap files auto gen'd by editor
    ];

    // delete the files
    del(typeScriptGenFiles, cb);
});

gulp.task('watch', function() {
    gulp.watch([config.allTypeScript], ['compile-ts', 'gen-ts-refs']);
    gulp.watch([config.allSassFiles], ['styles']);
});

gulp.task('styles', function () {
    return gulp.src(config.allSassFiles)
        .pipe(compass({
            config_file: 'config.rb',
            debug: false,
            css: 'src/components/',
            sass: 'src/components/'
        }));
});

gulp.task('copyTsc', function () {
    return gulp.src('Typescript/*.*')
        .pipe(gulp.dest('node_modules/gulp-typescript/node_modules/typescript/bin/'));
});

gulp.task('renameAngular', function () {
    var angularVersion = fs.readFileSync('package.json');
    var parts = /"angular2": "npm:angular2@\^(.*?)",/.exec(angularVersion);
    var angularFolderName = 'jspm_packages/npm/angular2@' + parts[1];
    if (fs.existsSync(angularFolderName)) {
        fs.renameSync(angularFolderName, 'jspm_packages/npm/angular2');
    }
    var config = fs.readFileSync('config.js', {encoding: 'utf8'});
    fs.writeFileSync('config.js', config.replace(/"npm:angular2@.*?"/g, '"npm:angular2"'))
});

gulp.task('install', ['copyTsc', 'renameAngular']);

gulp.task('default', function (callback) {
    runSequence('clean-ts', 'compile-ts', 'gen-ts-refs', 'styles', 'watch', callback);
});


text:
<?php

namespace Zend\Expressive\Hal\Metadata\Exception;

use RuntimeException;
use Zend\Expressive\Hal\Metadata\AbstractMetadata;
use Zend\Expressive\Hal\Metadata\MetadataMap;
use Zend\Expressive\Hal\Metadata\MetadataMapFactory;

class InvalidConfigException extends RuntimeException implements Exception
{
    /**
     * @param mixed $config
     */
    public static function dueToNonArray($config) : self
    {
        return new self(sprintf(
            'Invalid %s configuration; expected an array, but received %s',
            MetadataMap::class,
            is_object($config) ? get_class($config) : gettype($config)
        ));
    }

    public static function dueToNonArrayMetadata($metadata) : self
    {
        return new self(sprintf(
            'Invalid %s metadata item configuration; expected an array, but received %s',
            MetadataMap::class,
            is_object($metadata) ? get_class($metadata) : gettype($metadata)
        ));
    }

    public static function dueToMissingMetadataClass() : self
    {
        return new self('Unable to generate metadata; missing "__class__" element');
    }

    /**
     * @param mixed $class
     */
    public static function dueToInvalidMetadataClass($class) : self
    {
        $className = $class;
        if (! is_string($className)) {
            $className = is_object($class) ? get_class($class) : gettype($class);
        }
        return new self(sprintf(
            'Invalid metadata class provided: %s is not a class name',
            $className
        ));
    }

    public static function dueToNonMetadataClass(string $class) : self
    {
        return new self(sprintf(
            '%s is not a valid metadata class; does not extend %s',
            $class,
            AbstractMetadata::class
        ));
    }

    public static function dueToUnrecognizedMetadataClass(string $class, string $classWithoutNamespace) : self
    {
        return new self(sprintf(
            '%s does not know how to construct a %s instance; please extend the '
            . 'factory and create a "create%s" method',
            MetadataMapFactory::class,
            $class,
            $classWithoutNamespace
        ));
    }

    public static function dueToMissingMetadata(string $type, array $requiredKeys) : self
    {
        return new self(sprintf(
            'Unable to create HAL metadata of type %s; one or more of the '
            . 'following keys were missing: %s',
            $type,
            implode(', ', $requiredKeys)
        ));
    }
}


text:
//
// Copyright Microsoft Corporation.  All rights reserved.
// ericroz - Sept 2015
//

using System;
using System.Runtime.Serialization;

namespace ProviderFactory.Speech.RxToProjectOxford.Exceptions
{
    /// <summary>
    /// Exception thrown when initial silence in the audio exceeded the maximum limit.
    /// </summary>
    [Serializable]
    public class InitialSilenceTimeoutException : SpeechTimeoutException
    {
        /// <summary>
        /// Default constructor for <see cref="InitialSilenceTimeoutException"/>.
        /// </summary>
        public InitialSilenceTimeoutException() { }

        /// <summary>
        /// Message constructor for <see cref="InitialSilenceTimeoutException"/>.
        /// </summary>
        /// <param name="message">The exception message.</param>
        public InitialSilenceTimeoutException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Message and inner exception constructor for <see cref="InitialSilenceTimeoutException"/>.
        /// </summary>
        /// <param name="message">The exception message.</param>
        /// <param name="innerException">The inner exception.</param>
        public InitialSilenceTimeoutException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        /// <summary>
        /// Serialization context constructor for <see cref="InitialSilenceTimeoutException"/>.
        /// </summary>
        /// <param name="info">The serialization info.</param>
        /// <param name="context">The serialization context.</param>
        protected InitialSilenceTimeoutException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
    }
}


text:
(function () {
	var d = document;
	var c = {
		menuType:"canvas",
        COCOS2D_DEBUG:2, // full debug mode
		box2d:false, // no physics in this game
		chipmunk: false, // no chipmunk engine
		showFPS:false, // let's show the FPS meter
		frameRate:60, // 60 frames per second
		tag:"gameCanvas", // id of the canvas element
		engineDir: "../Cocos2d-html5/cocos2d/", // path to your cocos2d installation

		appFiles: ['src/Splash.js', 'src/SplashGame.js', 'src/SplashLudus.js','src/Menu.js','src/Game.js','src/Ship.js','src/Background.js']
	};

	window.addEventListener('DOMContentLoaded', function () {
		var s = d.createElement("script");
		s.src = c.engineDir + "platform/jsloader.js";
		d.body.appendChild(s);
		s.c = c;
		s.id = "cocos2d-html5";
		document.ccConfig = c;
	});
})();


text:
package datastore

import (
	"github.com/jmoiron/modl"
	"github.com/wolfeidau/assembly/assembly"
)

func init() {
	DB.AddTableWithName(assembly.User{}, "user").SetKeys(true, "ID")
}

type usersStore struct{ *Datastore }

func (s *usersStore) Get(login string) (*assembly.User, assembly.Response, error) {
	var users []*assembly.User
	if err := s.dbh.Select(&users, `SELECT * FROM public.user WHERE login=$1;`, login); err != nil {
		return nil, nil, err
	}
	if len(users) == 0 {
		return nil, nil, assembly.ErrUserNotFound
	}
	return users[0], nil, nil
}

func (s *usersStore) Create(user *assembly.User) (*assembly.User, assembly.Response, error) {

	err := transact(s.dbh, func(tx modl.SqlExecutor) error {
		var existing []*assembly.User

		if err := s.dbh.Select(&existing, `SELECT * FROM public.user WHERE login=$1;`, user.Login); err != nil {
			return err
		}

		if len(existing) > 0 {
			return assembly.ErrUserLoginExists
		}

		if err := tx.Insert(user); err != nil {
			return err
		}

		return nil
	})

	return user, nil, err
}

func (s *usersStore) Update(user *assembly.User) (*assembly.User, assembly.Response, error) {

	err := transact(s.dbh, func(tx modl.SqlExecutor) error {

		n, err := tx.Update(user)

		if err != nil {
			return err
		}

		if n != 1 {
			return assembly.ErrUserNotFound
		}

		return nil
	})

	return user, nil, err
}

func (s *usersStore) List(opt *assembly.UsersListOptions) ([]*assembly.User, assembly.Response, error) {
	if opt == nil {
		opt = &assembly.UsersListOptions{}
	}

	sql := `SELECT * FROM public.user`

	var users []*assembly.User

	return users, nil, s.dbh.Select(&users, sql)
}


text:
using System.Linq;
using Xunit;

namespace System.Diagnostics.Tests
{
    public class ProcessModuleTests : ProcessTestBase
    {
        [Fact]
        public void TestModuleProperties()
        {
            ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
            Assert.True(modules.Count > 0);

            foreach (ProcessModule module in modules)
            {
                Assert.NotNull(module);

                Assert.NotNull(module.FileName);
                Assert.NotEmpty(module.FileName);

                Assert.InRange(module.BaseAddress.ToInt64(), 0, long.MaxValue);
                Assert.InRange(module.EntryPointAddress.ToInt64(), 0, long.MaxValue);
                Assert.InRange(module.ModuleMemorySize, 0, long.MaxValue);
            }
        }

        [Fact]
        [PlatformSpecific(PlatformID.AnyUnix)]
        public void TestModulesContainsCorerun()
        {
            ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
            Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("corerun"));
        }

        [Fact]
        [PlatformSpecific(PlatformID.Linux)] // OSX only includes the main module
        public void TestModulesContainsUnixNativeLibs()
        {
            ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
            Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("libcoreclr"));
            Assert.Contains(modules.Cast<ProcessModule>(), m => m.FileName.Contains("System.Native"));
        }
    }
}


text:
package com.jgeppert.struts2.jquery.views.velocity.components;

import com.jgeppert.struts2.jquery.components.Anchor;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.components.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Johannes Geppert
 * @see Anchor
 */
public class AnchorDirective extends JqueryAbstractDirective {
    public String getBeanName() {
        return "a";
    }

    protected Component getBean(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
        return new Anchor(stack, req, res);
    }

    public int getType() {
        return BLOCK;
    }
}


text:
using System;
using GTInterfacesLibrary.MessageTypes;

namespace Server.Interfaces
{
    /// <summary>
    /// The DataManager interface represenst the list of methods for storing, maintaining game actions on server.
    /// </summary>
    public interface IDataManager
    {
        #region game related functions
        /// <summary>
        /// List of online players currently on the server.
        /// </summary>
        String[] OnlinePlayers { get; }

        /// <summary>
        /// The method is performed when a client is logged in and decide if there is a user already logged in with the same name.
        /// </summary>
        /// <param name="playerName">The player name to login.</param>
        /// <returns>True if the user is logged in successfully, otherwise false.</returns>
        bool LoginPlayer(String playerName);

        /// <summary>
        /// The method is performed when a client is logged out.
        /// </summary>
        /// <param name="playerName">The player name to log out.</param>
        void LogoutPlayer(String playerName);

        /// <summary>
        /// Create the given.
        /// </summary>
        /// <param name="game">The game to create.</param>
        void CreateGame(Game game);

        /// <summary>
        /// Join to the given game id.
        /// </summary>
        /// <param name="gameId">The id of the game, which the client would like to join.</param>
        /// <param name="playerName">The name of the player to join to the game.</param>
        /// <returns>True if the join was successful, otherwise false.</returns>
        Boolean JoinGame(Int32 gameId, String playerName);

        /// <summary>
        /// Get game from by TypeId.
        /// </summary>
        /// <param name="gameId">The id of the game.</param>
        /// <returns>If exists then the game which has the given TypeId, otherwise null.</returns>
        Game GetGame(Int32 gameId);

        /// <summary>
        /// Get the open games.
        /// </summary>
        /// <param name="player">The name of the player.</param>
        /// <param name="id">The id of the game.</param>
        /// <returns>The list of the opened games, which has the same id.</returns>
        Game[] GetOpenGames(String player, Int32 id);

        /// <summary>
        /// Change game state on the other user if the user made a change.
        /// </summary>
        /// <param name="player">The player who made a change.</param>
        /// <param name="game">The game which contains all the relevant data of the change.</param>
        void ChangeGameState(String player, Game game);

        /// <summary>
        /// End the game.
        /// </summary>
        /// <param name="game">The game which should be ended.</param>
        /// <param name="player">The player who ends the game.</param>
        /// <param name="winner">The winner of the game, it can be null, if the game is cancelled.</param>
        void EndGame(Game game, String player, String winner = null);
        #endregion
    }
}


text:
/*
 *  Blinks a LED forever (until Ctrl+C)
 */
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>

#define IN   0
#define OUT  1

#define LOW  0
#define HIGH 1

#define POUT 11

static int GPIOExport(int pin);
static int GPIOUnexport(int pin);
static int GPIODirection(int pin, int dir);
static int GPIORead(int pin);
static int GPIOWrite(int pin, int value);

volatile int done = 0;

void term(int signum)
{
    done = 1;
}

int main(int argc, char *argv[]) {
	printf("START...\n");

	//catch SIGTERM for graceful exit
	struct sigaction action;
    memset(&action, 0, sizeof(struct sigaction));
    action.sa_handler = term;
    sigaction(SIGTERM, &action, NULL);

	printf("INIT GPIO\n");
    //Enable GPIO pins
    if (-1 == GPIOExport(POUT))
		return(1);

    //Set GPIO directions
    if (-1 == GPIODirection(POUT, OUT))
		return(2);

    while(done == 0) {//while not done...
		//Write GPIO value
		printf("ON\n");
		if (-1 == GPIOWrite(POUT, HIGH))
			return(3);
		usleep(1000 * 1000);
		printf("OFF\n");
		if (-1 == GPIOWrite(POUT, LOW))
			return(3);
		usleep(1000 * 1000);
    }

    //Disable GPIO pins
    if (-1 == GPIOUnexport(POUT))
		return(4);

    return(0);
}

int GPIOExport(int pin) {
#define BUFFER_MAX 3
    char buffer[BUFFER_MAX];
    ssize_t bytes_written;
    int fd;

    fd = open("/sys/class/gpio/export", O_WRONLY);
    if (-1 == fd) {
	fprintf(stderr, "Failed to open export for writing!\n");
	return(-1);
    }

    bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
    write(fd, buffer, bytes_written);
    close(fd);
    return(0);
}

int GPIOUnexport(int pin) {
    char buffer[BUFFER_MAX];
    ssize_t bytes_written;
    int fd;

    fd = open("/sys/class/gpio/unexport", O_WRONLY);
    if (-1 == fd) {
	fprintf(stderr, "Failed to open unexport for writing!\n");
	return(-1);
    }

    bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
    write(fd, buffer, bytes_written);
    close(fd);
    return(0);
}

int GPIODirection(int pin, int dir) {
    static const char s_directions_str[]  = "in\0out";

#define DIRECTION_MAX 35
    char path[DIRECTION_MAX];
    int fd;

    snprintf(path, DIRECTION_MAX, "/sys/class/gpio/gpio%d/direction", pin);
    fd = open(path, O_WRONLY);
    if (-1 == fd) {
	fprintf(stderr, "Failed to open gpio direction for writing!\n");
	return(-1);
    }

    if (-1 == write(fd, &s_directions_str[IN == dir ? 0 : 3], IN == dir ? 2 : 3)) {
	fprintf(stderr, "Failed to set direction!\n");
	return(-1);
    }

    close(fd);
    return(0);
}

int GPIORead(int pin) {
#define VALUE_MAX 30
    char path[VALUE_MAX];
    char value_str[3];
    int fd;

    snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
    fd = open(path, O_RDONLY);
    if (-1 == fd) {
	fprintf(stderr, "Failed to open gpio value for reading!\n");
	return(-1);
    }

    if (-1 == read(fd, value_str, 3)) {
	fprintf(stderr, "Failed to read value!\n");
	return(-1);
    }

    close(fd);

    return(atoi(value_str));
}

int GPIOWrite(int pin, int value) {
    static const char s_values_str[] = "01";

    char path[VALUE_MAX];
    int fd;

    snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
    fd = open(path, O_WRONLY);
    if (-1 == fd) {
	fprintf(stderr, "Failed to open gpio value for writing!\n");
	return(-1);
    }

    if (1 != write(fd, &s_values_str[LOW == value ? 0 : 1], 1)) {
	fprintf(stderr, "Failed to write value!\n");
	return(-1);
    }

    close(fd);
    return(0);
}


text:
using System;
using System.Linq;

namespace BondBench.Schemas
{
	public partial class ArraySegment64K
	{

		public static bool Compare(ArraySegment64K arr1, ArraySegment64K arr2)
		{
			if (arr1 == null || arr1.Arr == null)
				throw new ArgumentNullException ("arr1");

			if (arr2 == null || arr2.Arr == null)
				throw new ArgumentNullException ("arr2");

			if (arr1.Arr.Count != arr2.Arr.Count)
				throw new ArgumentException (
					String.Format("Array are not equal in size arr1 size={0}, arr2 size={1}", arr1.Arr.Array.Length, arr2.Arr.Array.Length)
				);

			if (!Enumerable.SequenceEqual (arr1.Arr, arr2.Arr))
				throw new ArgumentException ("Arrays are not equal");

			return true;
		}

		public static ArraySegment64K Create()
		{
			return Create (100);
		}

		public static ArraySegment64K Create(int seed)
		{
			var b = new ArraySegment64K ();
			b.Arr = new ArraySegment<byte>(SerializersBenchmarks.DataFiller.FillByteArray(65536, seed));

			return b;
		}

	}
}


text:
package com.amazonaws.services.s3control.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.s3control.model.*;
import com.amazonaws.transform.Marshaller;

import com.amazonaws.util.StringUtils;

/**
 * DeleteAccessPointPolicyRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteAccessPointPolicyRequestMarshaller implements Marshaller<Request<DeleteAccessPointPolicyRequest>, DeleteAccessPointPolicyRequest> {

    public Request<DeleteAccessPointPolicyRequest> marshall(DeleteAccessPointPolicyRequest deleteAccessPointPolicyRequest) {

        if (deleteAccessPointPolicyRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<DeleteAccessPointPolicyRequest> request = new DefaultRequest<DeleteAccessPointPolicyRequest>(deleteAccessPointPolicyRequest, "AWSS3Control");

        request.setHttpMethod(HttpMethodName.DELETE);

        if (deleteAccessPointPolicyRequest.getAccountId() != null) {
            request.addHeader("x-amz-account-id", StringUtils.fromString(deleteAccessPointPolicyRequest.getAccountId()));
        }

        String uriResourcePath = "/v20180820/accesspoint/{name}/policy";

        uriResourcePath = com.amazonaws.transform.PathMarshallers.NON_GREEDY.marshall(uriResourcePath, "name", deleteAccessPointPolicyRequest.getName());
        request.setResourcePath(uriResourcePath);

        return request;
    }

}


text:
                                            <button type="button" class="btn btn-primary col-xs-12"
                                                    data-ng-click="vm.newUom()">

                                            </button>

                                            <button type="button" class="btn btn-default" data-ng-click="vm.selectAll()"
                                                    data-tooltip="{{vm.getSelectionKey() | translate}}"
                                                    data-tooltip-trigger="mouseenter" data-tooltip-placement="bottom">

                                            </button>
                                            <button type="button" class="btn btn-default" data-ng-click="vm.showInactive = !vm.showInactive"
                                                    data-tooltip="{{vm.getStatusToggleKey() | translate}}"
                                                    data-tooltip-trigger="mouseenter" data-tooltip-placement="bottom">

                                            </button>

                                            <button type="button" class="btn btn-success" data-ng-if="vm.selected"
                                                    data-ng-click="vm.activateUoms()"
                                                    data-tooltip="{{'fc.RESTORE_SELECTED_TEXT' | translate}}"
                                                    data-tooltip-trigger="mouseenter" data-tooltip-placement="bottom">

                                            </button>
                                            <button type="button" class="btn btn-danger" data-ng-if="vm.selected"
                                                    data-ng-click="vm.deactivate()"
                                                    data-tooltip="{{'fc.DELETE_SELECTED_TEXT' | translate}}"
                                                    data-tooltip-trigger="mouseenter" data-tooltip-placement="bottom">

                                            </button>

                                        <input type="search" class="form-control"
                                               placeholder="{{'fc.SEARCH_PLACEHOLDER_TEXT' | translate}}"
                                               data-ng-model="vm.filter" data-vt-keyboard
                                               data-tooltip="{{'fc.SEARCH_PLACEHOLDER_TEXT' | translate}}"
                                               data-tooltip-placement="top-left" data-tooltip-trigger="focus" />

                                        <button type="button" class="btn btn-default dropdown-toggle" style="width: 100%">

                                            <span data-ng-if="vm.fields.length <= 0">

                                             0">
                                                {{vm.fields.join(', ') | string: 'titleize'}}

                                        </button>

                                                    {{f | string: 'humanize'}}

                                                            {{uom.code}}

                                                                :

                                                                {{uom.packagable}}

                                                                :

                                                                {{uom.description}}

                                                        <button class="btn btn-default"
                                                                data-ng-click="$event.stopPropagation(); vm.edit(uom)"
                                                                data-tooltip="{{'fc.EDIT_TEXT' | translate}}"
                                                                data-tooltip-placement="top"
                                                                data-tooltip-trigger="mouseover">

                                                        </button>
                                                        <button class="btn btn-success"
                                                                data-ng-click="$event.stopPropagation(); vm.activateUoms(uom)"
                                                                data-ng-if="!uom.active"
                                                                data-tooltip="{{'fc.RESTORE_TEXT' | translate}}"
                                                                data-tooltip-placement="top"
                                                                data-tooltip-trigger="mouseover">

                                                        </button>
                                                        <button class="btn btn-danger"
                                                                data-ng-click="$event.stopPropagation(); vm.deactivateUoms(uom)"
                                                                data-ng-if="uom.active"
                                                                data-tooltip="{{'fc.DELETE_TEXT' | translate}}"
                                                                data-tooltip-placement="top"
                                                                data-tooltip-trigger="mouseover">

                                                        </button>

                                        <button class="btn btn-default btn-sm" data-translate="fc.LOAD_MORE_TEXT"
                                                data-ng-click="vm.loadNextPage()"></button>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 12: 421 (1959)

#### Original name
Pyrenopeziza arctostaphyli E. Müll.

### Remarks
null


text:
module BasecampNinja; module Renderer; module Todolist
  include Representable::JSON

  property :id
  property :name
  property :description
  property :created_at
  property :updated_at
  property :completed
  property :position
  property :completed_count
  property :remaining_count
  property :creator, class: BasecampNinja::Person, extend: Renderer::Person
  property :todos, class: BasecampNinja::Todo do
    collection :remaining, class: BasecampNinja::Todo, extend: Renderer::Todo
    collection :completed, class: BasecampNinja::Todo, extend: Renderer::Todo
  end
  collection :comments, class: BasecampNinja::Comment, extend: Renderer::Comment
  collection :subscribers, class: BasecampNinja::Person, extend: Renderer::Person

  property :class_name, default: 'Todolist'
end; end; end


text:
layout: es_post
title: Sobre la ley de obligatoriedad a colegiarse al CPIC
categories: Profesional
tags: ['programación', 'cpic', 'colegio de profesionales en informatica y computación', 'ley']
permalink: es/2014/06/30/proyecto-ley-obligatoriedad-cpic-costa-rica/
thumbnail: http://www.profesional.co.cr/images/Informatica-Libre-logo2.png
language: es
---
Hoy el Colegio de Profesionales en Informatica y Computación (CPIC) de
Costa Rica, nos viene a intentar gobernar como un tirano que busca
poder.
El colegio tiene una ley en la asamblea legislativa, para asegurarse que
solamente colegiados puedan ejercer en Tecnologías de Información.

{{ '/images/Informatica-Libre-logo2.png' | img_tag: 'article-main-image' }}

Esto a simple vista parece inofensivo y hasta necesario, y desde la
perspectiva de profesionales de otras carreras colegiadas inclusive
justo.
Cuando pregunto por cual es la justificación de esto, cual es el
problema que esto viene a resolver, recibo respuestas como "si otros
profesionales tienen la misma restricción, porque no ustedes? es lo
justo", o "es para salvaguardar los intereses de los clientes", o "para
protegernos de hackers y profesionales sin ética".
Pero la realidad es que las intenciones del colegio son meramente
económicas, ellos han fallado en atraer el interes de los profesionales
y como solución deciden obligar con pena de carcel a integrarse a los
profesionales, porque saben que es la carrera de mayor crecimiento en el
mundo.

Pero, el problema aquí, no es solo una cuestión de oponerse a pagarles a
un grupo que tiene aires de grandesa, el problema es un problema serio
para el país, grave, mayúsculo.
No estoy siendo amarillista, el problema es que intentar poner en la
misma caja al area de tecnologías de información, junto a medicina,
abogacía o arquitectura es que no tiene el mas minimo sentido lógico.

La razón es que, aunque alguien pudiera poner ejemplos de como un
muchacho de colegio sin "preparación formal" no tiene la capacidad de
montar un sistema bancario seguro, escalable y eficiente y por esa razón
debería regularse la carrera, estaría dejando de cientos de otras ramas
de nuestra carrera.
Aunque ese ejemplo podría estar comparado con el trabajo de un
arquitecto, y en cierto sentido lo está, ese tipo de trabajo debería ser
supervisado y regulado por el cliente, porque las tendencias, esquemas,
estandares y otros, son demasiados y muy cambiantes, y es el cliente el
que debe determinar bajo que parametros debe permanecer ese desarrollo.

El problema es, que al ver ese ejemplo no veriamos todo otro monton de
ejemplos críticos, permitanme poner esto en perspectiva un poco, y el
porque nuestra area también es comparable con el arte, con un pintor o
un músico, el cual sería destruido al intentar limitarse y controlarse
por un esquema como el que propone el CPIC:

- Cualquier niño de escuela o joven de colegio (de hecho miles a nivel
  mundial lo hacen todos los días) puede desarrollar una idea, un
sistema, un juego, una libreria, una solución a un problema.
- Cualquier profesional de cualquier area puede desarrollar herramientas
  que requieran.
- Un joven podría desarrollar el próximo "Facebook", o un sitio que
  ofrezca maneras novedosas para aprender alguna materia en el colegio,
o podria desarrollar un experimento que cambie la vida de miles de
personas, o simplemente un juego.
- Miles de proyectos open source son creados en una idea desarrollada en
  un fin de semana o en un par de noches, por personas que no nos
imaginamos.
- Un profesional de recursos humanos puede crear una herramienta que le
  ayude a hacer su trabajo.
- Un periodista puede crear un sitio para informar de sus artículos y
  opiniones.

Todos estos ejemplos son casos que según el CPIC no estan certificados
para ejercer estas tareas, y por lo tanto no serán aceptados en el
colegio y por consiguiente estan cometiendo un crimen, de la misma
manera que alguien que no es abogado no puede defender a un acusado, o
que alguien que no es medico no puede efectuar una cirugía.
La simple comparación es absurda, porque las areas no tienen ningún
parecido, porque en nuestra area _cualquiera puede crear_, igual que un
joven puede decidir pintar o esculpir una obra, de la misma manera ese
mismo joven puede crear un sistema.
Así de versatil, libre y creativa es nuestra carrera y no esta límitada
solo por quienes el CPIC dice.
Si esto fuera como el CPIC insiste y dicta, entonces los creadores de
Facebook, Apple, Microsoft, Dell y millones de empresas más estarían en
las carceles, porque ninguno de ellos se graduó de la universidad,
como lo estipula el CPIC.

Las consecuencias de permitir que esta ley se apruebe son tan nefastas
que harían que miles de buenos profesionales no graduados se conviertan
en criminales si continuan ejerciendo la carrera y perderan sus
trabajos, empresas perderan sus empleados, la cantidad de profesionales
que se requieren no se podrá suplir, muchas empresas se irán del país,
personas honestas, justas y trabajadoras serás criminales por ejercer
aquello en lo que han demostrado ser excelentes, los jovenes no podran
ser creativos en esta area, porque estarían cometiendo un crimen.
En este momento los ingresos de divisas en el país generados por esta
área son mayores a los del cafe, banano o cualquier otro producto, y con
menos costos y mayores beneficios para el país.

Realmente queremos cercenar la creatividad, convertir un trabajo
honesto en un crimen y traer tantos problemas económicos y sociales al
país?

Mientras paises desarrollados invierten miles de millones de dolares en
incentivar a los niños y jovenes a crear proyectos en el area de
tecnologias de información, en programar y crear, Costa Rica intenta
declarar esto un crimen.

Es nuestra obligación cívica detener semejante atrocidad, los proyectos
del CPIC deben ser sacados de la asamblea.

Recursos:

- [Proyecto de ley 18919 - Obligatoriedad de pertenecer al
  CPIC](http://www.asamblea.go.cr/sil_access/ver_texto_base.aspx?Numero_Proyecto=18919)
- [Firmas en oposición al proyecto de
  ley](https://secure.avaaz.org/es/petition/Diputados_de_la_Comision_de_Asuntos_Sociales_Asamblea_Legislativa_No_a_la_obligatoriedad_a_pertenecer_al_CPIC_Expediente/?shSIUcb)
- [Proyecto de gobierno y empresas para incentivar a los niños y jovenes a
  programar](http://code.org)
- [Proyecto de libro de cuentos y trabajo para enseñar a los niños a
  programar](http://www.helloruby.com)
- [Proyecto de juego de mesa para enseñar a los niños y jovenes las
  bases de programación](http://www.codemonkeyplanet.com)


text:
layout: post
title: Home Made Masturbation 9 - Scene 6
titleinfo: pornvd
desc: Watch Home Made Masturbation 9 - Scene 6. Pornhub is the ultimate xxx porn and sex site.
---

Home Made Masturbation 9 - Scene 6

Watch Home Made Masturbation 9 - Scene 6. Pornhub is the ultimate xxx porn and sex site.


text:
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#siteNavBar">

      </button>
      andreabertin.net

About

Portfolio

Job

Contacts

<home-header></home-header>

          Hello, my name is Andrea Bertin

          I live in Milan, Italy,
          where I work as a full-time software developer.
          Since programming is also my hobby
          I enjoy it even in my free time but in a more funny way,
          this site I made is an example.
          Programming aside, I enjoy reading, drawing,
          writing and oriental-arts related topics
          (japanese for the most)

<projects-summaries></projects-summaries>


text:
const CopyWebpack = require('copy-webpack-plugin');
module.exports = {
  plugins: [
    new CopyWebpack([
      { from: './node_modules/opencv/data/haarcascade_frontalface_alt.xml', to: '.' },
    ]),
  ]
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using ACommandLineParser.Exceptions;

namespace ACommandLineParser
{
    public class ArgumentCollection: IArgumentCollection
    {
        private readonly List<IArgument> _arguments;

        public ArgumentCollection()
        {
            _arguments = new List<IArgument>();
        }

        public IArgument this[string key]
        {
            get
            {
                IArgument arg;
                if (!TryFindArgument(key, out arg))
                {
                    throw new ACommandLineParserException($"Can't find argument: {key}");
                }
                return arg;
            }
        }

        public void Add(IArgument arg)
        {
            _arguments.Add(arg);
        }

        public void Sort()
        {
            _arguments.Sort((a1, a2) => string.Compare(a1.ShortName, a2.ShortName, StringComparison.Ordinal));
        }

        public void AddCommandLineArguments(string[] args)
        {
            foreach (var arg in args.Where(a => a[0] == '-'))
            {
                string value = arg.Substring(2, arg.Length - 2);
                string shortName = arg.Substring(0, 2);
                SetArgumentValue(arg, shortName, value);
            }
        }

        private void SetArgumentValue(string arg, string shortName, string argumentValue)
        {
            IArgument tmpArg;
            if (!TryFindArgument(shortName, out tmpArg))
            {
                throw new ACommandLineParserException($"Illegal command line argument: {arg}");
            }
            tmpArg.Value = argumentValue;
        }

        public bool TryFindArgument(string key, out IArgument argument)
        {
            argument = _arguments.Find(a => a.ShortName == key || a.Name == key);
            return argument != null;
        }

        public bool VerifyArguments()
        {
            return _arguments.TrueForAll(a => a.IsOptional || a.IsRuleOk(this));
        }

        public void Accept(IArgumentVisitor argVisitor)
        {
            _arguments.ForEach(a => a.Accept(argVisitor));
        }
    }
}


text:
using System;
using System.Text.RegularExpressions;
using Logrila.Logging;
using Logrila.Logging.NLogIntegration;
using Redola.ActorModel;
using Redola.Rpc.TestContracts;

namespace Redola.Rpc.TestActorServer
{
    class Program
    {
        static ILog _log;

        static Program()
        {
            NLogLogger.Use();
            _log = Logger.Get<Program>();
        }

        static void Main(string[] args)
        {
            var localActorConfiguration = AppConfigActorConfiguration.Load();
            var localActor = new RpcActor(localActorConfiguration);

            var helloService = new HelloService(localActor, new CountableRateLimiter());
            var calcService = new CalcService(localActor, new CountableRateLimiter());
            var orderService = new OrderService(localActor, new CountableRateLimiter());
            var orderEventClient = new OrderEventClient(localActor);

            localActor.RegisterRpcHandler(helloService);
            localActor.RegisterRpcHandler(calcService);
            localActor.RegisterRpcHandler(orderService);
            localActor.RegisterRpcHandler(orderEventClient);

            var directoryConfiguration = AppConfigCenterActorDirectoryConfiguration.Load();
            var directory = new CenterActorDirectory(directoryConfiguration);
            localActor.Bootup(directory);

            while (true)
            {
                try
                {
                    string text = Console.ReadLine().ToLowerInvariant();
                    if (text == "quit" || text == "exit")
                    {
                        break;
                    }
                    else if (text == "reconnect")
                    {
                        localActor.Shutdown();

                        directory = new CenterActorDirectory(directoryConfiguration);
                        localActor.Bootup(directory);
                    }
                    else if (Regex.Match(text, @"^notify(\d*)$").Success)
                    {
                        var match = Regex.Match(text, @"notify(\d*)$");
                        int totalCalls = 0;
                        if (!int.TryParse(match.Groups[1].Value, out totalCalls))
                        {
                            totalCalls = 1;
                        }
                        for (int i = 0; i < totalCalls; i++)
                        {
                            NotifyOrderDelivered(orderEventClient);
                        }
                    }
                    else
                    {
                        _log.WarnFormat("Cannot parse the operation for input [{0}].", text);
                    }
                }
                catch (Exception ex)
                {
                    _log.Error(ex.Message, ex);
                }
            }

            localActor.Shutdown();
        }

        private static void NotifyOrderDelivered(IOrderEventService orderEventClient)
        {
            var notification = new OrderDeliveredNotification()
            {
                OrderID = Guid.NewGuid().ToString(),
                OrderStatus = 1,
            };

            _log.DebugFormat("NotifyOrderDelivered, order [{0}] delivered.", notification.OrderID);
            orderEventClient.OrderDelivered(notification);
        }
    }
}


text:
post_id: /panspektronism-skapar-inte-subjektiviteter
date: 2008-10-20 08:02
return_url: '2008-10-01-panspektronism-skapar-inte-subjektiviteter.html'
name: 'Kalle P'
email: 'karl@isk-gbg.org'
comment: '
Bra post! Ja, det är nog något åt det här hållet vi måste tänka. Gillar även ditt sätt att särskilja panopticismen och panspektrocismen grad av närvaro.
'

---


text:
function HtmlPage () {
    this._xhr = null;
}
HtmlPage.prototype.Fetch = function (url, callback, args) {
    this._xhr = new XMLHttpRequest();
    this._xhr.open("GET", url, true);
    this._xhr._owner = this;
    this._xhr.onreadystatechange = function () {
        if (this.readyState != 4)
            return;
        var dom = document.implementation.createHTMLDocument("");
        var range = dom.createRange();
        range.selectNodeContents(dom.documentElement);
        range.deleteContents();
        var node = range.createContextualFragment(this.responseText);
        dom.documentElement.appendChild(node);
        if (callback)
            callback(dom, this.status, args);
        this._owner._xhr = null;
    };
    this._xhr.send();
};


text:
package org.apache.hyracks.client.stats.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import org.apache.hyracks.api.job.profiling.counters.ICounter;
import org.apache.hyracks.client.stats.AggregateCounter;
import org.apache.hyracks.client.stats.Counters;
import org.apache.hyracks.client.stats.IClusterCounterContext;
import org.apache.hyracks.control.common.job.profiling.counters.Counter;

/**
 * @author yingyib
 */
public class ClientCounterContext implements IClusterCounterContext {
    private static String[] RESET_COUNTERS = { Counters.NETWORK_IO_READ, Counters.NETWORK_IO_WRITE,
            Counters.MEMORY_USAGE, Counters.MEMORY_MAX, Counters.DISK_READ, Counters.DISK_WRITE, Counters.NUM_PROCESSOR };
    private static String[] AGG_COUNTERS = { Counters.SYSTEM_LOAD };
    private static int UPDATE_INTERVAL = 10000;

    private final Map<String, Counter> counterMap = new HashMap<String, Counter>();
    private final String baseURL;
    private final List<String> slaveMachines = new ArrayList<String>();
    private boolean stopped = false;
    private Thread updateThread = new UpdateThread();

    public ClientCounterContext(String hostName, int restPort, Collection<String> slaveMachines) {
        this.baseURL = "http://" + hostName + ":" + restPort + "/rest/nodes/";
        this.slaveMachines.addAll(slaveMachines);
        for (String restCounterName : RESET_COUNTERS) {
            counterMap.put(restCounterName, new AggregateCounter(restCounterName));
        }
        for (String aggCounterName : AGG_COUNTERS) {
            counterMap.put(aggCounterName, new AggregateCounter(aggCounterName));
        }
        for (String slave : slaveMachines) {
            for (String restCounterName : RESET_COUNTERS) {
                counterMap.put(slave + "$" + restCounterName, new AggregateCounter(restCounterName));
            }
            for (String aggCounterName : AGG_COUNTERS) {
                counterMap.put(slave + "$" + aggCounterName, new AggregateCounter(aggCounterName));
            }
        }
        requestCounters();
        updateThread.start();
    }

    /**
     * Reset the counters
     */
    public void reset() {
        for (String aggCounterName : RESET_COUNTERS) {
            AggregateCounter aggCounter = (AggregateCounter) counterMap.get(aggCounterName);
            aggCounter.reset();
        }
        for (String slave : slaveMachines) {
            for (String aggCounterName : RESET_COUNTERS) {
                AggregateCounter aggCounter = (AggregateCounter) counterMap.get(slave + "$" + aggCounterName);
                aggCounter.reset();
            }
        }
    }

    public void resetAll() {
        reset();
        for (String aggCounterName : AGG_COUNTERS) {
            AggregateCounter aggCounter = (AggregateCounter) counterMap.get(aggCounterName);
            aggCounter.reset();
        }
        for (String slave : slaveMachines) {
            for (String aggCounterName : AGG_COUNTERS) {
                AggregateCounter aggCounter = (AggregateCounter) counterMap.get(slave + "$" + aggCounterName);
                aggCounter.reset();
            }
        }
    }

    @Override
    public synchronized ICounter getCounter(String name, boolean create) {
        Counter counter = counterMap.get(name);
        if (counter == null) {
            throw new IllegalStateException("request an unknown counter: " + name + "!");
        }
        return counter;
    }

    @Override
    public ICounter getCounter(String machineName, String counterName, boolean create) {
        Counter counter = counterMap.get(machineName + "$" + counterName);
        if (counter == null) {
            throw new IllegalStateException("request an unknown counter: " + counterName + " on slave machine "
                    + machineName + "!");
        }
        return counter;
    }

    /**
     * request to each slave machine for all the counters
     */
    private synchronized void requestCounters() {
        try {
            reset();
            for (String slave : slaveMachines) {
                String slaveProfile = requestProfile(slave);
                JSONParser parser = new JSONParser();
                JSONObject jo = (JSONObject) parser.parse(slaveProfile);
                Object counterObject = jo.get("result");
                if (counterObject instanceof JSONObject) {
                    updateCounterMapWithJSONArray(slave, (JSONObject) counterObject);
                }
            }
        } catch (Exception e) {
            //ignore
        }
    }

    /**
     * Update counters
     *
     * @param jo
     *            the Profile JSON object
     */
    private void updateCounterMapWithJSONArray(String slave, JSONObject jo) {
        for (String counterName : RESET_COUNTERS) {
            updateCounter(slave, jo, counterName);
        }

        for (String counterName : AGG_COUNTERS) {
            updateCounter(slave, jo, counterName);
        }
    }

    private void updateCounter(String slave, JSONObject jo, String counterName) {
        Object counterObject = jo.get(counterName);
        long counterValue = extractCounterValue(counterObject);
        // global counter
        ICounter counter = getCounter(counterName, true);
        counter.set(counterValue);
        //local counters
        ICounter localCounter = getCounter(slave, counterName, true);
        localCounter.set(counterValue);
    }

    private long extractCounterValue(Object counterObject) {
        long counterValue = 0;
        if (counterObject == null) {
            return counterValue;
        } else if (counterObject instanceof JSONArray) {
            JSONArray jArray = (JSONArray) counterObject;
            Object[] values = jArray.toArray();
            /**
             * use the last non-zero value as the counter value
             */
            for (Object value : values) {
                if (value instanceof Double) {
                    Double dValue = (Double) value;
                    double currentVal = dValue.doubleValue();
                    if (currentVal != 0) {
                        counterValue = (long) currentVal;
                    }
                } else if (value instanceof Long) {
                    Long lValue = (Long) value;
                    long currentVal = lValue.longValue();
                    if (currentVal != 0) {
                        counterValue = lValue.longValue();
                    }
                }
            }
        } else {
            Long val = (Long) counterObject;
            counterValue = val.longValue();
        }
        return counterValue;
    }

    /**
     * Request a counter from the slave machine
     *
     * @param slaveMachine
     * @return the JSON string from the slave machine
     */
    private String requestProfile(String slaveMachine) {
        try {
            String url = baseURL + slaveMachine;
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            int responseCode = con.getResponseCode();
            if (responseCode != 200) {
                throw new IllegalStateException("The http response code is wrong: " + responseCode);
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            return response.toString();
        } catch (Exception e) {
            if (!(e instanceof java.net.ConnectException || e instanceof IOException)) {
                throw new IllegalStateException(e);
            } else {
                return "";
            }
        }
    }

    /**
     * Stop the counter profiler
     */
    public void stop() {
        synchronized (updateThread) {
            stopped = true;
            updateThread.notifyAll();
        }
        try {
            updateThread.join();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * The thread keep updating counters
     */
    private class UpdateThread extends Thread {

        @Override
        public synchronized void run() {
            try {
                while (true) {
                    if (stopped) {
                        break;
                    }
                    requestCounters();
                    wait(UPDATE_INTERVAL);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                notifyAll();
            }
        }

    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<meta name="generator" content="JDiff v1.1.1">

<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
Method Removals Index
</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="../stylesheet-jdiff.css" TITLE="Style">

All Methods

Removals

Additions

Changes

Bold is New, strike is deleted

A
B
G
O
R
S
V
 TOP

<nobr>addMember
(Member)</nobr>

B
A
G
O
R
S
V
 TOP

<nobr><A HREF="com.google.inject.Binder.html#com.google.inject.Binder.bindListener_removed(com.google.inject.matcher.Matcher<? super com.google.inject.TypeLiteral<?>>, com.google.inject.spi.TypeListener)" class="hiddenlink" target="rightframe">bindListener
(Matcher<TypeLiteral<?>>, TypeListener)</nobr>

G
A
B
O
R
S
V
 TOP

<nobr>graph
()</nobr>

O
A
B
G
R
S
V
 TOP

<nobr>of
(Injector)</nobr>

R
A
B
G
O
S
V
 TOP

rootedAt

  <nobr>type
(Key[]) in com.google.inject.grapher.InjectorGrapher
</nobr>

  <nobr>type
(Class[]) in com.google.inject.grapher.InjectorGrapher
</nobr>

S
A
B
G
O
R
V
 TOP

<nobr><A HREF="com.google.inject.grapher.ImplementationNode.html#com.google.inject.grapher.ImplementationNode.setClassKey_removed(com.google.inject.Key<?>)" class="hiddenlink" target="rightframe">setClassKey
(Key<?>)</nobr>

<nobr>setInstance
(Object)</nobr>

<nobr><A HREF="com.google.inject.grapher.InterfaceNode.html#com.google.inject.grapher.InterfaceNode.setKey_removed(com.google.inject.Key<?>)" class="hiddenlink" target="rightframe">setKey
(Key<?>)</nobr>

setSource

  <nobr>type
(Object) in com.google.inject.grapher.ImplementationNode
</nobr>

  <nobr>type
(Object) in com.google.inject.grapher.InterfaceNode
</nobr>

<nobr>setType
(Type)</nobr>

V
A
B
G
O
R
S
 TOP

visit

  <nobr><A HREF="com.google.inject.grapher.TransitiveDependencyVisitor.html#com.google.inject.grapher.TransitiveDependencyVisitor.visit_removed(com.google.inject.spi.ExposedBinding<?>)" class="hiddenlink" target="rightframe">type
(ExposedBinding<?>) in com.google.inject.grapher.TransitiveDependencyVisitor
</nobr>

  <nobr><A HREF="com.google.inject.grapher.TransitiveDependencyVisitor.html#com.google.inject.grapher.TransitiveDependencyVisitor.visit_removed(com.google.inject.spi.UntargettedBinding<?>)" class="hiddenlink" target="rightframe">type
(UntargettedBinding<?>) in com.google.inject.grapher.TransitiveDependencyVisitor
</nobr>

  <nobr>type
(RequireExplicitBindingsOption) in com.google.inject.spi.ElementVisitor
</nobr>

  <nobr>type
(ScopeBinding) in com.google.inject.spi.ElementVisitor
</nobr>

  <nobr>type
(StaticInjectionRequest) in com.google.inject.spi.ElementVisitor
</nobr>

  <nobr>type
(TypeConverterBinding) in com.google.inject.spi.ElementVisitor
</nobr>

  <nobr>type
(TypeListenerBinding) in com.google.inject.spi.ElementVisitor
</nobr>