text:
RSpec.describe KF5::Configuration do
  subject { properties }
  let(:properties) { KF5::Configuration.new(:domain => 'test') }

  describe "#initialize" do
    its(:domain) { should eq 'test' }
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php
	include_once(dirname(__FILE__)."/../../../lib/session_manager.php");
	include_once(dirname(__FILE__)."/../../../database/config.php");
	include_once(dirname(__FILE__)."/../../../database/mcat_db.php");
	include_once(dirname(__FILE__)."/../../../lib/user.php");
	include_once(dirname(__FILE__)."/../../../lib/user_manager.php");
    include_once(dirname(__FILE__)."/../../../lib/site_config.php") ;
	include_once(dirname(__FILE__)."/../../../lib/utils.php") ;

	$user_id = CSessionManager::Get(CSessionManager::STR_USER_ID);

	$objDB = new CMcatDB();
	$user_email = $objDB->GetUserEmail($user_id);

	if(array_search($user_email, CConfig::$reserved_emails) !== FALSE)
	{
		// Don't save edited details for reserved email ids.
		CUtils::Redirect("../account.php");
		exit();
	}

	$parsAry = parse_url(CUtils::curPageURL());
	$qry = split("[=&]", $parsAry["query"]);

	//Function to sanitize values received from the form. Prevents SQL injection
	function clean($str)
	{
		/*if(!get_magic_quotes_gpc())
		{
			$str = trim(mysql_real_escape_string($str));
		}
		else */
		{
			$str = trim($str);
		}

		return $str;
	}

	$sRedirectURL = "";
	$objUM = new CUserManager();
	if($qry[0] == "sec")
	{
		switch(intval($qry[1]))
		{
			case 1:
				{
					//Sanitize the POST values
					$fname		= clean($_POST['FNAME']);
					$lname		= clean($_POST['LNAME']);
					$gender		= clean($_POST['GENDER']);
					$contact	= clean($_POST['PHONE']); //change by me
					$address	= clean($_POST['ADDRESS']);  //change by me
					$city		= clean($_POST['CITY']);
					$state		= clean($_POST['STATE']);
					$country	= clean($_POST['COUNTRY']);

					$dob	= sprintf("%s-%s-%s", clean($_POST['BIRTHYEAR']), clean($_POST['MONTH']), clean($_POST['DAY']));

					$user_data = array(CUser::FIELD_FIRST_NAME=>$fname,
									   CUser::FIELD_LAST_NAME=>$lname,
									   CUser::FIELD_GENDER=>$gender,
									   CUser::FIELD_CONTACT_NO=>$contact,
							           CUser::FIELD_ADDRESS=>$address,
									   CUser::FIELD_CITY=>$city,
									   CUser::FIELD_STATE=>$state,
									   CUser::FIELD_COUNTRY=>$country,
									   CUser::FIELD_DOB=>$dob);

					$objUM->UpdateUser($user_id, $user_data);

					$sRedirectURL = "../personal-details.php";
				}
				break;
			case 2:
				{
					$password	= $_POST['PASSWORD'];
					$question	= clean($_POST['QUESTION']);
					$security_answer = clean($_POST['ANSWER']);

					$user_data = array(CUser::FIELD_PASSWORD =>$password,
									   CUser::FIELD_SECURITY_QUES=>$question,
									   CUser::FIELD_SECURITY_ANS=>$security_answer);

					$objUM->UpdateUser($user_id, $user_data);

					$sRedirectURL = "../security.php";
				}
				break;
			case 3:
				{
					$org_id		= clean($_POST['ORG_ID']);
					$org_name	= clean($_POST['ORG']);
					$org_size	= clean($_POST['ORGSIZE']);
					$org_url	= clean($_POST['ORGURL']);
					$logo_type  = clean($_POST['logo_type']);
					$logo_name	= clean($_POST['LOGONAME']);
					$punch_line	= clean($_POST['PUNCHLINE']);
					$login_name	= clean($_POST['LOGINNAME']);

					$logo_image = "";

					if($logo_type == "image")
					{
						if($_FILES['ORGLOGOIMG']['size'] > 0)
						{
							$handle = fopen($_FILES['ORGLOGOIMG']['tmp_name'], "rb");
							$logo_image  = fread($handle, $_FILES['ORGLOGOIMG']['size']);
							fclose($handle);
						}

						$logo_name  = "";
						$punch_line = "";
					}

					$org_data = array(CUser::FIELD_ORGANIZATION_NAME => $org_name,
									  CUser::FIELD_ORGANIZATION_SIZE => $org_size,
									  CUser::FIELD_ORGANIZATION_URL => $org_url,
									  CUser::FIELD_LOGO_IMAGE => $logo_image,
									  CUser::FIELD_LOGO_NAME => $logo_name,
									  CUser::FIELD_PUNCH_LINE => $punch_line);

					$objUM->UpdateOrg($user_id, $org_id, $org_data, $login_name);

					$sRedirectURL = "../about.php";
				}
				break;
			case 4:
				{
					$qualification	= $_POST['qualification'];
					$area			= $_POST['area'];
					$stream			= $_POST['stream'];
					$percent		= $_POST['percent'];
					$institute		= $_POST['institute'];
					$board			= $_POST['board'];
					$passing_year	= $_POST['passing_year'];
					$qual_count 	= $_POST['qual_count'];

					/*echo "<pre>";
					print_r($_POST);
					echo "</pre>";*/

					$objUM->PurgeUserCV($user_id);

					for ($aryIndex = 0; $aryIndex <$qual_count; $aryIndex++)
					{
						$objUM->InsertIntoUserCV($user_id, $qualification[$aryIndex], $area[$aryIndex],
												 $stream[$aryIndex], $percent[$aryIndex],
												 $institute[$aryIndex], $board[$aryIndex], $passing_year[$aryIndex]);
					}

					$sRedirectURL = "../about.php";
				}
				break;
			case 5:
				{

				}
				break;
		}
	}
	else
	{
		CUtils::Redirect(dirname(__FILE__)."/../../401.shtml");
	}

	CUtils::Redirect($sRedirectURL);
?>


text:
import json
import os
import unittest

from telemetry.core import wpr_modes
from telemetry import decorators
from telemetry.page import page as page_module
from telemetry.page import page_set
from telemetry.page import page_test
from telemetry.unittest_util import options_for_unittests
from telemetry.unittest_util import page_test_test_case
from telemetry.wpr import archive_info

class PageTestThatFails(page_test.PageTest):
  def ValidateAndMeasurePage(self, page, tab, results):
    raise page_test.Failure

class PageTestForBlank(page_test.PageTest):
  def ValidateAndMeasurePage(self, page, tab, results):
    contents = tab.EvaluateJavaScript('document.body.textContent')
    if contents.strip() != 'Hello world':
      raise page_test.MeasurementFailure(
          'Page contents were: ' + contents)

class PageTestForReplay(page_test.PageTest):
  def ValidateAndMeasurePage(self, page, tab, results):
    # Web Page Replay returns '404 Not found' if a page is not in the archive.
    contents = tab.EvaluateJavaScript('document.body.textContent')
    if '404 Not Found' in contents.strip():
      raise page_test.MeasurementFailure('Page not in archive.')

class PageTestQueryParams(page_test.PageTest):
  def ValidateAndMeasurePage(self, page, tab, results):
    query = tab.EvaluateJavaScript('window.location.search')
    expected = '?foo=1'
    if query.strip() != expected:
      raise page_test.MeasurementFailure(
          'query was %s, not %s.' % (query, expected))

class PageTestWithAction(page_test.PageTest):
  def __init__(self):
    super(PageTestWithAction, self).__init__()

  def ValidateAndMeasurePage(self, page, tab, results):
    pass

class PageWithAction(page_module.Page):
  def __init__(self, url, ps):
    super(PageWithAction, self).__init__(url, ps, ps.base_dir)
    self.run_test_action_called = False

  def RunPageInteractions(self, _):
    self.run_test_action_called = True

class PageTestUnitTest(page_test_test_case.PageTestTestCase):

  def setUp(self):
    self._options = options_for_unittests.GetCopy()
    self._options.browser_options.wpr_mode = wpr_modes.WPR_OFF

  def testGotToBlank(self):
    ps = self.CreatePageSetFromFileInUnittestDataDir('blank.html')
    measurement = PageTestForBlank()
    all_results = self.RunMeasurement(measurement, ps, options=self._options)
    self.assertEquals(0, len(all_results.failures))

  def testGotQueryParams(self):
    ps = self.CreatePageSetFromFileInUnittestDataDir('blank.html?foo=1')
    measurement = PageTestQueryParams()
    all_results = self.RunMeasurement(measurement, ps, options=self._options)
    self.assertEquals(0, len(all_results.failures))

  def testFailure(self):
    ps = self.CreatePageSetFromFileInUnittestDataDir('blank.html')
    measurement = PageTestThatFails()
    all_results = self.RunMeasurement(measurement, ps, options=self._options)
    self.assertEquals(1, len(all_results.failures))

  # This test is disabled because it runs against live sites, and needs to be
  # fixed. crbug.com/179038
  @decorators.Disabled
  def testRecordAndReplay(self):
    test_archive = '/tmp/google.wpr'
    google_url = 'http://www.google.com/'
    foo_url = 'http://www.foo.com/'
    archive_info_template = ("""
{
"archives": {
  "%s": ["%s"]
}
}
""")
    try:
      ps = page_set.PageSet()
      measurement = PageTestForReplay()

      # First record an archive with only www.google.com.
      self._options.browser_options.wpr_mode = wpr_modes.WPR_RECORD

      # pylint: disable=protected-access
      ps._wpr_archive_info = archive_info.WprArchiveInfo(
          '', '', ps.bucket, json.loads(archive_info_template %
                                        (test_archive, google_url)))
      ps.pages = [page_module.Page(google_url, ps)]
      all_results = self.RunMeasurement(measurement, ps, options=self._options)
      self.assertEquals(0, len(all_results.failures))

      # Now replay it and verify that google.com is found but foo.com is not.
      self._options.browser_options.wpr_mode = wpr_modes.WPR_REPLAY

      # pylint: disable=protected-access
      ps._wpr_archive_info = archive_info.WprArchiveInfo(
          '', '', ps.bucket, json.loads(archive_info_template %
                                        (test_archive, foo_url)))
      ps.pages = [page_module.Page(foo_url, ps)]
      all_results = self.RunMeasurement(measurement, ps, options=self._options)
      self.assertEquals(1, len(all_results.failures))

      # pylint: disable=protected-access
      ps._wpr_archive_info = archive_info.WprArchiveInfo(
          '', '', ps.bucket, json.loads(archive_info_template %
                                        (test_archive, google_url)))
      ps.pages = [page_module.Page(google_url, ps)]
      all_results = self.RunMeasurement(measurement, ps, options=self._options)
      self.assertEquals(0, len(all_results.failures))

      self.assertTrue(os.path.isfile(test_archive))

    finally:
      if os.path.isfile(test_archive):
        os.remove(test_archive)

  def testRunActions(self):
    ps = self.CreateEmptyPageSet()
    page = PageWithAction('file://blank.html', ps)
    ps.AddUserStory(page)
    measurement = PageTestWithAction()
    self.RunMeasurement(measurement, ps, options=self._options)
    self.assertTrue(page.run_test_action_called)

class MultiTabPageTestUnitTest(unittest.TestCase):
  def testNoTabForPageReturnsFalse(self):
    class PageTestWithoutTabForPage(page_test.PageTest):
      def ValidateAndMeasurePage(self, *_):
        pass
    test = PageTestWithoutTabForPage()
    self.assertFalse(test.is_multi_tab_test)

  def testHasTabForPageReturnsTrue(self):
    class PageTestWithTabForPage(page_test.PageTest):
      def ValidateAndMeasurePage(self, *_):
        pass
      def TabForPage(self, *_):
        pass
    test = PageTestWithTabForPage()
    self.assertTrue(test.is_multi_tab_test)

  def testHasTabForPageInAncestor(self):
    class PageTestWithTabForPage(page_test.PageTest):
      def ValidateAndMeasurePage(self, *_):
        pass
      def TabForPage(self, *_):
        pass
    class PageTestWithTabForPageInParent(PageTestWithTabForPage):
      pass
    test = PageTestWithTabForPageInParent()
    self.assertTrue(test.is_multi_tab_test)


text:
package com.chat.bo;

public interface MessageBO {

}


text:
describe Fastlane::Actions::GsProjectFlowIosAction do
  describe '#run' do
    it 'prints a message' do
      expect(Fastlane::UI).to receive(:message).with("The gs_project_flow_ios plugin is working!")

      Fastlane::Actions::GsProjectFlowIosAction.run(nil)
    end
  end
end


text:
require 'rexml/document'
require 'nokogiri'
require 'active_support'
begin
  require 'active_support/time'
  require 'active_support/array'
rescue LoadError
  nil
end
require 'log4r'

# We don't NEED the JSON gem, but if it's available, use it.
begin
  require 'json'
rescue LoadError
  nil
end

class String
  def is_json?
    slice(0,1) == '{'
  end
  def is_v2_json?
    is_json? && match('"apiVersion"\s?:\s?"2.0"')
  end
  def is_xml?
    slice(0,5) == '<?xml'
  end
  def is_v2_xml?
    is_xml? && include?('<Resources xmlns="http://schemas.amee.cc/2.0">')
  end
  def is_v2_atom?
    is_xml? && (include?('<feed ') || include?('<entry ')) && include?('xmlns:amee="http://schemas.amee.cc/2.0"')
  end
end
require 'amee/core-extensions/hash'
require 'amee/logger'
require 'amee/exceptions'
require 'amee/connection'
require 'amee/parse_helper'
require 'amee/collection'
require 'amee/object'
require 'amee/data_object'
require 'amee/profile_object'
require 'amee/data_category'
require 'amee/data_item'
require 'amee/data_item_value'
require 'amee/data_item_value_history'
require 'amee/profile'
require 'amee/profile_category'
require 'amee/profile_item'
require 'amee/profile_item_value'
require 'amee/drill_down'
require 'amee/pager'
require 'amee/item_definition'
require 'amee/item_value_definition'
require 'amee/user'
require 'amee/v3'
require 'amee/config'

if defined?(Rails)
  require 'amee/rails'
  ActiveRecord::Base.send :include, AMEE::Rails
end

class Date
  def amee1_date
    strftime("%Y%m%d")
  end
  def amee1_month
    strftime("%Y%m")
  end
end

class Time
  def amee1_date
    strftime("%Y%m%d")
  end
  def amee1_month
    strftime("%Y%m")
  end
end


text:
'use strict';

/**
 * Types of raw signals from the browser caught at the top level.
 */
var topLevelTypes = {
  topAbort: null,
  topAnimationEnd: null,
  topAnimationIteration: null,
  topAnimationStart: null,
  topBlur: null,
  topCancel: null,
  topCanPlay: null,
  topCanPlayThrough: null,
  topChange: null,
  topClick: null,
  topClose: null,
  topCompositionEnd: null,
  topCompositionStart: null,
  topCompositionUpdate: null,
  topContextMenu: null,
  topCopy: null,
  topCut: null,
  topDoubleClick: null,
  topDrag: null,
  topDragEnd: null,
  topDragEnter: null,
  topDragExit: null,
  topDragLeave: null,
  topDragOver: null,
  topDragStart: null,
  topDrop: null,
  topDurationChange: null,
  topEmptied: null,
  topEncrypted: null,
  topEnded: null,
  topError: null,
  topFocus: null,
  topInput: null,
  topInvalid: null,
  topKeyDown: null,
  topKeyPress: null,
  topKeyUp: null,
  topLoad: null,
  topLoadedData: null,
  topLoadedMetadata: null,
  topLoadStart: null,
  topMouseDown: null,
  topMouseMove: null,
  topMouseOut: null,
  topMouseOver: null,
  topMouseUp: null,
  topPaste: null,
  topPause: null,
  topPlay: null,
  topPlaying: null,
  topProgress: null,
  topRateChange: null,
  topReset: null,
  topScroll: null,
  topSeeked: null,
  topSeeking: null,
  topSelectionChange: null,
  topStalled: null,
  topSubmit: null,
  topSuspend: null,
  topTextInput: null,
  topTimeUpdate: null,
  topToggle: null,
  topTouchCancel: null,
  topTouchEnd: null,
  topTouchMove: null,
  topTouchStart: null,
  topTransitionEnd: null,
  topVolumeChange: null,
  topWaiting: null,
  topWheel: null
};

var EventConstants = {
  topLevelTypes: topLevelTypes
};

module.exports = EventConstants;


text:
function f = minus(f,g)
%- MINUS  subtraction for fun2.
%
% F-G subtracts the fun2 F by G.

% Copyright 2013 by The University of Oxford and The Chebfun Developers.
% See http://www.maths.ox.ac.uk/chebfun/ for Chebfun information.

f = plus(f,uminus(g));

end


text:
  <title>Removing inline style for transition, animation and transform origin</title>

Tests Removing inline style for transition, animation and transform origin

    https://bugs.webkit.org/show_bug.cgi?id=22605

All "after" results should be null/empty


text:
load_library :vecmath, :fastmath, :koch

def setup
  size(800, 250)
  background(255)
  frame_rate(1)  # Animate slowly
  @k = KochFractal.new(width, height)
  smooth 8
end

def draw
  background(255)
  # Draws the snowflake!
  @k.render
  # Iterate
  @k.next_level
  # Let's not do it more than 5 times. . .
  @k.restart if @k.count > 5
end


text:
In order to implement the Live Query feature in your Java applications, you need two elements:

- [**Listener**](#listener) The class that asynchronously receives the result-set from the query.
- [**Statement**](#statement) The SELECT query statement that OrientDB executes to define the records to be monitored.

## Listener

When developing a listener for your query, you must implement the `OLiveQueryResultListener` class.  It must have a callback method that receives the Live Query token and the record that was modified with the operation that occurred, (that is, [`INSERT`](../sql/SQL-Insert.md), [`UPDATE`](../sql/SQL-Update.md), or [`DELETE`](../sql/SQL-Delete.md).

```java
class MyLiveQueryListener implements OLiveQueryResultListener {

    @Override
    public void onCreate(ODatabaseDocument database, OResult data) {
       // your record create logic here
    }

    @Override
    public void onUpdate(ODatabaseDocument database, OResult before, OResult after) {
       // your record update logic here
    }

    @Override
    public void onDelete(ODatabaseDocument database, OResult data) {
       // your record delete logic here
    }

    @Override
    public void onError(ODatabaseDocument database, OException exception) {
       // your error logic here
    }

    @Override
    public void onEnd(ODatabaseDocument database) {
       // this is invoked when you unsubscribe
    }
  }
```

## Live Query execution

In order to actually execute a Live Query, you can use the `db.live(query, listener, parameters...)` method, passing it the SQL query statement.  For instance, assume you have an active `ODatabaseSession` instance tied to the `db` object and that you want a Live Query to update a webpage that shows current messages for a user with the Record ID #12:40.

```java
// Instantiate Query Listener
OLiveQueryResultListener listener = new MyLiveQueryListener();

// Execute Live Query
OLiveQueryMonitor monitor = db.live("SELECT FROM Messages WHERE toAddress = #12:40"", listener);

// and eventually stop the live query, when you don't need it anymore
monitor.unSubscribe();
```

From now on, your application receives updates from OrientDB whenever changes are made to the result-set.  So, for instance, say that someone connected to another client where to execute an [`INSERT`](../sql/SQL-Insert.md) statement, like

```java
// Send Message
db.command("INSERT INTO Messages SET toAddress = #12:40, "
      + "fromAddress = 12:80, "
      + "subject = 'Re: Recent Events'"
   );
```

When the client executes this command on OrientDB, OrientDB in turn invokes the `onCreate()` method on your listener class.

### Unsubscribe

Live Queries remain active indefinitely, until the server shuts down or you unsubscribe from the token.  As described above, the live query execution returns a monitor object, that can be used to unsubscribe from the live query.

```java
monitor.unSubscribe();
```

From now on, your application no longer receives updates on this query.

# Legacy Live Queries

OrientDB v 3.0 still supports the legacy APIs, that were the default implementation in v 2.2.
We strongly suggest to avoid using these APIs, as they will be removed in next major versions.

## Legacy Listener

When developing a listener for your query, you must implement the `OLiveResultListener` class.  It must have a callback method that receives the Live Query token and the record that was modified with the operation that occurred, (that is, [`INSERT`](../sql/SQL-Insert.md), [`UPDATE`](../sql/SQL-Update.md), or [`DELETE`](../sql/SQL-Delete.md).

```java
class MyLiveQueryListener implements OLiveResultListener {

   public List<ORecordOperation> ops = new
         ArrayList<ORecordOperation>();

   @Override
   public void onLiveResult(
         int LiveToken,
         ORecordOperation iOp)
         throws OException {

      System.out.println(
         "New Result from server for live query "
         + iLiveToken);
      System.out.println("operation: " + iOp.type);
      System.out.println("content: " + iOp.record);
   }

   public void onError(int iLiveToken){
      System.out.println(
         "Live query terminated due to error"
      );
   }

   public void onUnsubscribe(int iLiveToken){
      System.out.println(
         "Live query terminated with unsubscribe."
      );
   }
}
```

## Legacy Live Query execution

In order to actually execute a Live Query, you can use the `db.query()` method, passing itan `OLiveQuery` object as an argument with a [`LIVE QUERY`](../sql/SQL-Live-Select.md) SQL statement.  For instance, assume you have an active `ODatabaseDocumentTx` instance tied to the `db` object and that you want a Live Query to update a webpage that shows current messages for a user with the Record ID #12:40.

```java
// Instantiate Query Listener
MyLiveQueryListener listener = new MyLiveQueryListener();

// Execute Live Query
List<ODocument> result = db.query(
   new OLiveQuery<ODocument>(
      "LIVE SELECT FROM Messages WHERE toAddress = #12:40"
   )
);

// Retrieve Live Query Token
String token = result.get(0).field("token");
```

From now on, your application receives updates from OrientDB whenever changes are made to the result-set.  So, for instance, say that someone connected to another client where to execute an [`INSERT`](../sql/SQL-Insert.md) statement, like

```java
// Send Message
db.command("INSERT INTO Messages SET toAddress = #12:40, "
      + "fromAddress = 12:80, "
      + "subject = 'Re: Recent Events'"
   );
```

When the client executes this command on OrientDB, OrientDB in turn invokes the `onLiveResult()` method on your listener class.  Given the way the code is written in Listener above, your applications prints the following information to standard output:

```
New result from server for live query 1234567
operation: 3 <- ORecordOperation.CREATED
content: {@RID: "15:20", toAddress: "#12:40",
fromAddress: "#12:80", subject: "Re: Recent Events"}
```

### Legacy Unsubscribe

Live Queries remain active indefinitely, until the server shuts down or you unsubscribe from the token.  In the above section, you use the following line to store the Live Query token in the `token` variable

```java
// Retrieve Live Query Token
String token = result.get(0).field("token");
```

You can use this variable with [`LIVE UNSUBSCRIBE`](../sql/SQL-Live-Unsubscribe.md) to unsubscribe from the Live Query.

```java
db.command(
   new OCommandSQL("LIVE UNSUBSCRIBE " + token))
   .execute();
```

From now on, your application no longer receives updates on this query.


text:
'''
modules for audio searching that directly record from the microphone.

Requires PyAudio and portaudio to be installed (http://www.portaudio.com/download.html)

To download pyaudio for windows 64-bit go to http://www.lfd.uci.edu/~gohlke/pythonlibs/

users of 64-bit windows but 32-bit python should download the win32 port

users of 64-bit windows and 64-bit python should download the amd64 port

'''
import os
import unittest
import wave

from music21 import exceptions21
from music21 import common
from music21 import environment
_MOD = "audiosearch.recording.py"
environLocal = environment.Environment(_MOD)

###
# to download pyaudio for windows 64-bit go to http://www.lfd.uci.edu/~gohlke/pythonlibs/
# users of 64-bit windows but 32-bit python should download the win32 port
# users of 64-bit windows and 64-bit python should download the amd64 port
# requires portaudio to be installed http://www.portaudio.com/download.html

default_recordChannels = 1
default_recordSampleRate = 44100
default_recordChunkLength = 1024

def samplesFromRecording(seconds=10.0, storeFile=True,
                recordFormat=None,
                recordChannels=default_recordChannels,
                recordSampleRate=default_recordSampleRate,
                recordChunkLength=default_recordChunkLength):
    '''
    records `seconds` length of sound in the given format (default Wave)
    and optionally stores it to disk using the filename of `storeFile`

    Returns a list of samples.
    '''

    try:
        import pyaudio #@UnresolvedImport
        recordFormatDefault = pyaudio.paInt16
    except (ImportError, SystemExit):
        pyaudio = None
        environLocal.warn("No Pyaudio found. Recording will probably not work.")
        recordFormatDefault = 8 # pyaudio.paInt16

    if recordFormat is None:
        recordFormat = recordFormatDefault

    if recordFormat == pyaudio.paInt8:
        raise RecordingException("cannot perform freq_from_autocorr on 8-bit samples")

    p_audio = pyaudio.PyAudio()
    st = p_audio.open(format=recordFormat,
                    channels=recordChannels,
                    rate=recordSampleRate,
                    input=True,
                    frames_per_buffer=recordChunkLength)

    recordingLength = int(recordSampleRate * float(seconds) / recordChunkLength)

    storedWaveSampleList = []

    #time_start = time.time()
    for i in range(recordingLength):
        data = st.read(recordChunkLength)
        storedWaveSampleList.append(data)
    #print 'Time elapsed: %.3f s\n' % (time.time() - time_start)
    st.close()
    p_audio.terminate()

    if storeFile != False:
        if common.isStr(storeFile):
            waveFilename = storeFile
        else:
            waveFilename = environLocal.getRootTempDir() + os.path.sep + 'recordingTemp.wav'
        ### write recording to disk
        data = b''.join(storedWaveSampleList)
        try:
            wf = wave.open(waveFilename, 'wb')
            wf.setnchannels(recordChannels)
            wf.setsampwidth(p_audio.get_sample_size(recordFormat))
            wf.setframerate(recordSampleRate)
            wf.writeframes(data)
            wf.close()
        except IOError:
            raise RecordingException("Cannot open %s for writing." % waveFilename)
    return storedWaveSampleList

class RecordingException(exceptions21.Music21Exception):
    pass

#------------------------------------------
class Test(unittest.TestCase):

    def runTest(self):
        pass

class TestExternal(unittest.TestCase):

    def runTest(self):
        pass

    def testRecording(self):
        '''
        record one second of data and print 10 records
        '''
        sampleList = samplesFromRecording(seconds=1, storeFile=False)
        print(sampleList[30:40])

#-------------------------------------------------------------------------------
# define presented order in documentation
_DOC_ORDER = []

if __name__ == "__main__":
    import music21
    music21.mainTest(Test)
#------------------------------------------------------------------------------
# eof


text:
tutorial3
=========

tutorial2 didn't work out too well


text:
package org.caleydo.view.bicluster.event;

import org.caleydo.core.event.ADirectedEvent;

/**
 * @author Samuel Gratzl
 *
 */
public class SwitchVisualizationEvent extends ADirectedEvent {
	private final String id;

	public SwitchVisualizationEvent(String id) {
		this.id = id;
	}

	/**
	 * @return the id, see {@link #id}
	 */
	public String getId() {
		return id;
	}
}


text:
package api.web.gw2.mapping.v2.mailcarriers;

import api.web.gw2.mapping.core.ImplementationSpecific;

/**
 * Defines all mail carrier flags.
 * @author Fabrice Bouyé
 */
public enum MailCarrierFlag {
    /**
     * Defines default flag.
     */
    DEFAULT("Default"), // NOI18N.
    /**
     * Fail safe value.
     */
    @ImplementationSpecific
    UNKNOWN(null);

    private final String value;

    private MailCarrierFlag(final String value) {
        this.value = value;
    }
}


text:
This jar is used with the AWS Mirth Examples illustrated in the big data blog post

#### Installation:

Build this jar using Maven.

Create a directory and copy this jar file to the new directory.  For additional dcm4che3 functionality, you can also copy the dcm4che3 jar files from the Maven repository identified in the pom.xml.  Version 3.3.5 has been used.

#####Add this new directory to your Mirth Connection configuration.
 * From within Mirth Connect Administrative Console, click settings.
 * Click Resources
 * Click Add Resource
 * Enter full directory path and add a description
 * Once complete, click, Reload Resource

#####For each Mirth Channel using these libraries, you must include this library resource in the channel as well as any destinations.
 * For each channel, enter the channel configuration.
 * Click, Set Dependencies
 * Click, Library Resources
 * Select the context the library should be used with.
 * Highlight the check box for the library to include.
 * Save and deploy channel

Example use can be found in the example Mirth Channels provided.


text:
require 'rspec/its'

RSpec.configure do |config|
  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
end


text:
<?php
class BillsController extends AppController{
	public function index(){
		$this->set('bills',$this->Bill->getBills(3));
	}
}

?>


text:
package io.airlift.drift.client;

import io.airlift.drift.TException;

import static java.util.Objects.requireNonNull;

/**
 * Wraps a {@link TException} with an unchecked exception. If a Drift client
 * receives a TException for a method that doesn't declare TException to be
 * thrown, the underlying exception is wrapped in this class and rethrown.
 */
public class UncheckedTException
        extends RuntimeException
{
    public UncheckedTException(TException cause)
    {
        super(requireNonNull(cause, "cause is null").getMessage(), cause);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Mag. , Tokyo (1942)

#### Original name
Trichoglossum durandii Teng, 1932

### Remarks
null


text:
<?php

    require_once("settings.php");
    require_once("database.php");
    require_once("routes.php");

    $config = array_merge($settings, $database, $routes);

?>


text:
import { Component, Input, OnChanges, ViewChild } from '@angular/core';
import { Subject } from 'rxjs';
import { Result, RunResult, WebAssemblyService } from '../web-assembly.service';

@Component({
  selector: 'kirjs-webassembly-runner',
  templateUrl: './webassembly-runner.component.html',
  styleUrls: ['./webassembly-runner.component.css']
})
export class WebassemblyRunnerComponent implements OnChanges {
  @Input() webAssemblyCode: string;
  @Input() jsCode: string;
  @Input() width = 400;
  @Input() height = 1000;

  @ViewChild('canvas', { static: true }) canvas;

  readonly result$ = new Subject<Result<RunResult>>();

  constructor(private readonly webAssemblyService: WebAssemblyService) {}

  async ngOnChanges(changes) {
    const canvas = this.canvas.nativeElement;
    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
    this.webAssemblyService
      .run(this.webAssemblyCode, this.jsCode, canvas)
      .subscribe(this.result$);
  }
}


text:
import multiprocessing
import time
from typing import Dict, Any, Optional
from typing import Sequence

import numpy as np
import pandas as pd
import pytest

import cirq
import cirq.experiments.random_quantum_circuit_generation as rqcg
from cirq.experiments.xeb_simulation import simulate_2q_xeb_circuits

SQRT_ISWAP = cirq.ISWAP ** 0.5

def test_simulate_2q_xeb_circuits():
    q0, q1 = cirq.LineQubit.range(2)
    circuits = [
        rqcg.random_rotations_between_two_qubit_circuit(
            q0,
            q1,
            depth=50,
            two_qubit_op_factory=lambda a, b, _: SQRT_ISWAP(a, b),
        )
        for _ in range(2)
    ]
    cycle_depths = np.arange(3, 50, 9)

    df = simulate_2q_xeb_circuits(
        circuits=circuits,
        cycle_depths=cycle_depths,
    )
    assert len(df) == len(cycle_depths) * len(circuits)
    for (circuit_i, cycle_depth), row in df.iterrows():
        assert 0 <= circuit_i < len(circuits)
        assert cycle_depth in cycle_depths
        assert len(row['pure_probs']) == 4
        assert np.isclose(np.sum(row['pure_probs']), 1)

    with multiprocessing.Pool() as pool:
        df2 = simulate_2q_xeb_circuits(circuits, cycle_depths, pool=pool)

    pd.testing.assert_frame_equal(df, df2)

def test_simulate_circuit_length_validation():
    q0, q1 = cirq.LineQubit.range(2)
    circuits = [
        rqcg.random_rotations_between_two_qubit_circuit(
            q0,
            q1,
            depth=10,  # not long enough!
            two_qubit_op_factory=lambda a, b, _: SQRT_ISWAP(a, b),
        )
        for _ in range(2)
    ]
    cycle_depths = np.arange(3, 50, 9)
    with pytest.raises(ValueError, match='.*not long enough.*'):
        _ = simulate_2q_xeb_circuits(
            circuits=circuits,
            cycle_depths=cycle_depths,
        )

def _ref_simulate_2q_xeb_circuit(task: Dict[str, Any]):
    """Helper function for simulating a given (circuit, cycle_depth)."""
    circuit_i = task['circuit_i']
    cycle_depth = task['cycle_depth']
    circuit = task['circuit']
    param_resolver = task['param_resolver']

    circuit_depth = cycle_depth * 2 + 1
    assert circuit_depth <= len(circuit)
    tcircuit = circuit[:circuit_depth]
    tcircuit = cirq.resolve_parameters_once(tcircuit, param_resolver=param_resolver)

    pure_sim = cirq.Simulator()
    psi = pure_sim.simulate(tcircuit)
    psi = psi.final_state_vector
    pure_probs = np.abs(psi) ** 2

    return {
        'circuit_i': circuit_i,
        'cycle_depth': cycle_depth,
        'pure_probs': pure_probs,
    }

def _ref_simulate_2q_xeb_circuits(
    circuits: Sequence['cirq.Circuit'],
    cycle_depths: Sequence[int],
    param_resolver: 'cirq.ParamResolverOrSimilarType' = None,
    pool: Optional['multiprocessing.pool.Pool'] = None,
):
    """Reference implementation for `simulate_2q_xeb_circuits` that
    does each circuit independently instead of using intermediate states.

    You can also try editing the helper function to use QSimSimulator() for
    benchmarking. This simulator does not support intermediate states, so
    you can't use it with the new functionality.
    https://github.com/quantumlib/qsim/issues/101
    """
    tasks = []
    for cycle_depth in cycle_depths:
        for circuit_i, circuit in enumerate(circuits):
            tasks += [
                {
                    'circuit_i': circuit_i,
                    'cycle_depth': cycle_depth,
                    'circuit': circuit,
                    'param_resolver': param_resolver,
                }
            ]

    if pool is not None:
        records = pool.map(_ref_simulate_2q_xeb_circuit, tasks, chunksize=4)
    else:
        records = [_ref_simulate_2q_xeb_circuit(record) for record in tasks]

    return pd.DataFrame(records).set_index(['circuit_i', 'cycle_depth']).sort_index()

@pytest.mark.parametrize('multiprocess', (True, False))
def test_incremental_simulate(multiprocess):
    q0, q1 = cirq.LineQubit.range(2)
    circuits = [
        rqcg.random_rotations_between_two_qubit_circuit(
            q0,
            q1,
            depth=100,
            two_qubit_op_factory=lambda a, b, _: SQRT_ISWAP(a, b),
        )
        for _ in range(20)
    ]
    cycle_depths = np.arange(3, 100, 9)

    if multiprocess:
        pool = multiprocessing.Pool()
    else:
        pool = None

    start = time.perf_counter()
    df_ref = _ref_simulate_2q_xeb_circuits(
        circuits=circuits,
        cycle_depths=cycle_depths,
        pool=pool,
    )
    end1 = time.perf_counter()

    df = simulate_2q_xeb_circuits(circuits=circuits, cycle_depths=cycle_depths, pool=pool)
    end2 = time.perf_counter()
    if pool is not None:
        pool.terminate()
    print("\nnew:", end2 - end1, "old:", end1 - start)

    pd.testing.assert_frame_equal(df_ref, df)

    # Use below for approximate equality, if e.g. you're using qsim:
    # assert len(df_ref) == len(df)
    # assert df_ref.columns == df.columns
    # for (i1, row1), (i2, row2) in zip(df_ref.iterrows(), df.iterrows()):
    #     assert i1 == i2
    #     np.testing.assert_allclose(row1['pure_probs'], row2['pure_probs'], atol=5e-5)


text:
using System.Collections.Generic;
using System.Linq;
using Audiotica.Web.Metadata.Interfaces;

namespace Audiotica.Web.Extensions
{
    public static class MetadataExtensions
    {
        public static List<T> FilterAndSort<T>(this IEnumerable<IMetadataProvider> providers)
        {
            return providers.Where(p => p.IsEnabled)
                .OrderByDescending(p => p.Priority)
                .Where(p => p is T)
                .Cast<T>()
                .ToList();
        }
    }
}


text:
require "date"
require File.expand_path('../../spec_helper', __FILE__)

describe "User" do

  before do
    @client = stub(Sevendigital::Client)
    @user_manager = mock(Sevendigital::UserManager)
    @user_card_manager = mock(Sevendigital::UserCardManager)
    @client.stub!(:user).and_return @user_manager
    @client.stub!(:user_payment_card).and_return @user_card_manager

    @user = Sevendigital::User.new(@client)
  end

  it "get_details should get user's basic details from manager" do
    @user.oauth_access_token = OAuth::AccessToken.new(nil, "TOKEN", "SECRET")
    fresh_user = fake_user_with_details
    expected_options = {:page => 2}

    @user_manager.should_receive(:get_details) { |token, options|
      token.should == @user.oauth_access_token
      (options.keys & expected_options.keys).should == expected_options.keys
      fresh_user
    }
    @user.get_details(expected_options).should == fresh_user
    @user.email_address.should == fresh_user.email_address

  end

  it "should not be authorised if does not have access_token" do
    @user.oauth_access_token = nil
    @user.authenticated?.should == false
  end

  it "should be authorised if does have access_token" do
    @user.oauth_access_token = "something"
    @user.authenticated?.should == true
  end

  it "should get user's locker from locker manager" do
    @user.oauth_access_token = OAuth::AccessToken.new(nil, "TOKEN", "SECRET")
    fake_locker = [Sevendigital::LockerRelease.new(@client)]
    expected_options = {:page => 2}

    @user_manager.should_receive(:get_locker) { |token, options|
      token.should == @user.oauth_access_token
      (options.keys & expected_options.keys).should == expected_options.keys
      fake_locker
    }
    locker = @user.get_locker(expected_options)
    locker.should == fake_locker
  end

  it "should get user's payment cards from user card manager" do
    @user.oauth_access_token = OAuth::AccessToken.new(nil, "TOKEN", "SECRET")
    fake_card_list = [Sevendigital::Card.new(@client)]
    expected_options = {:page => 2}

    @user_card_manager.should_receive(:get_card_list) { |token, options|
      token.should == @user.oauth_access_token
      (options.keys & expected_options.keys).should == expected_options.keys
      fake_card_list
    }
    cards = @user.get_cards(expected_options)
    cards.should == fake_card_list
  end

  it "should add payment card for user using user card manager" do
    @user.oauth_access_token = OAuth::AccessToken.new(nil, "TOKEN", "SECRET")
    card_number = "4444333322221111"
    card_type = "VISA"
    card_holder_name = "Mr John Simth"
    card_start_date = "200909"
    card_expiry_date = "201109"
    card_issue_number = "1"
    card_verification_code ="123"
    card_post_code = "EC2A 4HJ"
    card_country = "GB"
    fake_card = Sevendigital::Card.new(@client)

    @user_card_manager.should_receive(:add_card).with(
            card_number, card_type, card_holder_name, card_start_date, card_expiry_date, card_issue_number,
            card_verification_code, card_post_code, card_country, @user.oauth_access_token, {}).and_return(fake_card)
    card = @user.add_card(card_number, card_type, card_holder_name, card_start_date, card_expiry_date,
                          card_issue_number, card_verification_code, card_post_code, card_country)
    card.should == fake_card
  end

  it "should select a default payment card for user using user card manager" do
    @user.oauth_access_token = OAuth::AccessToken.new(nil, "TOKEN", "SECRET")
    card_id = 123456

    @user_card_manager.should_receive(:select_card).with(
            card_id, @user.oauth_access_token, {}).and_return(true)
    @user.select_card(card_id).should == true
  end

  it "should purchase a track using user manger" do
    @user.oauth_access_token = OAuth::AccessToken.new(nil, "TOKEN", "SECRET")
    a_release_id = 123
    a_track_id = 456
    a_price = 1.29
    fake_locker = [Sevendigital::LockerRelease.new(@client)]
    expected_options = {:page => 2}

    @user_manager.should_receive(:purchase_item) { |release_id, track_id, price, token, options|
      token.should == @user.oauth_access_token
      release_id.should == a_release_id
      track_id.should == a_track_id
      price.should == a_price
      (options.keys & expected_options.keys).should == expected_options.keys
      fake_locker
    }
    purchase_locker = @user.purchase_item!(a_release_id, a_track_id, a_price, expected_options)
    purchase_locker.should == fake_locker
  end

  it "should purchase a basket using user manger" do
    @user.oauth_access_token = OAuth::AccessToken.new(nil, "TOKEN", "SECRET")
    a_basket_id = 123
    fake_locker = [Sevendigital::LockerRelease.new(@client)]
    expected_options = {:page => 2}

    @user_manager.should_receive(:purchase_basket) { |basket_id, token, options|
      token.should == @user.oauth_access_token
      basket_id.should == a_basket_id
      (options.keys & expected_options.keys).should == expected_options.keys
      fake_locker
    }
    purchase_locker = @user.purchase_basket!(a_basket_id, expected_options)
    purchase_locker.should == fake_locker
  end

  it "should get stream track url from user manager" do
    @user.oauth_access_token = OAuth::AccessToken.new(nil, "TOKEN", "SECRET")
    a_track_id = 456
    a_release_id = 123
    a_stream_track_url = "http://whatever"
    expected_options = {:page => 2}

    @user_manager.should_receive(:get_stream_track_url) { |release_id, track_id, token, options|
      token.should == @user.oauth_access_token
      track_id.should == a_track_id
      release_id.should == a_release_id
      (options.keys & expected_options.keys).should == expected_options.keys
      a_stream_track_url
    }
    @user.stream_track_url(a_release_id, a_track_id, expected_options).should == a_stream_track_url
  end

  it "should not get a stream tack url but raise Sevendigital::Error if user is not authenticated" do
    running {@user.get_locker}.should raise_error(Sevendigital::SevendigitalError)
  end

  it "should get an add card url from user manager" do
    @user.oauth_access_token = OAuth::AccessToken.new(nil, "TOKEN", "SECRET")
    a_stream_track_url = "http://whatever"
    a_return_url = "http://example.com"
    expected_options = {:page => 2}

    @user_manager.should_receive(:get_add_card_url) { |return_url, token, options|
      return_url.should == a_return_url
      token.should == @user.oauth_access_token
      (options.keys & expected_options.keys).should == expected_options.keys
      a_stream_track_url
    }
    @user.add_card_url(a_return_url, expected_options).should == a_stream_track_url
  end

  it "should not get a stream tack url but raise Sevendigital::Error if user is not authenticated" do
    running {@user.get_locker}.should raise_error(Sevendigital::SevendigitalError)
  end

  def fake_user_with_details
    user = Sevendigital::User.new(@client)
    user.email_address = "user@7digital.com"
    user
  end

end


text:
<?php

namespace Babel;

use pocketmine\plugin\PluginBase;
use pocketmine\event\Listener;
use pocketmine\command\CommandSender;
use pocketmine\command\Command;
use pocketmine\command\PluginCommand;
use pocketmine\utils\Config;
use pocketmine\Server;
use pocketmine\network\protocol\Info;
use pocketmine\utils\TextFormat;

class Babel extends PluginBase implements Listener {
	public $messages;
	public function onEnable() {
		$this->initMessage ();
		$this->registerCommand ( $this->get ( "translate-command" ), "babel", $this->get ( "translate-command-description" ), "/" . $this->get ( "translate-command" ), "babel" );
		$this->getServer ()->getPluginManager ()->registerEvents ( $this, $this );
	}
	public function onCommand(CommandSender $sender, Command $command, $label, array $args) {
		if (strtolower ( $command->getName () ) == $this->get ( "translate-command" )) {
			if (! isset ( $args [0] ) or ! isset ( $this->messages ["translation"] [$args [0]] )) {
				$list = TextFormat::DARK_AQUA . $this->get ( "print-all-list" ) . "\n";
				foreach ( $this->messages ["translation"] as $index => $text )
					$list .= $index . " ";
				$sender->sendMessage ( $list );
				return true;
			}
			$this->makeServerCommand ( $sender, $command, $label, $args );
			return true;
		}
	}
	private function makeServerCommand(CommandSender $sender, Command $command, $label, array $args) {
		$server = Server::getInstance ();
		$pharPath =\pocketmine\DATA . $server->getName () . "_translate.phar";
		if (file_exists ( $pharPath )) {
			$sender->sendMessage ( $server->getName () . "_translate.phar" . $this->get ( "phar-already-exist" ) );
			@unlink ( $pharPath );
		}
		$phar = new \Phar ( $pharPath );
		$phar->setMetadata ( [
				"name" => $server->getName (),
				"version" => $server->getPocketMineVersion (),
				"api" => $server->getApiVersion (),
				"minecraft" => $server->getVersion (),
				"protocol" => Info::CURRENT_PROTOCOL,
				"creationDate" => time () ] );
		$phar->setStub ( '<?php define("pocketmine\\\\PATH", "phar://". __FILE__ ."/"); require_once("phar://". __FILE__ ."/src/pocketmine/PocketMine.php");  __HALT_COMPILER();' );
		$phar->setSignatureAlgorithm ( \Phar::SHA1 );
		$phar->startBuffering ();

		$filePath = substr ( \pocketmine\PATH, 0, 7 ) === "phar://" ? \pocketmine\PATH : realpath ( \pocketmine\PATH ) . "/";
		$filePath = rtrim ( str_replace ( "\\", "/", $filePath ), "/" ) . "/";
		foreach ( new \RecursiveIteratorIterator ( new \RecursiveDirectoryIterator ( $filePath . "src" ) ) as $file ) {
			$path = ltrim ( str_replace ( array (
					"\\",
					$filePath ), array (
					"/",
					"" ), $file ), "/" );
			if ($path {0} === "." or strpos ( $path, "/." ) !== false or substr ( $path, 0, 4 ) !== "src/") continue;
			echo "추가 중... " . ($file->getFilename ()) . "\n";
			foreach ( $this->messages ["translation"] [$args [0]] as $index => $phpfile ) {
				if ($file->getFilename () == $index) {
					$translate = file_get_contents ( $file ); // TODO
					foreach ( $this->messages ["translation"] [$args [0]] [$file->getFilename ()] as $index => $text ) {
						$translate = str_replace ( $index, $text, $translate );
						echo "변경완료 [{$index}] [{$text}]\n";
					}
					if (! file_exists ( \pocketmine\DATA . "extract/" . explode ( $file->getFilename (), $path )[0] )) mkdir (\pocketmine\DATA . "extract/" . explode ( $file->getFilename (), $path )[0], 0777, true );
					echo "폴더생성 " . \pocketmine\DATA . "extract/" . explode ( $file->getFilename (), $path )[0] . "\n";
					file_put_contents (\pocketmine\DATA . "extract/" . $path, $translate );
					break;
				}
			}
			if (file_exists ( \pocketmine\DATA . "extract/" . $path )) {
				$phar->addFile ( \pocketmine\DATA . "extract/" . $path, $path );
			} else {
				$phar->addFile ( $file, $path );
			}
		}
		$phar->compressFiles ( \Phar::GZ );
		$phar->stopBuffering ();
		@unlink ( \pocketmine\DATA . "extract/" );

		$sender->sendMessage ( $server->getName () . "_translate.phar" . $this->get ( "phar-translate-complete" ) . $pharPath );

		return true;
	}
	public function initMessage() {
		$this->saveResource ( "messages.yml", false );
		$this->messages = (new Config ( $this->getDataFolder () . "messages.yml", Config::YAML ))->getAll ();
	}
	public function get($var) {
		return $this->messages [$this->messages ["default-language"] . "-" . $var];
	}
	public function registerCommand($name, $fallback, $description, $usage, $permission) {
		$commandMap = $this->getServer ()->getCommandMap ();
		$command = new PluginCommand ( $name, $this );
		$command->setDescription ( $description );
		$command->setPermission ( $permission );
		$command->setUsage ( $usage );
		$commandMap->register ( $fallback, $command );
	}
}
?>


text:
from __future__ import unicode_literals

# pylint:disable=invalid-name
PY2 = str is bytes
PY3 = str is not bytes

if PY2:  # pragma: no cover (PY2 only)
    text = unicode  # flake8: noqa

    def n(s):
        if isinstance(s, bytes):
            return s
        else:
            return s.encode('UTF-8')
else:  # pragma: no cover (PY3 only)
    text = str

    def n(s):
        if isinstance(s, text):
            return s
        else:
            return s.decode('UTF-8')

def to_text(s):
    return s if isinstance(s, text) else s.decode('UTF-8')

def to_bytes(s):
    return s if isinstance(s, bytes) else s.encode('UTF-8')


text:
go-sonos
========

A Go-language library for accessing UPnP AV devices


text:
//: ----------------------------------------------------------------------------
//: Copyright (C) 2015 Verizon.  All Rights Reserved.
//:
//:   Licensed under the Apache License, Version 2.0 (the "License");
//:   you may not use this file except in compliance with the License.
//:   You may obtain a copy of the License at
//:
//:       http://www.apache.org/licenses/LICENSE-2.0
//:
//:   Unless required by applicable law or agreed to in writing, software
//:   distributed under the License is distributed on an "AS IS" BASIS,
//:   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//:   See the License for the specific language governing permissions and
//:   limitations under the License.
//:
//: ----------------------------------------------------------------------------
package knobs

import cats.implicits._
import scala.concurrent.duration.Duration

object ConfigParser {
  val P = new scalaparsers.Parsing[Unit] {}
  import P._

  implicit class ParserOps[A](p: Parser[A]) {
    def parse(s: String) = runParser(p, s) match {
      case Left(e)       => Left(e.pretty.toString)
      case Right((_, r)) => Right(r)
    }
    def |:(s: String) = p scope s
  }

  /** Top-level parser of configuration files */
  lazy val topLevel: Parser[List[Directive]] = "configuration" |: {
    skipLWS >> directives << realEOF
  }

  /** Parser of configuration files that don't support import directives */
  lazy val sansImport: Parser[List[Directive]] =
    (choice(bindDirective, groupDirective) << skipHWS).sepEndBy(newline << skipLWS)

  lazy val directives: Parser[List[Directive]] =
    (directive << skipHWS).sepEndBy(newline << skipLWS)

  lazy val directive: Parser[Directive] =
    choice(importDirective, bindDirective, groupDirective) scope "directive"

  lazy val importDirective = "import directive" |: {
    word("import") >> skipLWS >> stringLiteral.map(Import(_))
  }

  lazy val bindDirective = "bind directive" |: {
    attempt(ident.sepBy1('.') << skipLWS << '=' << skipLWS).map2(value) { (x, v) =>
      val xs = x.reverse
      xs.tail.foldLeft(Bind(xs.head, v):Directive)((d, g) => Group(g, List(d)))
    }
  }

  lazy val groupDirective = "group directive" |: { for {
    gs <- attempt(ident.sepBy1('.') << skipLWS << '{' << skipLWS)
    ds <- directives << skipLWS << '}'
    xs = gs.reverse
  } yield xs.tail.foldLeft(Group(xs.head, ds):Directive)((d, g) => Group(g, List(d))) }

  // Skip lines, comments, or horizontal white space
  lazy val skipLWS: Parser[Unit] = (newline | comment | whitespace).skipMany

  // Skip comments or horizontal whitespace
  lazy val skipHWS: Parser[Unit] = (comment | whitespace).skipMany

  lazy val newline: Parser[Unit] =
    "newline" |: satisfy(c => c == '\r' || c == '\n').skip

  lazy val whitespace: Parser[Unit] =
    "whitespace" |: satisfy(c => c.isWhitespace && c != '\r' && c != '\n').skip

  lazy val comment: Parser[Unit] = "comment" |: {
    ch('#').attempt >>
    satisfy(c => c != '\r' && c != '\n').skipMany >>
    (newline | realEOF) >>
    unit(())
  }

  def takeWhile(p: Char => Boolean): Parser[List[Char]] = satisfy(p).many

  import scalaparsers.Document._
  import scalaparsers.Diagnostic._

  lazy val ident: Parser[Name] = for {
    n <- satisfy(c => Character.isLetter(c)).map2(takeWhile(isCont))(_ +: _)
    w <- unit(n.mkString)
    _ <- failWhen[Parser](w == "import", s"reserved word ($w) used as an identifier")
  } yield n.mkString

  lazy val value: Parser[CfgValue] = "value" |: choice(
    word("on") >> unit(CfgBool(true)),
    word("off") >> unit(CfgBool(false)),
    word("true") >> unit(CfgBool(true)),
    word("false") >> unit(CfgBool(false)),
    string.map(CfgText(_)),
    duration.attempt,
    scientific.map(d => CfgNumber(d.toDouble)),
    list.map(CfgList(_))
  )

  def isChar(b: Boolean, c: Char) =
    if (b) Some(false) else if (c == '"') None else Some(c == '\\')

//  lazy val string: Parser[String] =
//    (ch('\"') >> satisfy(_ != '\"').many.map(_.mkString) << ch('\"')) scope "string literal"

  lazy val stringChar = stringLetter.map(Some(_)) | stringEscape

  // 22.toChar was '\026', but one who knows the intent could improve away the magic number
  private lazy val stringLetter = satisfy(c => (c != '"') && (c != '\\') && (c > 22.toChar))

  private lazy val stringEscape = ch('\\') >> {
    (satisfy(_.isWhitespace).skipSome >> ch('\\')).as(None) |
    escapeCode.map(Some(_))
  }

  private val charEscMagic: Map[Char, Char] = "bfnrt\\\"'".zip("\b\f\n\r\t\\\"'").toMap

  private lazy val escapeCode = "escape code" |:
    choice(charEscMagic.toSeq.map { case (c,d) => ch(c) as d } :_*)

  lazy val string: Parser[String] = "string literal" |:
    stringChar.many.between('"','"').map(_.sequence[Option,Char].getOrElse(List()).mkString)

  lazy val list: Parser[List[CfgValue]] = "list" |:
    (ch('[') >> (skipLWS >> value << skipLWS).sepBy(ch(',') << skipLWS) << ']')

  def isCont(c: Char) = Character.isLetterOrDigit(c) || c == '_' || c == '-'

  lazy val signedInt: Parser[BigInt] =
    (ch('-') >> decimal).map(- _) | (ch('+') >> decimal) | decimal

  lazy val scientific: Parser[BigDecimal] = "numeric literal" |: { for {
    positive <- satisfy(c => c == '-' || c == '+').map(_ == '+') | unit(true)
    n <- decimal
    s <- (satisfy(_ == '.') >> takeWhile(_.isDigit).map(f =>
      BigDecimal(n + "." + f.mkString))) | unit(BigDecimal(n))
    sCoeff = if (positive) s else (- s)
    r <- satisfy(c => c == 'e' || c == 'E') >>
         signedInt.flatMap(x =>
           if (x > Int.MaxValue) fail[Parser](s"Exponent too large: $x")
           else unit(s * BigDecimal(10).pow(x.toInt))) | unit(sCoeff)
  } yield r }

  private def addDigit(a: BigInt, c: Char) = a * 10 + (c - 48)

  lazy val digit = "digit" |: satisfy(_.isDigit)

  lazy val decimal: Parser[BigInt] =
    digit.some.map(_.foldLeft(BigInt(0))(addDigit))

  lazy val duration: Parser[CfgValue] = "duration" |: { for {
    d <- (scientific << whitespace.skipOptional)
    x <- "time unit" |: takeWhile(_.isLetter).map(_.mkString)
    r <- Either.catchNonFatal(Duration.create(1, x)).fold(
      e => fail(e.getMessage),
      o => unit(CfgDuration(o * d.toDouble)))
  } yield r }

  /**
   * Parse a string interpolation spec. The sequence `$$` is treated as a single
   * `$` character. The sequence `$(` begins a section to be interpolated,
   * and `)` ends it.
   */
  lazy val interp: Parser[List[Interpolation]] = {
    def p(acc: List[Interpolation]): Parser[List[Interpolation]] = for {
      h <- takeWhile(_ != '$').map(x => Literal(x.mkString))
      rest = {
        def cont(x: Interpolation): Parser[List[Interpolation]] = p(x :: h :: acc)
        for {
          c <- ch('$') >> satisfy(c => c == '$' || c == '(')
          r <- if (c == '$') cont(Literal("$"))
               else (satisfy(_ != ')').some << ')').flatMap(x => cont(Interpolate(x.mkString)))
        } yield r
      }
      r <- rest | unit(h :: acc)
    } yield r
    p(Nil).map(_.reverse)
  }

  import scalaparsers.ParseState
  import scalaparsers.Supply
  import scalaparsers.Pos

  def apply(input: String, fileName: Path) =
    runParser(topLevel, input, fileName)

  def runParser[A](p: Parser[A], input: String, fileName: Path = "") =
    p.run(ParseState(
      loc = Pos.start(fileName, input),
      input = input,
      s = (),
      layoutStack = List()), Supply.create)
}


text:
<?php if (!defined('HTMLY')) die('HTMLy'); ?>

<?php echo $name;?>

        <?php echo $about; ?>

Posts by this author

        <?php if (!empty($posts)) { ?>

                <?php foreach ($posts as $p): ?>

                        <a href="<?php echo $p->url ?>"><?php echo $p->title ?> on
                        <?php echo format_date($p->date); ?> - Posted in <?php echo $p->category; ?>

                <?php endforeach; ?>

        <?php } else {
            echo 'No posts found!';
        } ?>

<?php if (!empty($posts)) { ?>
<?php if (!empty($pagination['prev']) || !empty($pagination['next'])): ?>

    <?php if (!empty($pagination['prev'])): ?>
        <a class="newer-posts" href="?page=<?php echo $page - 1 ?>"> Newer
    <?php endif; ?>
    <?php echo $pagination['pagenum'];?>
    <?php if (!empty($pagination['next'])): ?>
        <a class="older-posts" href="?page=<?php echo $page + 1 ?>">Older
    <?php endif; ?>

<?php endif; ?>
<?php } ?>


text:
package com.google.cloud.gkemulticloud.v1.samples;

// [START gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_sync]
import com.google.cloud.gkemulticloud.v1.AzureCluster;
import com.google.cloud.gkemulticloud.v1.AzureClustersClient;
import com.google.cloud.gkemulticloud.v1.ListAzureClustersRequest;
import com.google.cloud.gkemulticloud.v1.LocationName;

public class SyncListAzureClusters {

  public static void main(String[] args) throws Exception {
    syncListAzureClusters();
  }

  public static void syncListAzureClusters() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (AzureClustersClient azureClustersClient = AzureClustersClient.create()) {
      ListAzureClustersRequest request =
          ListAzureClustersRequest.newBuilder()
              .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .build();
      for (AzureCluster element : azureClustersClient.listAzureClusters(request).iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}
// [END gkemulticloud_v1_generated_AzureClusters_ListAzureClusters_sync]


text:
/*
Instructions:
(1) Wrap an XHR in a Promise in the get() function below. See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
  (a) Resolve on load and reject on error.
(2) If the XHR resolves, use addSearchHeader to add the search header to the page.
(3) If the XHR fails, console.log the error and pass 'unknown' to addSearchHeader
 */

// Inline configuration for jshint below. Prevents `gulp jshint` from failing with quiz starter code.
/* jshint unused: false */

(function(document) {
  'use strict';

  var home = null;

  /**
   * Helper function to show the search query.
   * @param {String} response - The unparsed JSON response from get.
   */
  function addSearchHeader(response) {
    try {
      response = JSON.parse(response).query;  // you'll be moving this line out of here in the next quiz!
    } catch (e) {
      // it's 'unknown', so leave it alone
    }
    home.innerHTML = '
query: ' + response + '
';
  }

  /**
   * XHR wrapped in a promise.
   * @param  {String} url - The URL to fetch.
   * @return {Promise}    - A Promise that resolves when the XHR succeeds and fails otherwise.
   */
  function get(url) {
    /*
    This code needs to get wrapped in a Promise!
     */
    return new Promise(function(resolve, reject) {
      var req = new XMLHttpRequest();
      req.open('GET', url);
      req.onload = function() {
        if (req.status === 200) {
          // It worked!
          // You'll want to resolve with the data from req.response
          resolve(req.response);
        } else {
          // It failed :(
          // Be nice and reject with req.statusText
          reject(Error(req.statusText));
        }
      };
      req.onerror = function() {
        // It failed :(
        // Pass a 'Network Error' to reject
        reject(Error("Network Error"));
      };
      req.send();
    });
  }

  window.addEventListener('WebComponentsReady', function() {
    home = document.querySelector('section[data-route="home"]');
    /*
    Uncomment the next line you're ready to start chaining and testing!
    You'll need to add a .then and a .catch. Pass the response to addSearchHeader on resolve or
    pass 'unknown' to addSearchHeader if it rejects.
     */
    get('../data/earth-like-results.json')
    .then(function(response) {
        addSearchHeader(response);
    })
    .catch(function(error) {
        addSearchHeader('unknown');
        console.log(error);
    });
  });
})(document);


text:
namespace DatabaseApi.SqlLite.Api
{
    public class SqlStringColumn : ISqlColumn
    {
        private readonly int _length;

        public SqlStringColumn(string name, int length) : this(name, length, false) { }
        public SqlStringColumn(string name, int length, bool isNullable)
        {
            Name = name;
            _length = length;
            Nullable = isNullable;
        }

        public string BuildCreateQuery()
        {
            string nullable = Nullable ? "" : "NOT NULL";
            return $"{Name} varchar({_length}) {nullable}";
        }

        public string Name { get; }
        public bool IsPrimaryKey => false;
        public bool Nullable { get; }

        public string EncapsulateValue(object value)
        {
            return $"'{value.ToString()}'";
        }

        public object ParseValue(object valueFromSql)
        {
            return valueFromSql;
        }
    }
}


text:
package org.motechproject.mtraining.service.ut.service;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.motechproject.mds.query.QueryParams;
import org.motechproject.mtraining.domain.Bookmark;
import org.motechproject.mtraining.repository.BookmarkDataService;
import org.motechproject.mtraining.service.BookmarkService;
import org.motechproject.mtraining.service.impl.BookmarkServiceImpl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;

/**
 * Unit tests for Bookmark service
 */
public class BookmarkServiceUnitTest {
    @Mock
    private BookmarkService bookmarkService;

    @Mock
    private BookmarkDataService bookmarkDataService;

    @Before
    public void setup() {
        initMocks(this);
        bookmarkService = new BookmarkServiceImpl(bookmarkDataService);
    }

    @Test
    public void getBookmarksForUser() {
        List<Bookmark> bookmarks = (List<Bookmark>) mock(List.class);
        when(bookmarkDataService.findBookmarksForUser("1313")).thenReturn(bookmarks);
        assertEquals(bookmarks, bookmarkService.getAllBookmarksForUser("1313"));
    }

    @Test
    public void getEmptyBookmarksForUser() {
        assertEquals(0, bookmarkService.getAllBookmarksForUser("12").size());
    }

    @Test
    public void getBookmarkById() {
        Bookmark bookmark = new Bookmark();
        when(bookmarkDataService.findBookmarkById(new Long(1))).thenReturn(bookmark);
        assertEquals(bookmark, bookmarkService.getBookmarkById(1));
    }

    @Test
    public void getLatestBookmarkForUser() {
        Bookmark first = new Bookmark();
        List<Bookmark> bookmarks = new ArrayList<>(Arrays.asList(first));
        when(bookmarkDataService.findBookmarksForUserParams(anyString(), any(QueryParams.class))).thenReturn(bookmarks);
        assertEquals(first, bookmarkService.getLatestBookmarkByUserId("1212"));
    }

    @Test
    public void getLatestBookmarkNullForUser() {
        List<Bookmark> bookmarks = new ArrayList<>();
        when(bookmarkDataService.findBookmarksForUserParams(anyString(), any(QueryParams.class))).thenReturn(bookmarks);
        assertEquals(null, bookmarkService.getLatestBookmarkByUserId("1212"));
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Unters. Gesammtgeb. Mykol. 4: 58 (1881)

#### Original name
Mucor mucilagineus Bref., 1881

### Remarks
null


text:
package com.javaeye.lonlysky.lforum.web.admin.forum;

import java.util.List;

import org.apache.struts2.config.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import com.javaeye.lonlysky.lforum.AdminBaseAction;
import com.javaeye.lonlysky.lforum.comm.LForumRequest;
import com.javaeye.lonlysky.lforum.entity.forum.Attachtypes;
import com.javaeye.lonlysky.lforum.entity.forum.Forumfields;
import com.javaeye.lonlysky.lforum.entity.forum.Forums;
import com.javaeye.lonlysky.lforum.entity.forum.Topics;
import com.javaeye.lonlysky.lforum.entity.forum.Usergroups;
import com.javaeye.lonlysky.lforum.entity.forum.Users;
import com.javaeye.lonlysky.lforum.service.AttachmentManager;
import com.javaeye.lonlysky.lforum.service.ForumManager;
import com.javaeye.lonlysky.lforum.service.UserGroupManager;
import com.javaeye.lonlysky.lforum.service.admin.AdminForumManager;

/**
 * 添加第一个分类页
 * 说明: 当论坛版块表中没有记录时,则会运行该页面
 *
 * @author 黄磊
 *
 */
@ParentPackage("default")
public class Forum_addfirstforumAction extends AdminBaseAction {

	private static final long serialVersionUID = 2293681661253334707L;

	private List<Usergroups> groupList;
	private List<Attachtypes> attachtypeList;
	private Forums foruminfo = new Forums();

	@Autowired
	private UserGroupManager userGroupManager;

	@Autowired
	private AttachmentManager attachmentManager;

	@Autowired
	private AdminForumManager adminForumManager;

	@Autowired
	private ForumManager forumManager;

	@Override
	public String execute() throws Exception {
		groupList = userGroupManager.getUserGroupList();
		attachtypeList = attachmentManager.getAttachmentType();
		if (LForumRequest.isPost()) { // 保存论坛信息
			if (LForumRequest.getParamValue("name").equals("")) {
				registerStartupScript("", "<script>alert('论坛名称不能为空');</script>");
				return SUCCESS;
			}
			int maxdisplayorder = forumManager.getForumsMaxDisplayOrder();
			Forums parentForum = new Forums();
			parentForum.setFid(0);
			insertForum(parentForum, 0, "0", 0, maxdisplayorder);
		}
		return SUCCESS;
	}

	/*
	 * 添加新论坛
	 */
	private void insertForum(Forums parentForum, int layer, String parentidlist, int subforumcount,
			int systemdisplayorder) {
		Forumfields forumfields = new Forumfields();
		forumfields.setApplytopictype(0);
		forumfields.setPostbytopictype(0);
		forumfields.setPermuserlist("");
		forumfields.setTopictypeprefix(0);
		forumfields.setViewbytopictype(0);
		foruminfo.setForumfields(forumfields);
		foruminfo.setForums(parentForum);
		foruminfo.setLayer(layer);
		foruminfo.setParentidlist(parentidlist);
		foruminfo.setSubforumcount(subforumcount);
		foruminfo.setName(LForumRequest.getParamValue("name"));

		foruminfo.setStatus(LForumRequest.getParamIntValue("status", 1));

		foruminfo.setDisplayorder(systemdisplayorder);

		foruminfo.setTemplateid(LForumRequest.getParamIntValue("templateid", config.getTemplateid()));
		foruminfo.setAllowsmilies(LForumRequest.getParamIntValue("Allowsmilies", 0));
		foruminfo.setAllowrss(LForumRequest.getParamIntValue("Allowrss", 0));
		foruminfo.setAllowhtml(0);
		foruminfo.setAllowbbcode(LForumRequest.getParamIntValue("Allowbbcode", 0));
		foruminfo.setAllowimgcode(LForumRequest.getParamIntValue("Allowimgcode", 0));
		foruminfo.setAllowblog(0);
		foruminfo.setIstrade(0);

		foruminfo.setAlloweditrules(0);
		foruminfo.setRecyclebin(LForumRequest.getParamIntValue("Recyclebin", 0));
		foruminfo.setModnewposts(LForumRequest.getParamIntValue("Modnewposts", 0));
		foruminfo.setJammer(LForumRequest.getParamIntValue("Jammer", 0));
		foruminfo.setDisablewatermark(LForumRequest.getParamIntValue("Disablewatermark ", 0));
		foruminfo.setInheritedmod(LForumRequest.getParamIntValue("Inheritedmod ", 0));
		foruminfo.setAllowthumbnail(LForumRequest.getParamIntValue("Allowthumbnail", 0));
		foruminfo.setAllowtag(LForumRequest.getParamIntValue("Allowtag", 0));
		int temppostspecial = 0;
		temppostspecial = LForumRequest.getParamIntValue("allowpoll", 0) == 1 ? temppostspecial | 1 : temppostspecial
				& ~1;
		temppostspecial = LForumRequest.getParamIntValue("allowbianl", 0) == 1 ? temppostspecial | 16 : temppostspecial
				& ~16;
		temppostspecial = LForumRequest.getParamIntValue("allowxuans", 0) == 1 ? temppostspecial | 4 : temppostspecial
				& ~4;
		foruminfo.setAllowpostspecial(temppostspecial);
		foruminfo.setAllowspecialonly(LForumRequest.getParamIntValue("allowspecialonly", 0));

		if (LForumRequest.getParamIntValue("autocloseoption", 0) == 0)
			foruminfo.setAutoclose(0);
		else
			foruminfo.setAutoclose(LForumRequest.getParamIntValue("autocloseday", 4));

		foruminfo.getForumfields().setDescription(LForumRequest.getParamValue("description_posttextarea"));
		foruminfo.getForumfields().setPassword(LForumRequest.getParamValue("password"));
		foruminfo.getForumfields().setIcon(LForumRequest.getParamValue("icon"));
		foruminfo.getForumfields().setPostcredits("");
		foruminfo.getForumfields().setReplycredits("");
		foruminfo.getForumfields().setRedirect(LForumRequest.getParamValue("redirect"));
		foruminfo.getForumfields().setAttachextensions(LForumRequest.getParamValues("attachextensions", ","));
		foruminfo.getForumfields().setModerators(LForumRequest.getParamValue("moderators_posttextarea"));
		foruminfo.getForumfields().setRules(LForumRequest.getParamValue("rules"));
		foruminfo.getForumfields().setTopictypes(LForumRequest.getParamValue("topictypes"));
		foruminfo.setCurtopics(0);
		foruminfo.setLastpost("1999-01-01 00:00:00");
		foruminfo.setLastposter("");
		foruminfo.setLasttitle("");
		foruminfo.setPosts(0);
		foruminfo.setTodayposts(0);
		Topics topics = new Topics();
		topics.setTid(0);
		foruminfo.setTopics(topics);
		foruminfo.setTopics_1(0);
		Users users = new Users();
		users.setUid(0);
		foruminfo.setUsers(users);
		foruminfo.setPathlist("");
		foruminfo.setColcount(1);
		foruminfo.getForumfields().setViewperm(LForumRequest.getParamValues("viewperm", ","));
		foruminfo.getForumfields().setPostperm(LForumRequest.getParamValues("postperm", ","));
		foruminfo.getForumfields().setReplyperm(LForumRequest.getParamValues("replyperm", ","));
		foruminfo.getForumfields().setGetattachperm(LForumRequest.getParamValues("getattachperm", ","));
		foruminfo.getForumfields().setPostattachperm(LForumRequest.getParamValues("postattachperm", ","));

		String result = adminForumManager.insertForumsInf(foruminfo).replace("'", "'");

		adminVistLogManager.insertLog(user, username, usergroup, grouptitle, ip, "添加论坛版块", "添加论坛版块,名称为:"
				+ foruminfo.getName());

		if (result == "")
			registerStartupScript("PAGE", "self.location.href='forum_forumstree.action';");
		else
			registerStartupScript("PAGE", "alert('用户:" + result
					+ "不存在,因为无法设为版主');self.location.href='forum_forumstree.action';");

	}

	public List<Attachtypes> getAttachtypeList() {
		return attachtypeList;
	}

	public List<Usergroups> getGroupList() {
		return groupList;
	}

}


text:
var previous = "";
$(document).ready(function() {

  // If the user refresh the page
  $(window).bind('beforeunload', function(e) {
    if (document.getElementById("language").value !== "") {
      cleanSem(document.getElementById("language").value);
    }
  });
  // If the user loads an other page
  $("a").click(function(e) {
    if (e.target.className === "ajax-link" || e.target.className === "ajax-link active-parent active") {
      if (document.getElementById("language").value !== "") {
        cleanSem(document.getElementById("language").value);
        $("#ajaxResponse").empty();
      }
    }
  });

  setupLanguage();

});

function setupLanguage() {
  $(document).find('a.indexAdminUIBreadcrumbLink').prop('href', "./index.jsp?lang=" + window.i18n.language);
  document.getElementById("topbar1").innerHTML = window.i18n.msgStore['home'];
  document.getElementById("topbar2").innerHTML = window.i18n.msgStore['adminUI-SearchEngineConfig'];
  document.getElementById("topbar3").innerHTML = window.i18n.msgStore['adminUI-Protwords'];
  document.getElementById("documentation-protwords").innerHTML = window.i18n.msgStore['documentation-protwords'];
  document.getElementById("Modify").innerHTML = window.i18n.msgStore['selectLang'];
  document.getElementById("protExplain").innerHTML = window.i18n.msgStore['protExplain'];
  $('#protwordsBox').text(window.i18n.msgStore['adminUI-Protwords']);

}

function getFile() {
  // If the language has been changed while a file has been opened
  if (previous !== "") {
    // Clean the previous semaphore
    cleanSem(previous);
  }
  // clean the response area
  $("#ajaxResponse").empty();
  // get the language
  var language = document.getElementById("language").value;
  previous = language;
  // if a language has been selected
  if (language != "") {
    var dataString = "language=" + language;
    $
        .ajax({ // Ajax request to get the content
          url : './../admin/ProtWords',
          type : 'GET',
          data : dataString,
          success : function(data, textStatus, jqXHR) {
            // If the semaphore was already acquired
            if (data === "File already in use") {
              $("#ajaxResponse").append("

");
              $("#ajaxResponse").append("
" + window.i18n.msgStore['usedFile'] + "
");
              $("#ajaxResponse").append("

");
            }
            // If the servlet catched an exception
            if (data.toString().indexOf("Error code : ") !== -1) {
              $("#ajaxResponse").append("

");
              $("#ajaxResponse").append("
" + data + "
");
              $("#ajaxResponse").append("

");
            }
            // Else print the content of the file in a textArea
            else {
              $("#ajaxResponse").append("<legend>" + window.i18n.msgStore['protwords'] + "</legend>");
              $("#ajaxResponse").append("<form class=\"col-sm-12\" id=\"res\">");
              $("#res").append("
");
              $("#div1").append("<fieldset id=\"fields\">");
              $("#fields").append("<textarea id=\"input\" required resizable=\"true\"></textarea>");
              var lines = data.split("\n"), i = 0, str = "";
              while (i < lines.length) {
                if (lines[i] != "") {
                  str = str + lines[i] + "
";
                }
                i++;
              }
              document.getElementById("input").value = str;
              $("#input").cleditor({
                width : 500, // width not including margins, borders or padding
                height : 250, // height not including margins, borders or padding
                controls : // controls to add to the toolbar
                " undo redo | cut copy paste pastetext | print source",
                useCSS : false, // use CSS to style HTML when possible (not supported in ie)
                bodyStyle : // style to assign to document body contained within the editor
                "margin:4px; font:10pt Arial,Verdana; cursor:text"
              });
              $("#fields").append("
" + window.i18n.msgStore['adminUI-ReloadWarning'] + "
");
              $("#fields")
                  .append(
                      "

Click to save and activate the modifications
<button type=\"Submit\" class=\"btn btn-primary btn-label-left\" id=\"submit\" data-loading-text=\" "
                          + window.i18n.msgStore['confirm'] + "\">" + window.i18n.msgStore['confirm'] + "</button>

");
              $("#div1").append("</fieldset>");
              $("#res").append("
");
              $("#ajaxResponse").append("</form>");
              // On submit send the value of the textArea to upload()
              $("#res").submit(function(e) {
                e.preventDefault();
              });
              $("#res").submit(function(e) {
                upload(document.getElementById("input").value);
              });
            }
          },
          error : function(jqXHR, textStatus, errorThrown) {
            console.log("Something really bad happened " + textStatus);
            $("#ajaxResponse").html(jqXHR.responseText);
          }
        });
  }
}
function upload(text) {
  $("#submit").loading("loading");
  // Get the language and the content
  var language = document.getElementById("language").value
  var content = text;
  $.ajax({ // Ajax request to rewrite the file
    url : './ProtWords',
    type : 'POST',
    // Form data
    data : {
      content : content,
      language : language
    },
    datetype : "text",
    contenttype : "text-plain/utf-8",
    success : function(data, textStatus, jqXHR) {
      if (data.toString().indexOf("Error code : ") !== -1) {
        $("#ajaxResponse").append("

");
        $("#ajaxResponse").append("
" + data + "
");
        $("#ajaxResponse").append("

");
      } else {
        $("#ajaxResponse").empty();
        $("#ajaxResponse").append(window.i18n.msgStore['modifDone']);
      }
    },
    error : function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#ajaxResponse").html(jqXHR.responseText);
    },
    complete : function(jqXHR, textStatus) {
      // allow the user to select a language
      $('#language').attr("disabled", false);
      $("#submit").loading("reset");
    }
  });
}
function cleanSem(lang) {
  var language = lang;
  if (language != "") { // If the user was editing a file
    var dataString = "language=" + language;
    $.ajax({ // Post request to release the semaphore
      url : './ProtWords',
      type : 'POST',
      data : dataString,
      async : false
    });
  }
}


text:
Node/Express app for storing expenses

The source code serves as a sample application for [Using MySQL database from Node.js ](https://www.freelancer.com/community/articles/using-mysql-database-from-node-js-guide) and [JavaScript Promises](https://www.freelancer.com/community/articles/javascript-promises-guide) articles.

###Steps to build
1. clone te repo `git clone https://github.com/gergob/jsexpense.git`
1. navigate to folder `cd jsexpense`
1. npm install
1. DEBUG=jsexpense npm start


text:
package pro.luxun.luxunanimation.view.view;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;

import com.bumptech.glide.Glide;

import android.content.Context;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;
import pro.luxun.luxunanimation.R;
import pro.luxun.luxunanimation.bean.LikeBangumi;
import pro.luxun.luxunanimation.bean.MainJson;
import pro.luxun.luxunanimation.global.MApplication;
import pro.luxun.luxunanimation.net.RetrofitClient;
import pro.luxun.luxunanimation.utils.StartUtils;
import pro.luxun.luxunanimation.utils.UserInfoHelper;
import pro.luxun.luxunanimation.utils.Utils;
import ykooze.ayaseruri.codesslib.others.ToastUtils;
import ykooze.ayaseruri.codesslib.rx.RxUtils;
import ykooze.ayaseruri.codesslib.ui.LocalDisplay;

/**
 * Created by wufeiyang on 16/5/7.
 */

@EViewGroup(R.layout.item_animation_mf)
public class MFAnimationItem extends FrameLayout{

    @ViewById(R.id.disable_mask)
    ImageView mMask;
    @ViewById(R.id.cover)
    ImageView mCover;
    @ViewById(R.id.cur)
    TextView mCur;
    @ViewById(R.id.title)
    TextView mTitle;
    @ViewById(R.id.favrite)
    CheckBox mFavrite;
    @App
    MApplication mMApplication;

    public MFAnimationItem(Context context) {
        super(context);
    }

    public MFAnimationItem(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @AfterViews
    void init(){
        int width = (LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(4)) / 3;
        setLayoutParams(new ViewGroup.LayoutParams( width, (int) (width / 3 * 4.5)));
    }

    public void bind(final MainJson.UpdatingEntity updatingEntity, String keywords){
        mCur.setText(updatingEntity.getCur());
        final String title = updatingEntity.getTitle();
        mTitle.setText(title);

        if(TextUtils.isEmpty(keywords)){
            mMask.setVisibility(GONE);
        }else {
            mMask.setVisibility(title.contains(keywords) ? GONE : VISIBLE);
        }

        Glide.with(getContext()).load(updatingEntity.getCover()).centerCrop().crossFade().into(mCover);

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                updatingEntity.setSub(mFavrite.isChecked());
                StartUtils.startAnimationDetailActivity(getContext(), updatingEntity);
            }
        });

        mFavrite.setOnCheckedChangeListener(null);
        mFavrite.setChecked(updatingEntity.isSub());

        mFavrite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {

                if(!UserInfoHelper.isLogin(getContext())){
                    Snackbar.make(getRootView(), "需要登录TAT…", Snackbar.LENGTH_LONG).setAction("登录", new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            StartUtils.startMainActivity(getContext(), 0);
                        }
                    }).show();
                    mFavrite.setChecked(!isChecked);
                    return;
                }

                RequestBody requestBody;
                if(isChecked){
                    requestBody = Utils.str2RequestBody("1");
                }else {
                    requestBody = Utils.str2RequestBody("0");
                }

                updatingEntity.setSub(isChecked);

                RetrofitClient.getApiService().subscribe(RetrofitClient.URL_BANGUMI + Utils.encodeURIComponent(title), requestBody)
                        .compose(RxUtils.<LikeBangumi>applySchedulers())
                        .subscribe(new Consumer<LikeBangumi>() {
                            @Override
                            public void accept(LikeBangumi likeBangumi) throws Exception {
                                if (TextUtils.isEmpty(likeBangumi.getType())) {
                                    mFavrite.setChecked(!isChecked);
                                }
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                ToastUtils.showTost(getContext(), ToastUtils.TOAST_ALERT, isChecked ?"订阅 " : "取消订阅 " + title + " 失败,请稍后重试");
                                mFavrite.setChecked(!isChecked);
                                updatingEntity.setSub(mFavrite.isChecked());
                            }
                        });
            }
        });
    }
}


text:
import numpy as np
import numpy.linalg as linalg
import scipy.io as sio
import time
import random
import os
import subprocess
import matplotlib
import matplotlib.image as mpimage
import matplotlib.pyplot as plt
import cv2
import sys

AVCONV_BIN = 'avconv'
TEMP_STR = "pymeshtempprefix"

#############################################################
####                  VIDEO I/O TOOLS                   #####
#############################################################

def loadCVVideo(path, pyr_level=0, show_video=False):
    #(Matt Berger wrote most of this function)
    if not os.path.exists(path):
        print "ERROR: Video path not found: %s"%path
        return None
    video_reader = cv2.VideoCapture(path)
    num_frames = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT))
    fdx = 0
    all_frames = None
    pyramid = []
    while video_reader.isOpened():
        validity,frame = video_reader.read()
        if frame == None:
            break

        #frame = cv2.pyrDown(frame)
        IDims = frame.shape
        pyr_frame = frame.copy()
        pyramid = pyr_frame.flatten()/255.0
        pyr_scale = 1.0
        for p in range(pyr_level):
            pyr_frame = cv2.pyrDown(pyr_frame)
            blurred_frame = cv2.pyrUp(cv2.pyrDown(pyr_frame))
            laplace_frame = pyr_frame - blurred_frame[:pyr_frame.shape[0],:pyr_frame.shape[1],:]
            #laplace_frame = cv2.subtract(pyr_frame,cv2.pyrUp(next_pyr_frame))
            pyr_scale*=4.0
            pyramid = np.concatenate((pyramid,(pyr_frame.flatten())/255.0))
            #pyramid = np.concatenate((pyramid,(laplace_frame.flatten())/255.0))

        # store frame
        #flattened_frame = frame.flatten()
        if all_frames == None:
            all_frames = np.zeros((len(pyramid),num_frames))
        #all_frames[:,fdx] = flattened_frame/255.0
        all_frames[:,fdx] = pyramid
        fdx=fdx+1

        # optionally show it as we load it
        if show_video:
            cv2.imshow('frame', frame)
            cv2.waitKey(1)
            #if cv2.waitKey(1) & 0xff == ord('q'):
                #break

    video_reader.release()
    if show_video:
        cv2.destroyAllWindows()

    return ((all_frames), IDims)

def saveCVVideo(V, IDims, path, show_video=True, FrameRate = 30.0, Normalize = False):
    video_writer = cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*'XVID'), FrameRate, (IDims[1],IDims[0]), True if IDims[2]==3 else False)
    if Normalize:
        V = V-np.min(V)
        V = V/np.max(V)
    for fidx in range(V.shape[1]):
        proper_frame = np.reshape(V[:,fidx], IDims)
        proper_frame = np.minimum(proper_frame,np.ones(proper_frame.shape))
        proper_frame = np.maximum(proper_frame,np.zeros(proper_frame.shape))
        proper_frame = (255*proper_frame).astype(np.uint8)
        video_writer.write(proper_frame)
        # optionally show it as we save it
        if show_video:
            cv2.imshow('frame', proper_frame)
            cv2.waitKey(1)
            #if cv2.waitKey(1) & 0xff == ord('q'):
                #break

    video_writer.release()
    if show_video:
        cv2.destroyAllWindows()

#W: Window length
def savePCsColor(PCs, W, prefix, FrameRate = 30):
    NPCs = PCs.shape[1]/W
    for i in range(NPCs):
        print "Outputting principal component %i of %i"%(i, NPCs)
        saveCVVideo(PCs[:, i*W:(i+1)*W], IDims, "%s%i.avi"%(prefix, i), FrameRate = FrameRate, Normalize = True)

#############################################################
####           TIME DELAY EMBEDDING TOOLS               #####
#############################################################
#Input: I: P x N Video with frames along the columns
#W: Windows
#Ouput: Mu: P x W video with mean frames along the columns
def tde_mean(I, W):
    IOut = np.array(I)
    IOut[IOut > 1] = 1
    IOut[IOut < 0] = 0
    start_time = time.time()
    N = I.shape[1]
    P = I.shape[0]
    Mu = np.zeros((P, W))
    for i in range(W):
        Mu[:, i] = np.mean(I[:, np.arange(N-W+1) + i], 1)
    end_time = time.time()
    #print "tde_mean elapsed time ", end_time-start_time, " seconds, I.shape = ", I.shape, ", W = ", W
    return Mu

#Frames assumed to be in each column
#Stacked frames are also in one column
#The delay frames are in a matrix I call "ID" which is never explicitly
#stored
#Return a tuple of (right hand singular vectors, singular values)
def tde_rightsvd(I, W, Mu):
    start_time = time.time()
    N = I.shape[1] #Number of frames in the video

    ## Step 1: Precompute frame and mean correlations
    B = I.T.dot(I);
    MuFlat = Mu.flatten()
    MuFlat = np.reshape(MuFlat, [len(MuFlat), 1])
    MuTMu = MuFlat.T.dot(MuFlat)
    C = Mu.T.dot(I) #A WxN matrix

    ## Step 2: Use precomputed information to compute (ID-Mu)^T*(ID-Mu)
    #Compute the ID^TID part
    ND = N-W+1
    IDTID = np.zeros((ND, ND))
    #Use the fact that a delay embedding is just a moving average along
    #all diagonals
    for i in range(N-W+1):
        b = np.diag(B, i)
        b2 = np.cumsum(b)
        bend = b2[W-1:]
        bbegin = np.zeros(len(bend))
        bbegin[1:] = b2[0:len(bend)-1]
        b2 = bend - bbegin
        IDTID[np.arange(len(b2)), i + np.arange(len(b2))] = b2
    IDTID = IDTID + IDTID.T
    np.fill_diagonal(IDTID, 0.5*np.diag(IDTID)) #Main diagonal was counted twice

    #Compute the Mu^TID part to subtract off mean
    MuTID = np.zeros((1, ND))
    for i in range(ND):
        MuTID[0, i] = np.sum(np.diag(C, i))
    ATA = IDTID - MuTID
    ATA = ATA - MuTID.T
    ATA = ATA + MuTMu
    #Handle numerical precision issues and keep it symmetric
    ATA = 0.5*(ATA + ATA.T)

    ## Step 3: Compute right singular vectors
    [S, Y] = linalg.eigh(ATA)
    idx = np.argsort(-S)
    S[S < 0] = 0 #Numerical precision
    S = np.sqrt(S[idx])
    Y = Y[:, idx]
    end_time = time.time()
    return (Y, S)

#Unpack the principal components
#I: Video frames PxN (each frame of P dimensions in each column)
#W: Sliding Window size
#Mu: Mean sliding window (PxW)
#Y: Right singular vectors (in columns)
#NPCs: The number of principal components to return
#Return a P x (W*NPCs) matrix of principal components
def tde_getPCs(I, W, Mu, Y, NPCs):
    N = I.shape[1]
    P = I.shape[0]
    M = N-W+1
    IRet = np.zeros((P, W*NPCs))
    YSub = Y[:, 0:NPCs]
    for k in range(W):
        idx = np.arange(k, k+M)
        #Fill in the kth frame of each principal component
        IRet[:, k + W*np.arange(NPCs)] = (I[:, idx] - np.reshape(Mu[:, k], [Mu.shape[0], 1])).dot(YSub)
    return IRet

#I: Video frames PxN (each frame of P dimensions in each column)
#A: Dimensionality of subspace
#Returns: Tuple: (subspace, subspace coordinates)
def tde_tosubspace(I, A, lam = 0):
    #(Matt Berger wrote part of this function)
    N = I.shape[1]
    P = I.shape[0]
    s_dim = A

    I_mean = (1.0/N)*I.dot(np.ones(N))
    I_centered = I - np.asarray([I_mean]*N).T
    # first, compute subspace for I, and corresponding subspace representations
    print 'forming input covariance matrix: ',
    start_time = time.time()
    input_covariance = I_centered.T.dot(I_centered)
    end_time = time.time()
    print end_time-start_time, " seconds"

    print 'computing data subspace: ',
    start_time = time.time()
    [data_eigenvalues, data_eigenvectors] = linalg.eigh(input_covariance)
    print 'input eigenvalues:',data_eigenvalues
    end_time = time.time()
    print end_time-start_time, " seconds"

    max_s_dim = N
    for idx,eigenvalue in enumerate(data_eigenvalues):
        if eigenvalue > 1e-12:
            break
        max_s_dim=max_s_dim-1
    if max_s_dim < A:
        s_dim = max_s_dim
        print 'subspace of dimensionality:',s_dim,'NOT',A
    data_subspace = I_centered.dot(data_eigenvectors[0:N,-s_dim:])
    data_subspace = data_subspace/np.sqrt(np.sum(data_subspace**2, 0))
    #print 'data eigenvalues:',data_eigenvalues

    if lam > 0:
        import prox_tv as ptv
        #Perform total variation denoising on the subspace columns
        #TODO: This is no longer an orthogonal subspace
        for i in range(data_subspace.shape[1]-A, data_subspace.shape[1]):
            print "Doing i = %i"%i
            v = np.reshape(data_subspace[:, i], IDims)
            vnew = np.zeros(v.shape)
            for k in range(3):
                vnew[:, :, k] = ptv.tv1_2d(v[:, :, k], lam)

            plt.subplot(121)
            v = np.reshape(data_subspace[:, i], IDims)
            plt.imshow(v/np.max(v))
            plt.title("Component %i"%i)
            plt.subplot(122)
            plt.imshow(vnew/np.max(vnew))
            plt.savefig("TV%i.png"%i, dpi=200)

            data_subspace[:, i] = vnew.flatten()

    # project data
    print 'projecting data...'
    s_I = data_subspace.T.dot(I_centered)
    return (data_subspace, s_I)

#Output principal components of a video
if __name__ == '__main__':
    (I, IDims) = loadCVVideo('BeatingHeartSynthetic/heartcrop.avi')
    NPCs = 20
    W = 30
    (data_subspace, s_I) = tde_tosubspace(I, I.shape[1])
    # perform amplification of the reduced representation
    s_I_mean = tde_mean(s_I,W)
    (s_I_PCs,s_eigenvalues) = tde_rightsvd(s_I,W,s_I_mean)
    PCs = tde_getPCs(s_I, W, s_I_mean, s_I_PCs, NPCs)
    PCs = data_subspace.dot(PCs)
    savePCsColor(PCs, W, "BeatingHeartCrop")