text:
require 'linguist/file_blob'

require 'test/unit'
require 'mime/types'
require 'pygments'

class TestBlob < Test::Unit::TestCase
  include Linguist

  Lexer = Pygments::Lexer

  def fixtures_path
    File.expand_path("../fixtures", __FILE__)
  end

  def blob(name)
    FileBlob.new(File.join(fixtures_path, name), fixtures_path)
  end

  def script_blob(name)
    blob = blob(name)
    blob.instance_variable_set(:@name, 'script')
    blob
  end

  def test_name
    assert_equal "foo.rb", blob("foo.rb").name
  end

  def test_pathname
    assert_equal Pathname.new("foo.rb"), blob("foo.rb").pathname
  end

  def test_mime_type
    assert_equal "application/octet-stream", blob("dog.o").mime_type
    assert_equal "application/ogg", blob("foo.ogg").mime_type
    assert_equal "application/postscript", blob("octocat.ai").mime_type
    assert_equal "application/x-ruby", blob("grit.rb").mime_type
    assert_equal "application/x-sh", blob("script.sh").mime_type
    assert_equal "application/xml", blob("bar.xml").mime_type
    assert_equal "text/plain", blob("README").mime_type
  end

  def test_content_type
    assert_equal "application/octet-stream", blob("dog.o").content_type
    assert_equal "application/ogg", blob("foo.ogg").content_type
    assert_equal "application/pdf", blob("foo.pdf").content_type
    assert_equal "image/png", blob("foo.png").content_type
    assert_equal "text/plain; charset=iso-8859-2", blob("README").content_type
    assert_equal "text/plain; charset=iso-8859-1", blob("script.pl").content_type
    assert_equal "text/plain; charset=iso-8859-1", blob("script.py").content_type
    assert_equal "text/plain; charset=iso-8859-1", blob("script.rb").content_type
    assert_equal "text/plain; charset=iso-8859-1", blob("script.sh").content_type
  end

  def test_disposition
    assert_equal "attachment; filename=foo+bar.jar", blob("foo bar.jar").disposition
    assert_equal "attachment; filename=foo.bin", blob("foo.bin").disposition
    assert_equal "attachment; filename=linguist.gem", blob("pkg/linguist.gem").disposition
    assert_equal "attachment; filename=octocat.ai", blob("octocat.ai").disposition
    assert_equal "inline", blob("README").disposition
    assert_equal "inline", blob("foo.txt").disposition
    assert_equal "inline", blob("grit.rb").disposition
    assert_equal "inline", blob("octocat.png").disposition
  end

  def test_data
    assert_equal "module Foo\nend\n", blob("foo.rb").data
  end

  def test_lines
    assert_equal ["module Foo", "end", ""], blob("foo.rb").lines
  end

  def test_size
    assert_equal 15, blob("foo.rb").size
  end

  def test_loc
    assert_equal 3, blob("foo.rb").loc
  end

  def test_sloc
    assert_equal 2, blob("foo.rb").sloc
  end

  def test_encoding
    assert_equal "ISO-8859-2", blob("README").encoding
    assert_equal "ISO-8859-1", blob("dump.sql").encoding
    assert_equal "UTF-8", blob("foo.txt").encoding
    assert_nil blob("dog.o").encoding
  end

  def test_binary
    # Large blobs aren't loaded
    large_blob = blob("git.exe")
    large_blob.instance_eval do
      def data; end
    end
    assert large_blob.binary?

    assert blob("git.deb").binary?
    assert blob("git.exe").binary?
    assert blob("hello.pbc").binary?
    assert blob("linguist.gem").binary?
    assert blob("octocat.ai").binary?
    assert blob("octocat.png").binary?
    assert blob("zip").binary?
    assert !blob("README").binary?
    assert !blob("file.txt").binary?
    assert !blob("foo.rb").binary?
    assert !blob("script.pl").binary?
  end

  def test_text
    assert blob("README").text?
    assert blob("dump.sql").text?
    assert blob("file.json").text?
    assert blob("file.txt").text?
    assert blob("md").text?
    assert blob("script.sh").text?
    assert blob("tender.md").text?
    assert blob("txt").text?
  end

  def test_image
    assert blob("octocat.gif").image?
    assert blob("octocat.jpeg").image?
    assert blob("octocat.jpg").image?
    assert blob("octocat.png").image?
    assert !blob("octocat.ai").image?
    assert !blob("octocat.psd").image?
  end

  def test_viewable
    assert blob("README").viewable?
    assert blob("foo.rb").viewable?
    assert blob("script.pl").viewable?
    assert !blob("linguist.gem").viewable?
    assert !blob("octocat.ai").viewable?
    assert !blob("octocat.png").viewable?
  end

  def test_generated
    assert !blob("README").generated?

    # Xcode project files
    assert blob("MainMenu.xib").generated?
    assert blob("MainMenu.nib").generated?
    assert blob("project.pbxproj").generated?

    # Gemfile.locks
    assert blob("Gemfile.lock").generated?

    # Generated .NET Docfiles
    assert blob("net_docfile.xml").generated?

    # Long line
    assert !blob("uglify.js").generated?

    # Inlined JS, but mostly code
    assert !blob("json2_backbone.js").generated?

    # Minified JS
    assert !blob("jquery-1.6.1.js").generated?
    assert blob("jquery-1.6.1.min.js").generated?
    assert blob("jquery-1.4.2.min.js").generated?

    # CoffeScript JS

    # These examples are to basic to tell
    assert !blob("coffee/empty.js").generated?
    assert !blob("coffee/hello.js").generated?

    assert blob("coffee/intro-old.js").generated?
    assert blob("coffee/classes-old.js").generated?

    assert blob("coffee/intro.js").generated?
    assert blob("coffee/classes.js").generated?
  end

  def test_vendored
    assert !blob("README").vendored?

    # Node depedencies
    assert blob("node_modules/coffee-script/lib/coffee-script.js").vendored?

    # Rails vendor/
    assert blob("vendor/plugins/will_paginate/lib/will_paginate.rb").vendored?

    # C deps
    assert blob("deps/http_parser/http_parser.c").vendored?
    assert blob("deps/v8/src/v8.h").vendored?

    # Prototype
    assert !blob("public/javascripts/application.js").vendored?
    assert blob("public/javascripts/prototype.js").vendored?
    assert blob("public/javascripts/effects.js").vendored?
    assert blob("public/javascripts/controls.js").vendored?
    assert blob("public/javascripts/dragdrop.js").vendored?

    # jQuery
    assert blob("jquery.js").vendored?
    assert blob("public/javascripts/jquery.js").vendored?
    assert blob("public/javascripts/jquery.min.js").vendored?
    assert blob("public/javascripts/jquery-1.7.js").vendored?
    assert blob("public/javascripts/jquery-1.7.min.js").vendored?
    assert blob("public/javascripts/jquery-1.5.2.js").vendored?
    assert blob("public/javascripts/jquery-1.6.1.js").vendored?
    assert blob("public/javascripts/jquery-1.6.1.min.js").vendored?
    assert !blob("public/javascripts/jquery.github.menu.js").vendored?

    # MooTools
    assert blob("public/javascripts/mootools-core-1.3.2-full-compat.js").vendored?
    assert blob("public/javascripts/mootools-core-1.3.2-full-compat-yc.js").vendored?

    # Dojo
    assert blob("public/javascripts/dojo.js").vendored?

    # MochiKit
    assert blob("public/javascripts/MochiKit.js").vendored?

    # YUI
    assert blob("public/javascripts/yahoo-dom-event.js").vendored?
    assert blob("public/javascripts/yahoo-min.js").vendored?
    assert blob("public/javascripts/yuiloader-dom-event.js").vendored?

    # LESS
    assert blob("public/javascripts/less-1.1.0.js").vendored?
    assert blob("public/javascripts/less-1.1.0.min.js").vendored?

    # WYS editors
    assert blob("public/javascripts/ckeditor.js").vendored?
    assert blob("public/javascripts/tiny_mce.js").vendored?
    assert blob("public/javascripts/tiny_mce_popup.js").vendored?
    assert blob("public/javascripts/tiny_mce_src.js").vendored?

    # Fabric
    assert blob("fabfile.py").vendored?

    # WAF
    assert blob("waf").vendored?

    # Visual Studio IntelliSense
    assert blob("Scripts/jquery-1.7-vsdoc.js").vendored?

    # Microsoft Ajax
    assert blob("Scripts/MicrosoftAjax.debug.js").vendored?
    assert blob("Scripts/MicrosoftAjax.js").vendored?
    assert blob("Scripts/MicrosoftMvcAjax.debug.js").vendored?
    assert blob("Scripts/MicrosoftMvcAjax.js").vendored?
    assert blob("Scripts/MicrosoftMvcValidation.debug.js").vendored?
    assert blob("Scripts/MicrosoftMvcValidation.js").vendored?

    # jQuery validation plugin (MS bundles this with asp.net mvc)
    assert blob("Scripts/jquery.validate.js").vendored?

    # NuGet Packages
    assert blob("packages/Modernizr.2.0.6/Content/Scripts/modernizr-2.0.6-development-only.js").vendored?
  end

  def test_indexable
    assert blob("file.txt").indexable?
    assert blob("foo.rb").indexable?
    assert !blob("defu.nkt").indexable?
    assert !blob("dump.sql").indexable?
    assert !blob("github.po").indexable?
    assert !blob("linguist.gem").indexable?
  end

  def test_language
    assert_equal Language['C'],           blob("hello.c").language
    assert_equal Language['C'],           blob("hello.h").language
    assert_equal Language['C++'],         blob("bar.h").language
    assert_equal Language['C++'],         blob("bar.hpp").language
    assert_equal Language['C++'],         blob("hello.cpp").language
    assert_equal Language['C++'],         blob("cuda.cu").language
    assert_equal Language['GAS'],         blob("hello.s").language
    assert_equal Language['Logtalk'],     blob("foo.lgt").language
    assert_equal Language['Objective-C'], blob("Foo.h").language
    assert_equal Language['Objective-C'], blob("Foo.m").language
    assert_equal Language['Objective-C'], blob("FooAppDelegate.h").language
    assert_equal Language['Objective-C'], blob("FooAppDelegate.m").language
    assert_equal Language['Objective-C'], blob("hello.m").language
    assert_equal Language['OpenCL'],      blob("fft.cl").language
    assert_equal Language['Ruby'],        blob("foo.rb").language
    assert_equal Language['Ruby'],        blob("script.rb").language
    assert_equal Language['Ruby'],        blob("wrong_shebang.rb").language
    assert_equal Language['Arduino'],     blob("hello.ino").language
    assert_equal Language['VHDL'],        blob("foo.vhd").language
    assert_nil blob("octocat.png").language

    # .cls disambiguation
    # https://github.com/abevoelker/abl-email-client/blob/master/com/abevoelker/email/Email.cls
    assert_equal Language['OpenEdge ABL'], blob("Email.cls").language
    # https://github.com/emcmanis/Thesis/blob/master/TeX/Thesis%20Template/reedthesis.cls
    assert_equal Language['TeX'], blob("reedthesis.cls").language
    # https://github.com/DangerMouseB/VLMessaging/blob/master/VLMMachineRouter/cApplication.cls
    assert_equal Language['Visual Basic'], blob("cApplication.cls").language
    # https://github.com/apex-commons/base/blob/master/src/classes/ArrayUtils.cls
    assert_equal Language['Apex'], blob("ArrayUtils.cls").language

    # .pl disambiguation
    assert_equal Language['Prolog'],      blob("test-prolog.pl").language
    assert_equal Language['Perl'],        blob("test-perl.pl").language
    assert_equal Language['Perl'],        blob("test-perl2.pl").language

    # .m disambiguation
    assert_equal Language['Objective-C'], blob("Foo.m").language
    assert_equal Language['Objective-C'], blob("hello.m").language
    assert_equal Language['Matlab'], blob("matlab_function.m").language
    assert_equal Language['Matlab'], blob("matlab_script.m").language

    # .r disambiguation
    assert_equal Language['R'],           blob("hello-r.R").language
    assert_equal Language['Rebol'],       blob("hello-rebol.r").language

    # .t disambiguation
    assert_equal Language['Perl'],        blob("perl-test.t").language
    assert_equal Language['Turing'],      blob("turing.t").language

    # .v disambiguation
    # https://github.com/progranism/Open-Source-FPGA-Bitcoin-Miner/blob/master/src/sha-256-functions.v
    assert_equal Language['Verilog'],     blob("sha-256-functions.v").language
    # https://github.com/coq/coq/blob/trunk/doc/faq/interval_discr.v
    assert_equal Language['Coq'],         blob("interval_discr.v").language

    # ML
    assert_equal Language['OCaml'],       blob("Foo.ml").language
    assert_equal Language['Standard ML'], blob("Foo.sig").language
    assert_equal Language['Standard ML'], blob("Foo.sml").language

    # Scilab
    assert_equal Language['Scilab'],       blob("scilab_script.sce").language
    assert_equal Language['Scilab'],       blob("scilab_function.sci").language
    assert_equal Language['Scilab'],       blob("scilab_test.tst").language

    # Config files
    assert_equal Language['INI'],   blob(".gitconfig").language
    assert_equal Language['Shell'], blob(".bash_profile").language
    assert_equal Language['Shell'], blob(".bashrc").language
    assert_equal Language['Shell'], blob(".profile").language
    assert_equal Language['Shell'], blob(".zlogin").language
    assert_equal Language['Shell'], blob(".zshrc").language
    assert_equal Language['VimL'],  blob(".gvimrc").language
    assert_equal Language['VimL'],  blob(".vimrc").language
    assert_equal Language['YAML'],  blob(".gemrc").language

    assert_nil blob("blank").language
    assert_nil blob("README").language

    # https://github.com/xquery/xprocxq/blob/master/src/xquery/xproc.xqm
    assert_equal Language['XQuery'], blob("xproc.xqm").language

    # https://github.com/wycats/osx-window-sizing/blob/master/center.applescript
    assert_equal Language['AppleScript'], blob("center.scpt").language
    assert_equal Language['AppleScript'], blob("center.applescript").language

    # https://github.com/Araq/Nimrod/tree/master/examples
    assert_equal Language['Nimrod'], blob("foo.nim").language

    # http://supercollider.sourceforge.net/
    # https://github.com/drichert/BCR2000.sc/blob/master/BCR2000.sc
    assert_equal Language['SuperCollider'], blob("BCR2000.sc").language

    # https://github.com/harrah/xsbt/wiki/Quick-Configuration-Examples
    assert_equal Language['Scala'], blob('build.sbt').language

    # https://github.com/gradleware/oreilly-gradle-book-examples/blob/master/ant-antbuilder/build.gradle
    assert_equal Language['Groovy'], blob("build.gradle").language

    # http://docs.racket-lang.org/scribble/
    assert_equal Language['Racket'], blob("scribble.scrbl").language

    # https://github.com/drupal/drupal/blob/7.x/modules/php/php.module
    assert_equal Language['PHP'], blob("drupal.module").language

    # https://github.com/googleapi/googleapi/blob/master/demos/gmail_demo/gmail.dpr
    assert_equal Language['Delphi'], blob("program.dpr").language

    # https://github.com/philiplaureano/Nemerle.FizzBuzz/blob/master/FizzBuzz/FizzBuzzer.n
    assert_equal Language['Nemerle'], blob("hello.n").language

    # https://github.com/dharmatech/agave/blob/master/demos/asteroids.sps
    assert_equal Language['Scheme'], blob("asteroids.sps").language

    # https://github.com/graydon/rust
    assert_equal Language['Rust'], blob("hello.rs").language

    # https://github.com/olabini/ioke
    assert_equal Language['Ioke'], blob("hello.ik").language

    # https://github.com/parrot/parrot
    assert_equal Language['Parrot Internal Representation'], blob("hello.pir").language
    assert_equal Language['Parrot Assembly'], blob("hello.pasm").language

    # http://gosu-lang.org
    assert_equal Language['Gosu'], blob("Hello.gsx").language
    assert_equal Language['Gosu'], blob("hello.gsp").language
    assert_equal Language['Gosu'], blob("Hello.gst").language
    assert_equal Language['Gosu'], blob("hello.vark").language

    # Groovy Server Pages
    assert_equal Language['Groovy Server Pages'], blob("bar.gsp").language
    assert_equal Language['Groovy Server Pages'], blob("hello-resources.gsp").language
    assert_equal Language['Groovy Server Pages'], blob("hello-pagedirective.gsp").language
    assert_equal Language['Groovy Server Pages'], blob("hello-var.gsp").language

    # https://github.com/Lexikos/AutoHotkey_L
    assert_equal Language['AutoHotkey'], blob("hello.ahk").language

    # Haml
    assert_equal Language['Haml'], blob("hello.haml").language
    assert_equal Language['HTML'], blob("hello.haml").language.group

    # Sass
    assert_equal Language['Sass'], blob("screen.sass").language
    assert_equal Language['CSS'], blob("screen.sass").language.group
    assert_equal Language['SCSS'], blob("screen.scss").language
    assert_equal Language['CSS'], blob("screen.scss").language.group

    # OpenEdge ABL / Progress
    assert_equal Language['OpenEdge ABL'], blob("openedge.p").language

    # Tea
    assert_equal Language['Tea'], blob("foo.tea").language

    # Kotlin
    assert_equal Language['Kotlin'], blob("Foo.kt").language

    # Julia: http://julialang.org/
    assert_equal Language['Julia'], blob("stockcorr.jl").language
  end

  def test_lexer
    assert_equal Lexer['Diff'], blob("dude-thing-okay--001.patch").lexer
    assert_equal Lexer['JavaScript'], blob("dude.js").lexer
    assert_equal Lexer['Ruby'], blob("Capfile").lexer
    assert_equal Lexer['Ruby'], blob("grit.rb").lexer
    assert_equal Lexer['Scheme'], blob("dude.el").lexer
    assert_equal Lexer['Text only'], blob("README").lexer
    assert_equal Lexer['Tea'], blob("foo.tea").lexer
    assert_equal Lexer['vhdl'], blob("foo.vhd").lexer
    assert_equal Lexer['Julia'], blob("stockcorr.jl").lexer
  end

  def test_shebang_script
    assert_equal 'sh', script_blob("script.sh").shebang_script
    assert_equal 'bash', script_blob("script.bash").shebang_script
    assert_equal 'zsh', script_blob("script.zsh").shebang_script
    assert_equal 'perl', script_blob("script.pl").shebang_script
    assert_equal 'ruby', script_blob("script.rb").shebang_script
    assert_equal 'ruby', script_blob("script2.rb").shebang_script
    assert_equal 'python', script_blob("script.py").shebang_script
    assert_equal 'node', script_blob("script.js").shebang_script
    assert_equal 'groovy', script_blob("script.groovy").shebang_script
    assert_equal 'macruby', script_blob("script.mrb").shebang_script
    assert_equal 'rake', script_blob("script.rake").shebang_script
    assert_equal 'foo', script_blob("script.foo").shebang_script
    assert_equal 'nush', script_blob("script.nu").shebang_script
    assert_equal 'scala', script_blob("script.scala").shebang_script
    assert_equal 'racket', script_blob("script.rkt").shebang_script
    assert_equal nil, script_blob("foo.rb").shebang_script
  end

  def test_shebang_language
    assert_equal Language['Shell'], script_blob("script.sh").shebang_language
    assert_equal Language['Shell'], script_blob("script.bash").shebang_language
    assert_equal Language['Shell'], script_blob("script.zsh").shebang_language
    assert_equal Language['Perl'], script_blob("script.pl").shebang_language
    assert_equal Language['Ruby'], script_blob("script.rb").shebang_language
    assert_equal Language['Python'], script_blob("script.py").shebang_language
    assert_equal Language['JavaScript'], script_blob("script.js").shebang_language
    assert_equal Language['Groovy'], script_blob("script.groovy").shebang_language
    assert_equal Language['Ruby'], script_blob("script.mrb").shebang_language
    assert_equal Language['Ruby'], script_blob("script.rake").shebang_language
    assert_equal Language['Nu'], script_blob("script.nu").shebang_language
    assert_equal Language['Scala'], script_blob("script.scala").shebang_language
    assert_equal Language['Racket'], script_blob("script.rkt").shebang_language
    assert_equal nil, script_blob("script.foo").shebang_language
    assert_equal nil, script_blob("foo.rb").shebang_language
  end

  def test_colorize
    assert_equal <<-HTML, blob("foo.rb").colorize

module Foo
end

    HTML
  end

  def test_colorize_without_wrapper
    assert_equal <<-HTML, blob("foo.rb").colorize_without_wrapper
module Foo
end
    HTML
  end

  def test_colorize_skips_minified_files
    assert_nil blob("jquery-1.6.1.min.js").colorize
  end
end


text:
namespace QtDataSync {

class Q_DATASYNC_EXPORT LocalStore : public QObject
{
	Q_OBJECT

public:
	enum ChangeType {
		Exists,
		ExistsDeleted,
		NoExists
	};
	Q_ENUM(ChangeType)

	class Q_DATASYNC_EXPORT SyncScope {
		friend class LocalStore;
		Q_DISABLE_COPY(SyncScope)

	public:
		SyncScope(SyncScope &&other) noexcept;
		~SyncScope();

	private:
		//no export needed
		struct Private {
			ObjectKey key;
			DatabaseRef database;
			std::function<void()> afterCommit;

			Private(const Defaults &defaults, ObjectKey key, LocalStore *owner);
		};
		QScopedPointer<Private> d;

		SyncScope(const Defaults &defaults, const ObjectKey &key, LocalStore *owner);
	};

	explicit LocalStore(Defaults defaults, QObject *parent = nullptr);
	~LocalStore() override;

	QJsonObject readJson(const ObjectKey &key, const QString &filePath, int *costs = nullptr) const;

	// normal store access
	quint64 count(const QByteArray &typeName) const;
	QStringList keys(const QByteArray &typeName) const;
	QList<QJsonObject> loadAll(const QByteArray &typeName) const;

	bool contains(const ObjectKey &key) const;
	QJsonObject load(const ObjectKey &key) const;
	void save(const ObjectKey &key, const QJsonObject &data);
	bool remove(const ObjectKey &key);

	QList<QJsonObject> find(const QByteArray &typeName, const QString &query, DataStore::SearchMode mode) const;
	void clear(const QByteArray &typeName);
	void reset(bool keepData);

	// change access
	quint32 changeCount() const;
	void loadChanges(int limit, const std::function<bool(ObjectKey, quint64, QString, QUuid)> &visitor) const; //(key, version, file, device)
	void markUnchanged(const ObjectKey &key, quint64 version, bool isDelete);
	void removeDeviceChange(const ObjectKey &key, QUuid deviceId);

	// sync access
	SyncScope startSync(const ObjectKey &key) const;
	std::tuple<QtDataSync::LocalStore::ChangeType, quint64, QString, QByteArray> loadChangeInfo(SyncScope &scope) const; //(changetype, version, filename, checksum)
	void updateVersion(SyncScope &scope,
					   quint64 oldVersion,
					   quint64 newVersion,
					   bool changed);
	void storeChanged(SyncScope &scope,
					  quint64 version,
					  const QString &filePath,
					  const QJsonObject &data,
					  bool changed,
					  ChangeType localState);
	void storeDeleted(SyncScope &scope,
					  quint64 version,
					  bool changed,
					  ChangeType localState);
	void markUnchanged(SyncScope &scope,
					   quint64 oldVersion,
					   bool isDelete);
	void commitSync(SyncScope &scope) const;

	void prepareAccountAdded(QUuid deviceId);

Q_SIGNALS:
	void dataChanged(const QtDataSync::ObjectKey &key, bool deleted);
	void dataResetted();

private:
	Defaults _defaults;
	Logger *_logger;
	EmitterAdapter *_emitter;
	DatabaseRef _database;

	QDir typeDirectory(const ObjectKey &key) const;
	QString filePath(const QDir &typeDir, const QString &baseName) const;
	QString filePath(const ObjectKey &key, const QString &baseName) const;

	void beginReadTransaction(const ObjectKey &key = ObjectKey{"any"}) const;
	void beginWriteTransaction(const ObjectKey &key = ObjectKey{"any"}, bool exclusive = false);
	void exec(QSqlQuery &query, const ObjectKey &key = ObjectKey{"any"}) const;

	Q_REQUIRED_RESULT std::function<void ()> storeChangedImpl(const DatabaseRef &db,
																 const ObjectKey &key,
																 quint64 version,
																 const QString &filePath,
																 const QJsonObject &data,
																 bool changed,
																 bool existing);
	void markUnchangedImpl(const DatabaseRef &db,
						   const ObjectKey &key,
						   quint64 version,
						   bool isDelete);
};

}

#endif // QTDATASYNC_LOCALSTORE_P_H

redpajama_set_name: RedPajamaGithub


text:
<bill session="110" type="h" number="3116" updated="2009-01-08T23:20:16-05:00">
	<status><introduced date="1184817600" datetime="2007-07-19"/></status>

	<introduced date="1184817600" datetime="2007-07-19"/>
	<titles>
		<title type="short" as="introduced">Public Safety Interoperability Implementation Act</title>
		<title type="official" as="introduced">To establish a permanent grant program to improve public safety communications and the interoperability of emergency communications equipment.</title>
	</titles>
	<sponsor id="400391"/>
	<cosponsors>
		<cosponsor id="400122" joined="2007-07-19"/>
		<cosponsor id="412258" joined="2008-06-23"/>
		<cosponsor id="400308" joined="2007-07-23"/>
		<cosponsor id="400139" joined="2007-07-19"/>
	</cosponsors>
	<actions>
		<action date="1184817600" datetime="2007-07-19"><text>Referred to the House Committee on Energy and Commerce.</text></action>
		<action date="1184817600" datetime="2007-07-19"><text>Referred to the Subcommittee on Telecommunications and the Internet.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	7/19/2007--Introduced.
Public Safety Interoperability Implementation Act - Amends the National Telecommunications and Information Administration Organization Act to establish the Public Safety Communications Trust Fund to make grants to implement interoperability and modernization for the communications needs of public safety, fire, emergency, law enforcement, and crisis management by state and local government agencies and instrumentalities and nonprofit organizations. Requires that the Fund be a separate Fund in the Digital Television Transition and Public Safety Fund and that it consist of certain amounts from the Digital Television Transition and Public Safety Fund, appropriations under this Act, and proceeds from the sale of certain bands of government-owned broadcast spectrum.

</bill>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Endodermophyton indicum Castell.

### Remarks
null


text:
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.
-->

<add><doc>
  <field name="id">0579B002</field>
  <field name="name">Canon PIXMA MP500 All-In-One Photo Printer</field>
  <field name="manu">Canon Inc.</field>
  <field name="cat">electronics</field>
  <field name="cat">multifunction printer</field>
  <field name="cat">printer</field>
  <field name="cat">scanner</field>
  <field name="cat">copier</field>
  <field name="features">Multifunction ink-jet color photo printer</field>
  <field name="features">Flatbed scanner, optical scan resolution of 1,200 x 2,400 dpi</field>
  <field name="features">2.5" color LCD preview screen</field>
  <field name="features">Duplex Copying</field>
  <field name="features">Printing speed up to 29ppm black, 19ppm color</field>
  <field name="features">Hi-Speed USB</field>
  <field name="features">memory card: CompactFlash, Micro Drive, SmartMedia, Memory Stick, Memory Stick Pro, SD Card, and MultiMediaCard</field>
  <field name="weight">352</field>
  <field name="price">179.99</field>
  <field name="popularity">6</field>
  <field name="inStock">true</field>
  <!-- Buffalo store -->
  <field name="store">45.17614,-93.87341</field>
</doc></add>


text:
import pick from 'lodash/pick';
import * as qs from 'query-string';

import {URL_PARAM} from 'app/constants/globalSelectionHeader';

const DEFAULT_STATUS = 'unresolved';

/**
 * Get query for API given the current location.search string
 */
export function getQuery(search: string) {
  const query = qs.parse(search);

  const status = typeof query.status !== 'undefined' ? query.status : DEFAULT_STATUS;

  const queryParams = {
    status,
    ...pick(query, ['cursor', ...Object.values(URL_PARAM)]),
  };

  return queryParams;
}


text:
class Solution:
        # @param {TreeNode} root
        # @return {integer}
    def maxDepth(self, root):
        if not root:
            return 0
        else:
            return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2014 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.exporter.kbart;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;

import org.lockss.config.TdbTestUtil;
import org.lockss.exporter.kbart.KbartTitle.Field;
import org.lockss.test.LockssTestCase;
import org.lockss.util.StringUtil;

public class TestKbartTitleHealthWrapper extends LockssTestCase {

  static final double HEALTH = 0.5;

  static final HashMap<Field, String> props = new HashMap<Field, String>() {{
    put(Field.TITLE_ID, TdbTestUtil.DEFAULT_TITLE_ID);
    put(Field.PRINT_IDENTIFIER, TdbTestUtil.DEFAULT_ISSN_1);
    put(Field.ONLINE_IDENTIFIER, TdbTestUtil.DEFAULT_EISSN_1);
  }};

  final KbartTitle title = TestKbartTitle.createKbartTitle(props);

  final KbartTitleHealthWrapper wrapper = new KbartTitleHealthWrapper(title, HEALTH);

  public final void testFieldValues() {
    assertEquals(title.fieldValues().size()+1, wrapper.fieldValues().size());
  }

  public final void testFieldValuesListOfField() {
    // Test property fields
    assertEquals(
	title.fieldValues(new ArrayList<Field>(props.keySet())).size()+1,
	nonEmptyValues(wrapper.fieldValues()).size()
    );
    // Test each field individually
    for (final Field f : Field.getFieldSet()) {
      List<Field> lf = new ArrayList<Field>() {{add(f);}};
      assertEquals(
	  title.fieldValues(lf).size()+1,
	  wrapper.fieldValues(lf).size()
      );
    }
  }

  public final void testKbartTitleHealthWrapper() {
    //fail("Not yet implemented");
  }

  public final void testGetHealth() {
    assertEquals(HEALTH, wrapper.getHealth());
  }

  public final void testEqualsObject() {
    // A pair of KBTs should be equal if all their fields have the same values
    assertTrue(wrapper.equals(title));
  }

  /**
   * Remove empty values from a list. The fieldValues() method returns an entry
   * for every Field, even if the list of fields on display is a subset.
   *
   * @param l a list
   * @return a list of the non-empty values of the source list
   */
  private List<String> nonEmptyValues(List<String> l) {
    List<String> res = new ArrayList();
    for (String s : l) {
      if (!StringUtil.isNullString(s)) res.add(s);
    }
    return res;
  }

}


text:
<?php

namespace Broadway\EventDispatcher;

/**
 * Event dispatcher implementation.
 */
class EventDispatcher implements EventDispatcherInterface
{
    private $listeners = [];

    /**
     * {@inheritDoc}
     */
    public function dispatch($eventName, array $arguments)
    {
        if (! isset($this->listeners[$eventName])) {
            return;
        }

        foreach ($this->listeners[$eventName] as $listener) {
            call_user_func_array($listener, $arguments);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function addListener($eventName, /* callable */ $callable)
    {
        if (! isset($this->listeners[$eventName])) {
            $this->listeners[$eventName] = [];
        }

        $this->listeners[$eventName][] = $callable;
    }
}


text:
module Rack
  class ObjectCounter
    VERSION = "0.1.0"
  end
end


text:
require_relative "../../test_helper"
require "smart_answer_flows/benefit-cap-calculator"

module SmartAnswer
  class BenefitCapCalculatorFlowTest < ActiveSupport::TestCase
    context BenefitCapCalculatorFlow do
      setup do
        @questions = {
          first_benefit: :first_benefit_amount?,
          second_benefit: :second_benefit_amount?,
          third_benefit: :third_benefit_amount?,
          fourth_benefit: :fourth_benefit_amount?
        }

        @selected_benefits = [:second_benefit, :fourth_benefit]
      end

      context "order of questions asked" do
        should "ask the next benefit amount question in the selected_benefits list" do
          # Should ask the first question in the selected benefits list
          assert_equal :second_benefit_amount?,
            BenefitCapCalculatorFlow.next_benefit_amount_question(@questions, @selected_benefits)

          # The selected benefits list should only contain unasked questions
          assert_equal [:fourth_benefit], @selected_benefits

          # Should ask the next question in the selected benefits list
          assert_equal :fourth_benefit_amount?,
            BenefitCapCalculatorFlow.next_benefit_amount_question(@questions, @selected_benefits)

          # After all questions have been asked, there should not be any unasked
          # questions in selected_benefits
          assert_equal [], @selected_benefits
        end
      end
    end
  end
end


text:
[![Standard - JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
![screen shot 2017-01-18 at 10 56 50 am](https://cloud.githubusercontent.com/assets/4153188/22057322/ee5f22c6-dd6c-11e6-9c53-4f5659f2f25c.png)
## RN Issues affecting the project

### Major
* Orientation change cannot be detected between renders. [This package](https://github.com/yamill/react-native-orientation) solves the problem but has been abandoned and does not work with RN 0.35 only up to 0.29
* secureTextEntry is broken for *phonePadText* and *emailAddressText* [Github Issue](https://github.com/facebook/react-native/issues/10678)

## Minor
* response.json() hangs when chrome debugging [Github Issue](https://github.com/facebook/react-native/issues/6679)
* [ActivityIndicator][Android] Indicator stays hidden if initialized as animating={false} [Github Issue](https://github.com/facebook/react-native/issues/9023)
* Status bar cannot change before activity is active, RN does not handle the promise rejection [Github Issue](https://github.com/facebook/react-native/issues/6700)

## License

Copyright (c) 2017 Trustlab Pty Ltd, under licence from Global Consent Limited
See our [License](https://github.com/TrustlabTech/ecd-rn/blob/master/LICENSE.md).


text:
CREATE TABLE sales (trans_id int, date date, amount
decimal(9,2), region text)
DISTRIBUTED BY (trans_id)
PARTITION BY RANGE (date)
SUBPARTITION BY LIST (region)
SUBPARTITION TEMPLATE
( SUBPARTITION usa VALUES ('usa'),
  SUBPARTITION asia VALUES ('asia'),
  SUBPARTITION europe VALUES ('europe'),
  DEFAULT SUBPARTITION other_regions)
  (START (date '2011-01-01') INCLUSIVE
   END (date '2012-01-01') EXCLUSIVE
   EVERY (INTERVAL '1 month'),
   DEFAULT PARTITION outlying_dates );


text:
package com.andreytim.jafar.problems.googlecodejam.y2015.qualification.A;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;

/**
 * Created by tim on 11/04/15.
 */
public class StandingOvation {

    private static String solve(Scanner in) {
        int[] shyness = new int[in.nextInt()+1];
        String str = in.next();
        for (int i = 0; i < str.length(); i++) {
            shyness[i] = str.charAt(i) - '0';
        }
        int res = 0, sum = shyness[0];
        for (int i = 1; i < shyness.length; i++) {
            if (sum < i) {
                res += i - sum;
                sum += i - sum;
            }
            sum += shyness[i];
        }
        return String.valueOf(res);
    }

    public static void main(String[] args) throws Exception {
//        Scanner in = new Scanner(System.in);
//        PrintStream out = System.out;
        Scanner in = new Scanner(new FileInputStream("in.txt"));
        PrintStream out = new PrintStream(new FileOutputStream("out.txt"));
        int T = in.nextInt();
        for (int i = 0; i < T; i++) {
            out.printf("Case #%d: %s\n", i+1, solve(in));
        }
        out.close();
    }

}


text:
namespace gl
{
class Context;
}  // namespace gl

namespace egl
{
class Error;
class Debug;
class Display;
class Surface;

class Thread : public LabeledObject
{
  public:
    Thread();

    void setLabel(EGLLabelKHR label) override;
    EGLLabelKHR getLabel() const override;

    void setSuccess();
    void setError(const Error &error,
                  const Debug *debug,
                  const char *command,
                  const LabeledObject *object);
    EGLint getError() const;

    void setAPI(EGLenum api);
    EGLenum getAPI() const;

    void setCurrent(gl::Context *context);
    Surface *getCurrentDrawSurface() const;
    Surface *getCurrentReadSurface() const;
    gl::Context *getContext() const;
    gl::Context *getValidContext() const;
    Display *getDisplay() const;

  private:
    EGLLabelKHR mLabel;
    EGLint mError;
    EGLenum mAPI;
    gl::Context *mContext;
};

}  // namespace egl

#endif  // LIBANGLE_THREAD_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <stroke android:width="0.5dp" android:color="@color/line_bg2" />
            <solid android:color="#eeeeee" />
            <corners android:radius="2dp" />
        </shape>
    </item>
    <item android:state_pressed="false">
        <shape>
            <stroke android:width="0.5dp" android:color="@color/line_bg2" />
            <solid android:color="@color/white" />
            <corners android:radius="2dp" />
        </shape>
    </item>

</selector>


text:
// Provides class sap.ui.core.support.RuleEngineOpaExtension
sap.ui.define(['sap/ui/base/Object'],function(Ui5Object) {
    "use strict";

    /*
    var oLogger = _OpaLogger.getLogger("sap.ui.test.OpaExtension",
        $.sap.log.Level.DEBUG);
    */

    /**
     * OPA extension interface.
     *
     * @class OPA extension interface.
     * @public
     * @alias sap.ui.test.OpaExtension
     * @author SAP SE
     * @since 1.48
     */
    var Extension = Ui5Object.extend("sap.ui.test.OpaExtension", {
        metadata : {
            publicMethods : [
                "onAfterInit",
                "onBeforeExit" ,
                "getAssertions"
            ]
        }

        /**
         * Startup hook, executed after startup of the application under test.
         * Executed in the application frame.
         * Subsequent waitFor's will wait for the returned promise to be resolved.
         *
         * @name sap.ui.test.OpaExtension.onAfterInit
         * @public
         * @function
         * @since 1.48
         * @returns {jQuery.promise} A promise that gets resolved on success or get rejected with the error.
         * Rejection of this promise does not prevent the application under test from loading
         * but will disable this extension.
         *
         * Sample usage:
         *

         *
         *      onAfterInit : function() {
         *          oLogger.debug("Default onAfterInit called");
         *          return $.when();
         *      }
         *
         *

         */

        /**
         * Shutdown hook, executed before shutdown of the application under test.
         * Executed in the application frame.
         * Subsequent waitFor's will wait for the returned promise to be resolved.
         *
         * @name sap.ui.test.OpaExtension.onBeforeExit
         * @public
         * @function
         * @since 1.48
         * @returns {jQuery.promise} A promise that gets resolved on success or get rejected with the error
         *
         *

         *
         *      onBeforeExit : function(){
         *          oLogger.debug("Default onBeforeExit called");
         *          return $.when();
         *      }
         *
         *

         */

        /**
         * Return the custom assertions provided by this extension.
         * The default QUnit assertion object will be augmented with them.
         * Subsequent waitFor's will wait for the returned promise to be resolved.
         *
         * @name sap.ui.test.OpaExtension.getAssertions
         * @public
         * @function
         * @since 1.48
         * @returns A map of custom assertion names and associated function. The assertion
         * function returns a {jQuery.promise} that get resolved with {@link QUnit.pushResult} object.
         * Promise is resolved for both passing and failing assertion and rejected if assertion
         * evaluation fails.
         *
         * Sample:
         *
         * Custom extension:
         *

         *
         *      sap.ui.define([
         *          'jquery.sap.global',
         *          'sap/ui/test/OpaExtension'
         *      ],function($, OpaExtension) {
         *          "use strict";
         *
         *          var customExtension = OpaExtension.extend("sap.ui.test.sample.CustomOpaExtension", {
         *              metadata : {
         *                  publicMethods : [
         *                      "getAssertions"
         *                  ]
         *              },
         *
         *              getAssertions : function() {
         *                  return {
         *                      myCustomAssertion: function() {
         *                          var deferred = $.Deferred();
         *
         *                          // start custom assertion logic, resolve the promise when ready
         *                          setTimeout(function() {
         *                              // Assertion passes
         *                              deferred.resolve({
         *                                  result: true,
         *                                  message: "Custom assertion passes"
         *                              });
         *
         *                              // OR Assertion fails
         *                              deferred.resolve({
         *                                  result: false,
         *                                  message: "Custom assertion fails"
         *                              });
         *
         *                              // OR Propagate an error while evaluating assertion
         *                              deferred.reject(new Error("Error while evaluating assertion, details: " + details));
         *                          },0);
         *
         *                          return deferred.promise();
         *                      }
         *                  }
         *              }
         *          });
         *
         *          return customExtension;
         *      });
         *
         *

         *
         * Usage:
         *
         * Activate this extension and provide some uri parameters:
         *

         *
         *      Opa5.extendConfig({
         *          extensions: ["sap/ui/test/sample/CustomOpaExtension"],
         *          appParams: {
         *              "key": "value"
         *          }
         *      });
         *
         *

         *
         * Call the custom assertion from the page object:
         *

         *
         *      Opa5.createPageObjects({
         *          onMyView : {
         *              viewName : "MyView",
         *              assertions : {
         *                  iShouldUseMyCustomAssertion : function () {
         *                      return this.waitFor({
         *                          id: "MyControlId",
         *                          actions: new Press(),
         *                          success : function () {
         *                              Opa5.assert.myCustomAssertion();
         *                          }
         *                      });
         *                  }
         *              }
         *          }
         *      });
         *
         *

         */
    });

    return Extension;
});


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Uredo pirolae H. Mart.

### Remarks
null


text:
<?php

namespace Ait\CmsBundle\Sonata\Block;

use Doctrine\ORM\EntityManager;
use Sonata\BlockBundle\Block\BaseBlockService;
use Sonata\BlockBundle\Block\BlockContextInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

class PageBlock extends BaseBlockService
{
    protected $enm;

    protected $pageClass;

    public function __construct($name, EngineInterface $templating, EntityManager $enm, $pageClass)
    {
        parent::__construct($name, $templating);
        $this->enm = $enm;
        $this->pageClass = $pageClass;
    }

    public function execute(BlockContextInterface $blockContext, Response $response = null)
    {
        $pages = $this->enm->createQueryBuilder()
            ->select('p.id, p.name')
            ->from('AppBundle:Page', 'p')
            ->orderBy('p.updatedAt', 'DESC')
            ->setMaxResults(10)
            ->getQuery()
            ->getArrayResult();

        return $this->renderResponse('AitCmsBundle:Sonata/Block:page_block.html.twig', [
            'block' => $blockContext->getBlock(),
            'pages' => $pages,
        ], $response);
    }
}


text: R -e "rmarkdown::render('main_report.Rmd')"


text:
<!DOCTYPE html>
<title>Reference rendering - PASS in block without margins</title>
PASS


text:
//----------------------------------------------------------------
// ListEntity.cs
// Copyright SimplyCast 2014
// This projected is licensed under the terms of the MIT license.
//  (see the attached LICENSE.txt).
//----------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace SimplyCast.ContactManager.Requests
{
    /// <summary>
    /// This class contains list-specific request information that can be
    /// serialized.
    /// </summary>
    [XmlRoot(ElementName = "list")]
    public class ListEntity
    {
        private string name;
        private int id;

        /// <summary>
        /// The list ID, specified in requests that assign a contact to a list.
        /// </summary>
        [XmlAttribute("id")]
        public int ID
        {
            get { return this.id; }
            set { this.id = value; }
        }

        /// <summary>
        /// A contact list name, used when creating or renaming a list.
        /// </summary>
        [XmlElement("name")]
        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }
    }
}


text:
namespace System.Globalization
{

using System;

public abstract class Calendar
{

	// Current era value.
	public const int CurrentEra = 0;

	// Internal state.
	private int twoDigitYearMax;

	// Constructor.
	protected Calendar()
			{
				twoDigitYearMax = -1;
			}

	// Get a list of eras for the calendar.
	public abstract int[] Eras { get; }

	// Set the last year of a 100-year range for 2-digit processing.
	public virtual int TwoDigitYearMax
			{
				get
				{
					return twoDigitYearMax;
				}
				set
				{
					twoDigitYearMax = value;
				}
			}

#if CONFIG_FRAMEWORK_1_2

	// Get the minimum DateTime value supported by this calendar.
	public virtual DateTime MinValue
			{
				get
				{
					return DateTime.MinValue;
				}
			}

	// Get the maximum DateTime value supported by this calendar.
	public virtual DateTime MaxValue
			{
				get
				{
					return DateTime.MaxValue;
				}
			}

	// Helper method for getting the maximum DateTime value for subclasses.
	internal DateTime GetMaxValue(int maxYear)
			{
				DateTime value;
				int month = GetMonthsInYear(maxYear, CurrentEra);
				int day = GetDaysInMonth(maxYear, month, CurrentEra);
				value = ToDateTime(maxYear, month, day, 0, 0, 0, 0, CurrentEra);
				return new DateTime(value.Ticks + TimeSpan.TicksPerDay - 1);
			}

#endif

	// Internal version of the default "Add*" methods.
	private static DateTime DefaultAdd
				(DateTime time, int value, long multiplier)
			{
				long ticks;

				// Get the final date tick value.  We use the
				// "checked" block to detect 64-bit overflow
				// when computing the tick value.
				checked
				{
					try
					{
						ticks = ((long)value) * multiplier + time.Ticks;
					}
					catch(OverflowException)
					{
						throw new ArgumentException(_("Arg_DateTimeRange"));
					}
				}

				// Construct and return a new DateTime object,
				// which will also check for out of range values.
				return new DateTime(ticks);
			}

	// Add a time period to a DateTime value.
	public virtual DateTime AddDays(DateTime time, int days)
			{
				return DefaultAdd(time, days, TimeSpan.TicksPerDay);
			}
	public virtual DateTime AddHours(DateTime time, int hours)
			{
				return DefaultAdd(time, hours, TimeSpan.TicksPerHour);
			}
	public virtual DateTime AddMilliseconds(DateTime time, double milliseconds)
			{
				long ticks;

				// Get the final date tick value.  We use the
				// "checked" block to detect overflow when
				// computing the tick value.
				checked
				{
					try
					{
						ticks = ((long)(milliseconds *
										(double)TimeSpan.TicksPerMillisecond))
								+ time.Ticks;
					}
					catch(OverflowException)
					{
						throw new ArgumentException(_("Arg_DateTimeRange"));
					}
				}

				// Construct and return a new DateTime object,
				// which will also check for out of range values.
				return new DateTime(ticks);
			}
	public virtual DateTime AddMinutes(DateTime time, int minutes)
			{
				return DefaultAdd(time, minutes, TimeSpan.TicksPerMinute);
			}
	public abstract DateTime AddMonths(DateTime time, int months);
	public virtual DateTime AddSeconds(DateTime time, int seconds)
			{
				return DefaultAdd(time, seconds, TimeSpan.TicksPerSecond);
			}
	public virtual DateTime AddWeeks(DateTime time, int weeks)
			{
				return DefaultAdd(time, weeks,
								  TimeSpan.TicksPerDay * 7L);
			}
	public abstract DateTime AddYears(DateTime time, int years);

	// Extract the components from a DateTime value.
	public abstract int GetDayOfMonth(DateTime time);
	public abstract System.DayOfWeek GetDayOfWeek(DateTime time);
	public abstract int GetDayOfYear(DateTime time);
	public virtual int GetHour(DateTime time)
			{
				return time.Hour;
			}
	public virtual double GetMilliseconds(DateTime time)
			{
				return ((double)(time.Ticks % TimeSpan.TicksPerSecond))
							/ (double)(TimeSpan.TicksPerMillisecond);
			}
	public virtual int GetMinute(DateTime time)
			{
				return time.Minute;
			}
	public abstract int GetMonth(DateTime time);
	public virtual int GetSecond(DateTime time)
			{
				return time.Second;
			}
	public abstract int GetYear(DateTime time);

	// Get the number of days in a particular month.
	public virtual int GetDaysInMonth(int year, int month)
			{
				return GetDaysInMonth(year, month, CurrentEra);
			}
	public abstract int GetDaysInMonth(int year, int month, int era);

	// Get the number of days in a particular year.
	public virtual int GetDaysInYear(int year)
			{
				return GetDaysInYear(year, CurrentEra);
			}
	public abstract int GetDaysInYear(int year, int era);

	// Get the era for a specific DateTime value.
	public abstract int GetEra(DateTime time);

	// Get the number of months in a specific year.
	public virtual int GetMonthsInYear(int year)
			{
				return GetMonthsInYear(year, CurrentEra);
			}
	public abstract int GetMonthsInYear(int year, int era);

	// Get the week of the year that a particular date falls within.
	public virtual int GetWeekOfYear(DateTime time,
									 CalendarWeekRule rule,
									 DayOfWeek firstDayOfWeek)
			{
				if(((int)firstDayOfWeek) < ((int)(DayOfWeek.Sunday)) ||
				   ((int)firstDayOfWeek) > ((int)(DayOfWeek.Saturday)))
				{
					throw new ArgumentOutOfRangeException
						("firstDayOfWeek", _("Arg_DayOfWeek"));
				}
				// Find out when Jan 1 occurs in this year.
				DayOfWeek jan1;
				jan1 = GetDayOfWeek(ToDateTime(GetYear(time), 1, 1,
											   0, 0, 0, 0, CurrentEra));

				// Compute the week value.
				int temp, inc;
				switch(rule)
				{
					case CalendarWeekRule.FirstDay:
					{
						// Determine how many days to increase by.
						inc = ((int)jan1) - ((int)firstDayOfWeek);
						if(inc < 0)
						{
							inc += 7;
						}

						// Compute the week value.
						return ((GetDayOfYear(time) + inc) / 7) + 1;
					}
					// Not reached.

					case CalendarWeekRule.FirstFullWeek:
					case CalendarWeekRule.FirstFourDayWeek:
					{
						// Calculate the number of days until the
						// start of the first week in the year.
						inc = ((int)firstDayOfWeek) - ((int)jan1);
						if(inc != 0)
						{
							if(inc < 0)
							{
								inc += 7;
							}
							if(rule == CalendarWeekRule.FirstFourDayWeek)
							{
								if(inc >= 4)
								{
									inc -= 7;
								}
							}
							else
							{
								if(inc >= 7)
								{
									inc -= 7;
								}
							}
						}

						// Compute the week value.
						temp = GetDayOfYear(time) - inc;
						if(temp > 0)
						{
							return ((temp - 1) / 7) + 1;
						}

						// The week is actually the last week of the
						// previous year, so restart the process.
						temp = GetYear(time) - 1;
						inc = GetMonthsInYear(temp);
						return GetWeekOfYear
							(ToDateTime(temp, inc, GetDaysInMonth(temp, inc),
										0, 0, 0, 0, CurrentEra),
							 rule, firstDayOfWeek);
					}
					// Not reached.

					default:
					{
						throw new ArgumentOutOfRangeException
							("rule", _("Arg_CalendarWeekRule"));
					}
					// Not reached.
				}
			}

	// Determine if a particular day is a leap day.
	public virtual bool IsLeapDay(int year, int month, int day)
			{
				return IsLeapDay(year, month, day, CurrentEra);
			}
	public abstract bool IsLeapDay(int year, int month, int day, int era);

	// Determine if a particular month is a leap month.
	public virtual bool IsLeapMonth(int year, int month)
			{
				return IsLeapMonth(year, month, CurrentEra);
			}
	public abstract bool IsLeapMonth(int year, int month, int era);

	// Determine if a particular year is a leap year.
	public virtual bool IsLeapYear(int year)
			{
				return IsLeapYear(year, CurrentEra);
			}
	public abstract bool IsLeapYear(int year, int era);

	// Convert a particular time into a DateTime value.
	public virtual DateTime ToDateTime(int year, int month, int day,
										int hour, int minute, int second,
										int millisecond)
			{
				return ToDateTime(year, month, day, hour, minute, second,
								  millisecond, CurrentEra);
			}
	public abstract DateTime ToDateTime(int year, int month, int day,
										int hour, int minute, int second,
										int millisecond, int era);

	// Convert a two-digit year value into a four-digit year value.
	public virtual int ToFourDigitYear(int year)
			{
				if(year < 0)
				{
					// Invalid year value.
					throw new ArgumentException(_("ArgRange_NonNegative"));
				}
				else if(year >= 100)
				{
					// Assume that the year is already 4 digits long.
					return year;
				}
				else
				{
					// Adjust the year using the "TwoDigitYearMax" value.
					int yearMax = TwoDigitYearMax;
					int yearMaxInCentury = (yearMax % 100);
					if(year <= yearMaxInCentury)
					{
						return (yearMax - yearMaxInCentury) + year;
					}
					else
					{
						return (yearMax - 100) + (year - yearMaxInCentury);
					}
				}
			}

}; // class Calendar

}; // namespace System.Globalization


text:
package io.github.suzp1984.accountdemo;

/**
 * Created by moses on 9/22/15.
 */
public class GithubAccount {
    public static final String ACCOUNT_TYPE = "io.github.suzp1984";
    public static final String ACCOUNT_NAME = "github";

    /**
     * Auth token types
     */
    public static final String AUTHTOKEN_TYPE_TEST = "test";
}


text:
package org.geomajas.graphics.client.operation;

import org.geomajas.annotation.Api;
import org.geomajas.graphics.client.object.GraphicsObject;

/**
 * Operation that removes an object.
 *
 * @author Jan De Moerloose
 * @since 1.0.0
 *
 */
@Api
public class RemoveOperation implements GraphicsOperation {

	private GraphicsObject object;

	/**
	 * Create a new operation to add an object.
	 *
	 * @param object
	 */
	@Api
	public RemoveOperation(GraphicsObject object) {
		this.object = object;
	}

	@Override
	public void execute() {
	}

	@Override
	public void undo() {
	}

	@Override
	public GraphicsObject getObject() {
		return object;
	}

	@Override
	public Type getType() {
		return Type.REMOVE;
	}

}


text:
function SeamlessLoop() {
	this.is = {
			  ff: Boolean(!(window.mozInnerScreenX == null) && /firefox/.test( navigator.userAgent.toLowerCase() )),
			  ie: Boolean(document.all && !window.opera),
			  opera: Boolean(window.opera),
			  chrome: Boolean(window.chrome),
			  safari: Boolean(!window.chrome && /safari/.test( navigator.userAgent.toLowerCase() ) && window.getComputedStyle && !window.globalStorage && !window.opera)
			};
	console.debug("ff: " + this.is.ff);
	console.debug("ie: " + this.is.ie);
	console.debug("opera: " + this.is.opera);
	console.debug("chrome: " + this.is.chrome);
	console.debug("safari: " + this.is.safari);
	this._total = 0;
	this._load = 0;
	this.cb_loaded;
	this.cb_loaded_flag = new Boolean();
	this.timeout;
	this.playDelay = -30;
	this.stopDelay = 30;
	if(this.is.chrome) this.playDelay = -25;
	if(this.is.chrome) this.stopDelay = 25;
	if(this.is.ff) this.playDelay = -25;
	if(this.is.ff) this.stopDelay = 85;
	if(this.is.opera) this.playDelay = 5;
	if(this.is.opera) this.stopDelay = 0;
	console.debug(this.playDelay + ", " + this.stopDelay);
	this.next = 1;
	this.audios = new Array();
	this.actual = new Array();
	this.dropOld = new Boolean();
	this.old;
	this._volume = 1;

	var t = this;
	this._eventCanplaythrough = function(audBool) {
		if(audBool == false) {
			audBool = true;
			t._load++;
			if(t._load == t._total) {
				t.loaded = true;
				if(t.cb_loaded_flag == true) {
					t.cb_loaded();
					t.cb_loaded_flag = false;
				}
			}
		}
	};

	this._eventPlaying = function(audMute) {
		setTimeout(function() {
			audMute.pause();
			try {
				audMute.currentTime = 0;
			} catch (e){console.debug(e.message);};
		}, t.stopDelay);

		if(t.dropOld == true) {
			setTimeout(function() {
				if(t.old.paused == false) {
					t.old.pause();
					try {
						t.old.currentTime = 0;
					} catch (e){console.debug(e.message);};
				}
			}, t.stopDelay);
			t.dropOld = false;
		}
	};

	this._eventEnded = function(aud) {
		aud.volume = this._volume;
	};

	this.doLoop = function() {
		var key = (this.next == 1 ? "_1" : "_2");
		var antikey = (this.next == 1 ? "_2" : "_1");

		var t = this;
		this.timeout = setTimeout(function() {t.doLoop();}, this.actual._length + this.playDelay);

		if(this.is.opera) this.actual[antikey].pause();

		this.actual[key].play();
		this.next *= -1;
	};

	this.isLoaded = function() {
		return Boolean(this._load == this._total);
	};
}

SeamlessLoop.prototype.start = function(id) {
	if(id != "") {
		this.actual = this.audios[id];
	}
	this.doLoop();
};

SeamlessLoop.prototype.volume = function(vol) {
	if(typeof vol != "undefined") {
		this.actual._1.volume = vol;
        	this.actual._2.volume = vol;
		this._volume = vol;
	}

	return vol;
};

SeamlessLoop.prototype.stop = function() {
	clearTimeout(this.timeout);
	this.actual._1.currentTime = 0;
	this.actual._1.pause();
	this.actual._2.currentTime = 0;
	this.actual._2.pause();
};

SeamlessLoop.prototype.callback = function(cb_loaded) {
	this.cb_loaded = cb_loaded;
	if(this.isLoaded() == true) cb_loaded();
	else this.cb_loaded_flag = true;
};

SeamlessLoop.prototype.update = function(id, sync) {
	//var key = (this.next == 1 ? "_1" : "_2");
	var antikey = (this.next == 1 ? "_2" : "_1");

	this.old = this.actual[antikey];
	this.actual = this.audios[id];
	if(sync == false) {
		if(this.old.paused == false) {
			this.dropOld = true;
			if(this.is.opera) this.old.pause();
		}
		clearTimeout(this.timeout);
		this.doLoop();
	}
};

SeamlessLoop.prototype.addUri = function(uri, length, id) {
	this.audios[id] = new Array();
	this.audios[id]._length = length;
	var t = this;
	this.audios[id]._1_isLoaded = new Boolean();
	this.audios[id]._2_isLoaded = new Boolean();
	this.audios[id]._1 = new Audio(uri);
	this.audios[id]._2 = new Audio(uri);
	this._total++;
	this.audios[id]._1.addEventListener("canplaythrough", function() {t._eventCanplaythrough(t.audios[id]._1_isLoaded);});
	this.audios[id]._2.addEventListener("canplaythrough", function() {t._eventCanplaythrough(t.audios[id]._2_isLoaded);});
	this.audios[id]._1.addEventListener("playing", function() {t._eventPlaying(t.audios[id]._2);});
	this.audios[id]._2.addEventListener("playing", function() {t._eventPlaying(t.audios[id]._1);});
	this.audios[id]._1.addEventListener("ended", function() {t._eventEnded(t.audios[id]._1);});
	this.audios[id]._2.addEventListener("ended", function() {t._eventEnded(t.audios[id]._2);});
	this.audios[id]._1.load();
	this.audios[id]._2.load();
	this.audios[id]._1.volume = this._volume;
	this.audios[id]._2.volume = this._volume;
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SessaoDomain</title>
<meta name="date" content="2015-04-21">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.br.uepb.domain

Class SessaoDomain

java.lang.Object

com.br.uepb.domain.SessaoDomain

@Entity
public class SessaoDomain
extends java.lang.Object

Representa uma sessão de determinado usuário no sistema
 Guarda o id do usuário

Author:

Sidney

Constructor Summary

Constructors

Constructor and Description

SessaoDomain(java.lang.String id1,
            UsuarioDomain usuario1)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.lang.String
getData()

java.lang.String
getHora()

java.lang.String
getId()

java.lang.String
getIdSessao()

java.lang.String
getIdUsuario()

UsuarioDomain
getUsuario()

boolean
isEstaAtiva()

void
setData(java.lang.String data)

void
setEstaAtiva(boolean estaAtiva)

void
setHora(java.lang.String hora)

void
setIdSessao(java.lang.String idSessao)

void
setIdUsuario(java.lang.String usuarioLogin)

void
setUsuario(UsuarioDomain usuario)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SessaoDomain

public SessaoDomain(java.lang.String id1,
                    UsuarioDomain usuario1)

Method Detail

getIdSessao

public java.lang.String getIdSessao()

Returns:

the idSessao

setIdSessao

public void setIdSessao(java.lang.String idSessao)

Parameters:

idSessao - the idSessao to set

isEstaAtiva

public boolean isEstaAtiva()

Returns:

the estaAtiva

setEstaAtiva

public void setEstaAtiva(boolean estaAtiva)

Parameters:

estaAtiva - the estaAtiva to set

getData

public java.lang.String getData()

Returns:

the data

setData

public void setData(java.lang.String data)

Parameters:

data - the data to set

getHora

public java.lang.String getHora()

Returns:

the hora

setHora

public void setHora(java.lang.String hora)

Parameters:

hora - the hora to set

getIdUsuario

public java.lang.String getIdUsuario()

Returns:

the usuarioLogin

setIdUsuario

public void setIdUsuario(java.lang.String usuarioLogin)

Parameters:

usuarioLogin - the usuarioLogin to set

setUsuario

public void setUsuario(UsuarioDomain usuario)

Parameters:

usuario - the usuario to set

getId

public java.lang.String getId()

getUsuario

public UsuarioDomain getUsuario()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
namespace YanZhiwei.DotNet4.Utilities.Collection
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Threading;

    /// <summary>
    /// 队列管理
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    public sealed class QueueManager<T>
        where T : class, new()
    {
        #region Fields

        /// <summary>
        /// 定时读取队列委托
        /// </summary>
        public Action<List<T>> TimeReadBatchList;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="taskMinute">定时读取队列数据分钟</param>
        public QueueManager(int taskMinute)
        {
            QueueCollection = new ConcurrentQueue<T>();
            StartDequeueTask(taskMinute);
        }

        #endregion Constructors

        #region Properties

        /// <summary>
        /// 队列,线程安全
        /// </summary>
        public ConcurrentQueue<T> QueueCollection
        {
            get; private set;
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// 数据入队
        /// </summary>
        /// <param name="item">数据对象</param>
        public void Add(T item)
        {
            QueueCollection.Enqueue(item);
        }

        private void StartDequeueTask(int taskMinute)
        {
            ThreadPool.QueueUserWorkItem((arg) =>
            {
                while (true)
                {
                    Thread.Sleep(TimeSpan.FromMinutes(taskMinute));
                    if (QueueCollection.Count > 0)
                    {
                        T _item = null;
                        List<T> _batchList = new List<T>();
                        while (QueueCollection.TryDequeue(out _item))
                        {
                            _batchList.Add(_item);
                        }
                        if (_batchList.Count > 0 && TimeReadBatchList != null)
                        {
                            TimeReadBatchList(_batchList);
                        }
                    }
                }
            });
        }

        #endregion Methods
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _04.Sort_Numbers
{
    class Program
    {
        static void Main(string[] args)
        {
            List<decimal> numbers = Console.ReadLine().Split().Select(decimal.Parse).ToList();

            numbers.Sort();

            Console.WriteLine(string.Join(" <= ",numbers));
        }
    }
}


text:
package io.lettuce.core.commands.reactive;

import static org.assertj.core.api.Assertions.assertThat;

import javax.inject.Inject;

import org.junit.jupiter.api.Test;

import reactor.test.StepVerifier;
import io.lettuce.core.KeyValue;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisException;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.reactive.RedisReactiveCommands;
import io.lettuce.core.commands.TransactionCommandIntegrationTests;
import io.lettuce.test.ReactiveSyncInvocationHandler;

/**
 * @author Mark Paluch
 */
public class TransactionReactiveCommandIntegrationTests extends TransactionCommandIntegrationTests {

    private final RedisClient client;
    private final RedisReactiveCommands<String, String> commands;
    private final StatefulRedisConnection<String, String> connection;

    @Inject
    public TransactionReactiveCommandIntegrationTests(RedisClient client, StatefulRedisConnection<String, String> connection) {
        super(client, ReactiveSyncInvocationHandler.sync(connection));
        this.client = client;
        this.commands = connection.reactive();
        this.connection = connection;
    }

    @Test
    void discard() {

        StepVerifier.create(commands.multi()).expectNext("OK").verifyComplete();

        commands.set(key, value).toProcessor();

        StepVerifier.create(commands.discard()).expectNext("OK").verifyComplete();
        StepVerifier.create(commands.get(key)).verifyComplete();
    }

    @Test
    void watchRollback() {

        StatefulRedisConnection<String, String> otherConnection = client.connect();

        otherConnection.sync().set(key, value);

        StepVerifier.create(commands.watch(key)).expectNext("OK").verifyComplete();
        StepVerifier.create(commands.multi()).expectNext("OK").verifyComplete();

        commands.set(key, value).toProcessor();

        otherConnection.sync().del(key);

        StepVerifier.create(commands.exec()).consumeNextWith(actual -> {
            assertThat(actual).isNotNull();
            assertThat(actual.wasDiscarded()).isTrue();
        });

        otherConnection.close();
    }

    @Test
    void execSingular() {

        StepVerifier.create(commands.multi()).expectNext("OK").verifyComplete();

        connection.sync().set(key, value);

        StepVerifier.create(commands.exec()).consumeNextWith(actual -> assertThat(actual).contains("OK")).verifyComplete();
        StepVerifier.create(commands.get(key)).expectNext(value).verifyComplete();
    }

    @Test
    void errorInMulti() {

        commands.multi().toProcessor();
        commands.set(key, value).toProcessor();
        commands.lpop(key).toProcessor();
        commands.get(key).toProcessor();

        StepVerifier.create(commands.exec()).consumeNextWith(actual -> {

            assertThat((String) actual.get(0)).isEqualTo("OK");
            assertThat((Object) actual.get(1)).isInstanceOf(RedisException.class);
            assertThat((String) actual.get(2)).isEqualTo(value);
        }).verifyComplete();
    }

    @Test
    void resultOfMultiIsContainedInCommandFlux() {

        commands.multi().toProcessor();

        StepVerifier.Step<String> set1 = StepVerifier.create(commands.set("key1", "value1")).expectNext("OK").thenAwait();
        StepVerifier.Step<String> set2 = StepVerifier.create(commands.set("key2", "value2")).expectNext("OK").thenAwait();
        StepVerifier.Step<KeyValue<String, String>> mget = StepVerifier.create(commands.mget("key1", "key2"))
                .expectNext(KeyValue.just("key1", "value1"), KeyValue.just("key2", "value2")).thenAwait();
        StepVerifier.Step<Long> llen = StepVerifier.create(commands.llen("something")).expectNext(0L).thenAwait();

        StepVerifier.create(commands.exec()).then(() -> {

            set1.verifyComplete();
            set2.verifyComplete();
            mget.verifyComplete();
            llen.verifyComplete();

        }).expectNextCount(1).verifyComplete();
    }

    @Test
    void resultOfMultiIsContainedInExecObservable() {

        commands.multi().toProcessor();
        commands.set("key1", "value1").toProcessor();
        commands.set("key2", "value2").toProcessor();
        commands.mget("key1", "key2").collectList().toProcessor();
        commands.llen("something").toProcessor();

        StepVerifier.create(commands.exec()).consumeNextWith(actual -> {

            assertThat(actual).contains("OK", "OK", list(kv("key1", "value1"), kv("key2", "value2")), 0L);

        }).verifyComplete();
    }
}


text:
cask "monitorcontrol" do
  version "2.1.0"
  sha256 "c02a1a96a002a3e9f1072e3924ea66226233a227b5c971d617b3ef4f12acf206"

  url "https://github.com/the0neyouseek/MonitorControl/releases/download/v#{version}/MonitorControl.#{version}.dmg"
  name "MonitorControl"
  desc "Tool to control external monitor brightness & volume"
  homepage "https://github.com/the0neyouseek/MonitorControl"

  depends_on macos: ">= :sierra"

  app "MonitorControl.app"
end


text:
using System;
using System.Runtime.CompilerServices;

namespace Serenity
{
    [Imported]
    public class GeneratedCode : Attribute
    {
        public GeneratedCode(string origin = null)
        {
            this.Origin = origin;
        }

        [IntrinsicProperty]
        public string Origin
        {
            get; private set;
        }
    }
}


text:
namespace gpdxl
{
using namespace gpos;

XERCES_CPP_NAMESPACE_USE

//---------------------------------------------------------------------------
//	@class:
//		CParseHandlerStacktrace
//
//	@doc:
//		Pass-through parse handler class for stack traces
//
//---------------------------------------------------------------------------
class CParseHandlerStacktrace : public CParseHandlerBase
{
private:
	// process the start of an element
	void StartElement(
		const XMLCh *const element_uri,			// URI of element's namespace
		const XMLCh *const element_local_name,	// local part of element's name
		const XMLCh *const element_qname,		// element's qname
		const Attributes &attr					// element's attributes
		) override;

	// process the end of an element
	void EndElement(
		const XMLCh *const element_uri,			// URI of element's namespace
		const XMLCh *const element_local_name,	// local part of element's name
		const XMLCh *const element_qname		// element's qname
		) override;

public:
	CParseHandlerStacktrace(const CParseHandlerStacktrace &) = delete;

	// ctor/dtor
	CParseHandlerStacktrace(CMemoryPool *mp,
							CParseHandlerManager *parse_handler_mgr,
							CParseHandlerBase *parse_handler_root);
};
}  // namespace gpdxl

#endif	// !GPDXL_CParseHandlerStacktrace_H

// EOF


text:
package main

import (
	"bufio"
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"strings"
)

func getColumnNames(csvReader *csv.Reader) []string {
	columnNames, err := csvReader.Read()
	if err != nil {
		panic(err)
	}

	for i, colName := range columnNames {
		columnNames[i] = strings.TrimSpace(colName)
	}
	return columnNames
}

// readInputRows reads all rows from a slice of io.Readers, inserting them into
// a channel in order. If the column names don't match across files, a panic
// occurs
func readInputRows(readers []io.Reader, ch chan<- *Row) {

	var csvReaders []*csv.Reader
	var colNames []string
	firstFile := true

	// Ensure column names match
	for _, reader := range readers {
		csvReader := csv.NewReader(reader)
		csvReaders = append(csvReaders, csvReader)

		if firstFile {
			firstFile = !firstFile
			colNames = getColumnNames(csvReader)
			continue
		}

		nextColNames := getColumnNames(csvReader)
		for i, col := range colNames {
			if nextColNames[i] != col {
				panic(fmt.Sprintf("column mismatch in file %d\n", i))
			}
		}
	}

	rowCount := 0
	var row *Row
	for _, csvReader := range csvReaders {
		for {
			record, err := csvReader.Read()
			if err == io.EOF {
				break
			} else if err != nil {
				panic(err)
			}

			for i, value := range record {
				record[i] = strings.TrimSpace(value)
			}

			row = &Row{colNames, record}
			ch <- row
			rowCount++
		}
	}
	close(ch)
	return
}

func writeCSVRows(writer io.Writer, ch <-chan *Row) error {
	csvWriter := csv.NewWriter(writer)
	first := true
	for row := range ch {
		if first {
			first = !first
			err := csvWriter.Write(row.ColumnNames)
			if err != nil {
				return err
			}
		}
		err := csvWriter.Write(row.Values)
		if err != nil {
			return err
		}
	}
	csvWriter.Flush()
	return nil
}

func readInputRowsFast(readers []io.Reader, ch chan<- *Row) {

	for _, reader := range readers {
		err := rowsFromReaderFast(reader, ch)
		if err != nil {
			panic(err)
		}
	}
}

func rowsFromReaderFast(reader io.Reader, ch chan<- *Row) error {
	bufferedReader := bufio.NewReader(reader)

	// get column names
	b, err := bufferedReader.ReadBytes('\n')
	if err != nil {
		return err
	}
	firstRow, err := parseRow(b, []string{})
	if err != nil {
		return err
	}
	colNames := firstRow.Values

	for {
		b, err := bufferedReader.ReadBytes('\n')
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}
		row, err := parseRow(b, colNames)
		if err != nil {
			return err
		}
		ch <- &row
	}
	return nil
}

// parseRow takes a slice of bytes and a slice of expected columns and attempts
// to return a Row filled with values from the byte slice
func parseRow(bs []byte, columnNames []string) (Row, error) {
	var values []string
	var currentValue []byte

	maxQuoteDepth := 3
	quotes := make([]byte, 0, maxQuoteDepth)

	for _, b := range bs {

		switch b {
		case '"', '\'':
			if len(quotes) != 0 && b == quotes[len(quotes)-1] { // delete last item in quote slice
				currentValue = append(currentValue, b)
				quotes = quotes[:len(quotes)-1]
			} else if len(quotes) < maxQuoteDepth { // increment quote slice
				currentValue = append(currentValue, b)
				quotes = append(quotes, b)
			} else {
				return Row{}, errors.New("quoting exceeded max depth")
			}
		case ',':
			if len(quotes) == 0 {
				values = append(values, string(currentValue))
				currentValue = []byte{}
			} else {
				currentValue = append(currentValue, b)
			}
		default:
			currentValue = append(currentValue, b)
		}
	}
	values = append(values, string(currentValue))

	var err error
	if len(columnNames) != 0 && len(columnNames) != len(values) {
		err = errors.New("unexpected number of columns")
	}

	return Row{columnNames, values}, err
}


text:
1. [Introducing ASP.NET Core 2.0 Preview 2](https://blogs.msdn.microsoft.com/webdev/2017/06/28/introducing-asp-net-core-2-0-preview-2/)
1. [Multi-Targeting and Porting a .NET Library to .NET Core 2.0](https://weblog.west-wind.com/posts/2017/Jun/22/MultiTargeting-and-Porting-a-NET-Library-to-NET-Core-20)
1. [How to Support Windows Authentication for ASP.NET Core in IIS](https://blogs.msdn.microsoft.com/wushuai/2017/06/26/how-to-support-windows-authentication-for-asp-net-core-in-iis/)
1. [Azure Redis Cache Geo-Replication in Public Preview](https://azure.microsoft.com/en-us/blog/azure-redis-cache-geo-replication-in-public-preview/)

## Tooling & Libraries

1. [Measuring your code's performance during development with BenchmarkDotNet – Part 1 Getting started](https://jeremylindsayni.wordpress.com/2017/06/22/measure-your-codes-performance-during-development-with-benchmarkdotnet-and-net-core/)
1. [Announcing EF Core 2.0 Preview 2](https://blogs.msdn.microsoft.com/dotnet/2017/06/28/announcing-ef-core-2-0-preview-2/)
1. [Rider EAP 24 includes performance fixes, F# Interactive](https://blog.jetbrains.com/dotnet/2017/06/29/rider-eap-24-includes-performance-fixes-f-interactive/)
1. [vswhere version 2.0 released](https://blogs.msdn.microsoft.com/heaths/2017/06/24/vswhere-version-2-0-released/)
1. [7 lesser known hacks for debugging in Visual Studio](https://blogs.msdn.microsoft.com/visualstudio/2017/06/26/7-lesser-known-hacks-for-debugging-in-visual-studio/)
1. [Diving Into Docker CE 17](https://dzone.com/articles/diving-into-docker-ce-17)

## Architecture & Databases

1. [Long-Awaited OpenAPI Spec 3.0 to Be Released in July](https://www.infoq.com/news/2017/06/open-api-spec-3)
1. [SQL Server Diagnostics Preview](https://blogs.msdn.microsoft.com/sql_server_team/sql-server-diagnostics-preview/)
1. [The Basics of Good T-SQL Coding Style – Part 3 Querying and Manipulating Data](https://www.simple-talk.com/sql/t-sql-programming/basics-good-t-sql-coding-style-part-3-querying-manipulating-data/)
1. [API Design Guidelines – Best Practices for Building a User-Friendly API](https://dzone.com/articles/api-design-guidelines-best-practices-for-building)
1. [NoSQL Review - ArangoDB 3.2 Beta](https://dzone.com/articles/nosql-review-arangodb-32-beta)
1. [5 Good Reasons to Use Event Sourcing](https://dzone.com/articles/5-great-points-why-you-use-event-sourcing-1)

## Programming Languages

1. [Announcing TypeScript 2.4](https://blogs.msdn.microsoft.com/typescript/2017/06/27/announcing-typescript-2-4/)
1. [C# - Make C# More Dynamic with Hyperlambda](https://msdn.microsoft.com/en-us/magazine/mt809119)
1. [Pure times](http://blog.ploeh.dk/2017/06/27/pure-times/)
1. [Pure times in Haskell](http://blog.ploeh.dk/2017/06/28/pure-times-in-haskell/)

## Runtime

1. [Networking stack - Technical roadmap](https://github.com/dotnet/designs/issues/9)
1. [Value Types vs Reference Types - Performance](http://adamsitnik.com/Value-Types-vs-Reference-Types/)
1. [Proposal - Ways to alter large object allocation behavior](https://github.com/dotnet/coreclr/issues/12426)
1. [Performance Improvements in RyuJIT in .NET Core and .NET Framework](https://blogs.msdn.microsoft.com/dotnet/2017/06/29/performance-improvements-in-ryujit-in-net-core-and-net-framework/)

## Other

1. [Team Conflict - Four Ways to Deflate the Discord that's Killing Your Team](https://alistapart.com/article/team-conflict-four-ways-to-deflate-the-discord-thats-killing-your-team)
1. [Imposter syndrome - Part 1](https://codeblog.jonskeet.uk/2017/06/16/imposter-syndrome-part-1/)
1. [Imposter syndrome - Part 2](https://codeblog.jonskeet.uk/2017/06/25/imposter-syndrome-part-2/)


text:
@interface SZURLRequestOperation () {
    NSObject *_stateLock;
}

@end

@implementation SZURLRequestOperation

- (id)initWithURLRequest:(NSMutableURLRequest*)request {

    if (self = [super init]) {
        _stateLock = [[NSObject alloc] init];
        self.request = request;
    }

    return self;
}

- (void)downloadCompletionWithResponse:(NSURLResponse*)response data:(NSMutableData*)data error:(NSError*)error {
    self.response = response;
    self.responseData = data;
    self.error = error;
    [self callCompletion];
    [self KVStop];
}

- (void)failWithError:(NSError*)error {
    self.error = error;
    self.didFail = YES;
    [self callCompletion];
    [self KVStop];
}

- (void)start {

    @synchronized(_stateLock) {
        if ([self isCancelled]) {
            return;
        }

        // Check for failed dependencies
        NSError *error = [self failedDependenciesError];
        if (error != nil) {
            [self failWithError:error];
            return;
        }

        [self KVStart];

        WEAK(self) weakSelf = self;
        self.URLRequestDownloader = [[SZURLRequestDownloader alloc] initWithURLRequest:self.request];
        self.URLRequestDownloader.completionBlock = ^(NSURLResponse *response, NSData *data, NSError *error) {
            [weakSelf downloadCompletionWithResponse:response data:data error:error];
        };
        [self.URLRequestDownloader start];
    }
}

- (void)cancel {
    @synchronized(_stateLock) {

        if (_executing) {
            [self.URLRequestDownloader cancel];
            self.URLRequestDownloader = nil;

        }

        [self KVCancel];
        [self KVStop];
    }
}

- (void)callCompletion {
    BLOCK_CALL_3(self.URLCompletionBlock, self.response, self.responseData, self.error);
}

- (NSString*)description {
    return [NSString stringWithFormat:@"%@ / %@", [self class], self.request];
}

@end


text:
<meta http-equiv="Content-Type" content="text/html; charset=windows-1250">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<title>Stred</title>
<base target="_self">
<meta name="Microsoft Border" content="none">

Pozrite si osobnú
stránku Danulka Šípa


text:
import { Plugin } from 'prosemirror-state';
import { EditorView } from 'prosemirror-view';

import { findCellElement } from '@/wysiwyg/helper/table';
import i18n from '@/i18n/i18n';

import { Emitter } from '@t/event';

interface ContextMenuInfo {
  action: string;
  command: string;
  payload?: {
    align: string;
  };
  className: string;
  disableInThead?: boolean;
}

const contextMenuGroups: ContextMenuInfo[][] = [
  [
    {
      action: 'Add row to up',
      command: 'addRowToUp',
      disableInThead: true,
      className: 'add-row-up',
    },
    {
      action: 'Add row to down',
      command: 'addRowToDown',
      disableInThead: true,
      className: 'add-row-down',
    },
    { action: 'Remove row', command: 'removeRow', disableInThead: true, className: 'remove-row' },
  ],
  [
    { action: 'Add column to left', command: 'addColumnToLeft', className: 'add-column-left' },
    { action: 'Add column to right', command: 'addColumnToRight', className: 'add-column-right' },
    { action: 'Remove column', command: 'removeColumn', className: 'remove-column' },
  ],
  [
    {
      action: 'Align column to left',
      command: 'alignColumn',
      payload: { align: 'left' },
      className: 'align-column-left',
    },
    {
      action: 'Align column to center',
      command: 'alignColumn',
      payload: { align: 'center' },
      className: 'align-column-center',
    },
    {
      action: 'Align column to right',
      command: 'alignColumn',
      payload: { align: 'right' },
      className: 'align-column-right',
    },
  ],
  [{ action: 'Remove table', command: 'removeTable', className: 'remove-table' }],
];

function getContextMenuGroups(eventEmitter: Emitter, inTableHead: boolean) {
  return contextMenuGroups
    .map((contextMenuGroup) =>
      contextMenuGroup.map(({ action, command, payload, disableInThead, className }) => {
        return {
          label: i18n.get(action),
          onClick: () => {
            eventEmitter.emit('command', command, payload);
          },
          disabled: inTableHead && !!disableInThead,
          className,
        };
      })
    )
    .concat();
}

export function tableContextMenu(eventEmitter: Emitter) {
  return new Plugin({
    props: {
      handleDOMEvents: {
        contextmenu: (view: EditorView, ev: Event) => {
          const tableCell = findCellElement(ev.target as HTMLElement, view.dom);

          if (tableCell) {
            ev.preventDefault();

            const { clientX, clientY } = ev as MouseEvent;
            const { left, top } = (view.dom.parentNode as HTMLElement).getBoundingClientRect();
            const inTableHead = tableCell.nodeName === 'TH';

            eventEmitter.emit('contextmenu', {
              pos: { left: `${clientX - left + 10}px`, top: `${clientY - top + 30}px` },
              menuGroups: getContextMenuGroups(eventEmitter, inTableHead),
              tableCell,
            });

            return true;
          }

          return false;
        },
      },
    },
  });
}