text:
namespace mojo {

namespace system {
namespace internal {

bool ShutdownCheckNoLeaks(Core* core_impl) {
  // No point in taking the lock.
  const HandleTable::HandleToEntryMap& handle_to_entry_map =
      core_impl->handle_table_.handle_to_entry_map_;

  if (handle_to_entry_map.empty())
    return true;

  for (HandleTable::HandleToEntryMap::const_iterator it =
           handle_to_entry_map.begin();
       it != handle_to_entry_map.end();
       ++it) {
    LOG(ERROR) << "Mojo embedder shutdown: Leaking handle " << (*it).first;
  }
  return false;
}

}  // namespace internal
}  // namespace system

namespace embedder {
namespace test {

bool Shutdown() {
  system::Core* core = system::entrypoints::GetCore();
  CHECK(core);
  system::entrypoints::SetCore(NULL);

  bool rv = system::internal::ShutdownCheckNoLeaks(core);
  delete core;
  return rv;
}

}  // namespace test
}  // namespace embedder

}  // namespace mojo


text:
import { newE2EPage } from '@stencil/core/testing';

import { closeItemSliding, openItemSliding } from '../test.utils';

test('item-sliding: standalone', async () => {
  const page = await newE2EPage({
    url: '/src/components/item-sliding/test/standalone?ionic:_testing=true'
  });

  const compares = [];
  compares.push(await page.compareScreenshot());

  // Pass sliding item with start icons in option
  await openItemSliding('#startItem', page);
  compares.push(await page.compareScreenshot(`start icons open`));
  await closeItemSliding(page);

  // Pass sliding item with top icons in option
  await openItemSliding('#topItem', page);
  compares.push(await page.compareScreenshot(`top icons open`));
  await closeItemSliding(page);

  // Pass sliding item with anchor option
  await openItemSliding('#anchorItem', page);
  compares.push(await page.compareScreenshot(`anchor option`));
  await closeItemSliding(page);

  for (const compare of compares) {
    expect(compare).toMatchScreenshot();
  }
});

test('item-sliding:rtl: standalone', async () => {
  const page = await newE2EPage({
    url: '/src/components/item-sliding/test/standalone?ionic:_testing=true&rtl=true'
  });

  const compares = [];
  compares.push(await page.compareScreenshot());

  // Pass sliding item with start icons in option
  await openItemSliding('#startItem', page, true);
  compares.push(await page.compareScreenshot(`start icons open`));
  await closeItemSliding(page);

  // Pass sliding item with top icons in option
  await openItemSliding('#topItem', page, true);
  compares.push(await page.compareScreenshot(`top icons open`));
  await closeItemSliding(page);

  // Pass sliding item with anchor option
  await openItemSliding('#anchorItem', page, true);
  compares.push(await page.compareScreenshot(`anchor option`));
  await closeItemSliding(page);

  for (const compare of compares) {
    expect(compare).toMatchScreenshot();
  }
});

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * TOP API: taobao.userrecommend.items.get request
 *
 * @author auto create
 * @since 1.0, 2013-03-23 12:41:17
 */
class UserrecommendItemsGetRequest
{
	/**
	 * 请求个数,建议取20个
	 **/
	private $count;

	/**
	 * 额外参数
	 **/
	private $ext;

	/**
	 * 请求类型,1:用户购买意图。其他值当非法值处理
	 **/
	private $recommendType;

	private $apiParas = array();

	public function setCount($count)
	{
		$this->count = $count;
		$this->apiParas["count"] = $count;
	}

	public function getCount()
	{
		return $this->count;
	}

	public function setExt($ext)
	{
		$this->ext = $ext;
		$this->apiParas["ext"] = $ext;
	}

	public function getExt()
	{
		return $this->ext;
	}

	public function setRecommendType($recommendType)
	{
		$this->recommendType = $recommendType;
		$this->apiParas["recommend_type"] = $recommendType;
	}

	public function getRecommendType()
	{
		return $this->recommendType;
	}

	public function getApiMethodName()
	{
		return "taobao.userrecommend.items.get";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function check()
	{

		RequestCheckUtil::checkNotNull($this->count,"count");
		RequestCheckUtil::checkNotNull($this->recommendType,"recommendType");
	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
extern "C" {
// clang-format off
#include "third_party/libjpeg-turbo/jpeglib.h"
#include "third_party/libjpeg-turbo/jpegint.h"
// clang-format on
}

namespace starboard {
namespace shared {
namespace libjpeg {

namespace {

JDIMENSION kInvalidHeight = 0xFFFFFF;

void ErrorManagerExit(j_common_ptr common_ptr) {
  // Returns the control to the setjmp point. The buffer which is filled by a
  // previous call to setjmp that contains information to store the environment
  // to that point.
  jmp_buf* buffer = static_cast<jmp_buf*>(common_ptr->client_data);
  longjmp(*buffer, 1);
}

void SourceManagerInitSource(j_decompress_ptr decompress_ptr) {
  // no-op.
}

boolean SourceManagerFillInputBuffer(j_decompress_ptr decompress_ptr) {
  // Normally, this function is called when we need to read more of the encoded
  // buffer into memory and a return false indicates that we have no data to
  // supply yet, but in our case, the encoded buffer is always in memory, so
  // this should never get called unless there is an error, in which case we
  // return false to indicate that.
  return false;
}

boolean SourceManagerResyncToRestart(j_decompress_ptr decompress_ptr,
                                     int desired) {
  return false;
}

void SourceManagerTermSource(j_decompress_ptr decompress_ptr) {
  // no-op.
}

void SourceManagerSkipInputData(j_decompress_ptr decompress_ptr,
                                long num_bytes) {  // NOLINT(runtime/int)
  // Since all our data that is required to be decoded should be in the buffer
  // already, trying to skip beyond it means that there is some kind of error or
  // corrupt input data. We acknowledge these error cases by setting
  // |bytes_in_buffer| to 0 which will result in a call to
  // SourceManagerFillInputBuffer() which will return false to indicate that an
  // error has occurred.
  size_t bytes_to_skip = std::min(decompress_ptr->src->bytes_in_buffer,
                                  static_cast<size_t>(num_bytes));
  decompress_ptr->src->bytes_in_buffer -= bytes_to_skip;
  decompress_ptr->src->next_input_byte += bytes_to_skip;
}

bool ReadHeader(jpeg_decompress_struct* info) {
  if (jpeg_read_header(info, true) != JPEG_HEADER_OK) {
    return false;
  }

  return true;
}

bool StartDecompress(jpeg_decompress_struct* info) {
  // jpeg_has_multiple_scans() returns TRUE if the incoming image file has more
  // than one scan.
  info->buffered_image = jpeg_has_multiple_scans(info);

  // TODO: switch libjpeg version to support JCS_RGBA_8888 output.
  info->out_color_space = JCS_RGB;

  // Compute output image dimensions
  jpeg_calc_output_dimensions(info);

  if (!jpeg_start_decompress(info)) {
    SB_LOG(WARNING) << "Start decompressor failed.";
    return false;
  }

  return true;
}

// Responsible for swizzeling and alpha-premultiplying a row of pixels.
template <int r, int g, int b, int a>
void FillRow(int width, uint8_t* dest, JSAMPLE* source) {
  for (int x = 0; x < width; ++x, source += 3, dest += 4) {
    dest[r] = source[0];
    dest[g] = source[1];
    dest[b] = source[2];
    dest[a] = 0xFF;
  }
}

bool ReadLines(jpeg_decompress_struct* info,
               SbDecodeTargetFormat decode_target_format,
               uint8_t* image_data) {
  // Creation of 2-D sample arrays which is for one row.
  // See the comments in jmemmgr.c.
  JSAMPARRAY buffer = (*info->mem->alloc_sarray)(
      (j_common_ptr)info, JPOOL_IMAGE, info->output_width * 4, 1);

  while (info->output_scanline < info->output_height) {
    // |info->output_scanline| would be increased 1 after reading one row.
    int row_index = static_cast<int>(info->output_scanline);

    // jpeg_read_scanlines() returns up to the maximum number of scanlines of
    // decompressed image data. This may be less than the number requested in
    // cases such as bottom of image, data source suspension, and operating
    // modes that emit multiple scanlines at a time. Image data should be
    // returned in top-to-bottom scanline order.
    // TODO: Investigate the performance improvements by processing
    // multiple pixel rows. It may have performance advantage to use values
    // larger than 1. For example, JPEG images often use 4:2:0 downsampling, and
    // in that case libjpeg needs to make an additional copy of half the image
    // pixels(see merged_2v_upsample()).
    if (jpeg_read_scanlines(info, buffer, 1) != 1) {
      return false;
    }

    // Write the decoded row pixels to image data.
    uint8_t* pixel_data = image_data + info->image_width * 4 * row_index;

    JSAMPLE* sample_buffer = *buffer;
    switch (decode_target_format) {
      case kSbDecodeTargetFormat1PlaneRGBA:
        FillRow<0, 1, 2, 3>(static_cast<int>(info->image_width), pixel_data,
                            sample_buffer);
        break;
      case kSbDecodeTargetFormat1PlaneBGRA:
        FillRow<2, 1, 0, 3>(static_cast<int>(info->image_width), pixel_data,
                            sample_buffer);
        break;
      // All the other decode formats are not supported.
      case kSbDecodeTargetFormat2PlaneYUVNV12:
      case kSbDecodeTargetFormat3PlaneYUVI420:
      case kSbDecodeTargetFormat3Plane10BitYUVI420:
#if SB_API_VERSION >= 14
      case kSbDecodeTargetFormat3Plane10BitYUVI420Compact:
#endif  // SB_API_VERSION >= 14
      case kSbDecodeTargetFormat1PlaneUYVY:
      case kSbDecodeTargetFormatInvalid:
        SB_NOTREACHED();
        break;
    }
  }

  return true;
}

// A baseline sequential JPEG is stored as one top-to-bottom scan of the image.
// Progressive JPEG divides the file into a series of scans. It is starting with
// a very low quality image, and then following scans gradually improve the
// quality.
// TODO: support displaying the low resolution image while decoding
// the progressive JPEG.
bool DecodeProgressiveJPEG(jpeg_decompress_struct* info,
                           SbDecodeTargetFormat decode_target_format,
                           uint8_t* image_data) {
  int status;
  do {
    // |jpeg_consume_input| decodes the input data as it arrives.
    status = jpeg_consume_input(info);
  } while (status == JPEG_REACHED_SOS || status == JPEG_ROW_COMPLETED ||
           status == JPEG_SCAN_COMPLETED);

  while (info->output_scanline == kInvalidHeight ||
         info->output_scanline <= info->output_height) {
    if (info->output_scanline == 0) {
      // Initialize for an output pass in buffered-image mode.
      // The |input_scan_number| indicates the scan of the image to be
      // processed.
      if (!jpeg_start_output(info, info->input_scan_number)) {
        // Decompression is suspended.
        return false;
      }
    }

    if (info->output_scanline == kInvalidHeight) {
      // Recover from the previous set flag.
      info->output_scanline = 0;
    }

    if (!ReadLines(info, decode_target_format, image_data)) {
      if (info->output_scanline == 0) {
        // Data is not enough for one line scan, so flag the |output_scanline|
        // to make sure that we don't call |jpeg_start_output| multiple times
        // for the same scan.
        info->output_scanline = kInvalidHeight;
      }
      return false;
    }

    if (info->output_scanline == info->output_height) {
      // Finish up after an output pass in buffered-image mode.
      if (!jpeg_finish_output(info)) {
        // Decompression is suspended due to
        // input_scan_number <= output_scan_number and EOI is not reached.
        // The suspension will be recovered when more data are coming.
        return false;
      }

      // The output scan number is the notional scan being processed by the
      // output side. The decompressor will not allow output scan number to get
      // ahead of input scan number.
      SB_DCHECK(info->input_scan_number >= info->output_scan_number);
      // This scan pass is done, so reset the output scanline.
      info->output_scanline = 0;
      if (info->input_scan_number == info->output_scan_number) {
        // No more scan needed at this point.
        break;
      }
    }
  }

  // |jpeg_input_complete| tests for the end of image.
  if (!jpeg_input_complete(info)) {
    return false;
  }

  return true;
}

}  // namespace

SbDecodeTarget Decode(SbDecodeTargetGraphicsContextProvider* context_provider,
                      SbDecodeTargetFormat decode_target_format,
                      const uint8_t* data,
                      size_t input_byte) {
  jpeg_decompress_struct info = {};
  jpeg_source_mgr source_manager = {};
  jpeg_error_mgr error_manager = {};

  info.err = jpeg_std_error(&error_manager);
  error_manager.error_exit = &ErrorManagerExit;

  // Allocate and initialize JPEG decompression object.
  jpeg_create_decompress(&info);

  info.src = &source_manager;

  // Set up callback functions.
  // Even some of them are no-op, we have to set them up for jpeg lib.
  source_manager.init_source = SourceManagerInitSource;
  source_manager.fill_input_buffer = SourceManagerFillInputBuffer;
  source_manager.skip_input_data = SourceManagerSkipInputData;
  source_manager.resync_to_restart = SourceManagerResyncToRestart;
  source_manager.term_source = SourceManagerTermSource;

  // |client_data| is available for use by application.
  jmp_buf jump_buffer;
  info.client_data = &jump_buffer;

  // int setjmp(jmp_buf env) saves the current environment (this program state),
  // at some point of program execution, into a platform-specific data
  // structure (jmp_buf) that can be used at some later point of program
  // execution by longjmp to restore the program state to that saved by setjmp
  // into jmp_buf. This process can be imagined to be a "jump" back to the point
  // of program execution where setjmp saved the environment. The return value
  // from setjmp indicates whether control reached that point normally or from a
  // call to longjmp. If the return is from a direct invocation, setjmp returns
  // 0. If the return is from a call to longjmp, setjmp returns a nonzero value.
  // warning C4611: interaction between '_setjmp' and C++ object destruction is
  // non-portable.
  if (setjmp(jump_buffer)) {
    // image data is empty.
    SB_DLOG(WARNING) << "Decoder encounters an error.";
    return kSbDecodeTargetInvalid;
  }

  // Next byte to read from buffer.
  info.src->next_input_byte = reinterpret_cast<const JOCTET*>(data);
  // Number of bytes remaining in buffer.
  info.src->bytes_in_buffer = input_byte;

  if (!ReadHeader(&info)) {
    // Data is not enough for decoding the header.
    return kSbDecodeTargetInvalid;
  }

  if (!StartDecompress(&info)) {
    return kSbDecodeTargetInvalid;
  }

  std::vector<uint8_t> decoded_data(info.image_width * info.image_height * 4);

  if (info.buffered_image) {  // Progressive JPEG.
    if (!DecodeProgressiveJPEG(&info, decode_target_format,
                               decoded_data.data())) {
      return kSbDecodeTargetInvalid;
    }
  } else if (!ReadLines(&info, decode_target_format,
                        decoded_data.data())) {  // Baseline sequential JPEG.
    return kSbDecodeTargetInvalid;
  }

  if (!jpeg_finish_decompress(&info)) {
    // In this case, we did read all the rows, so we don't really have to
    // treat this as an error.
    SB_DLOG(WARNING) << "Data source requests suspension of the decompressor.";
  }

  auto width = info.image_width;
  auto height = info.image_height;
  jpeg_destroy_decompress(&info);

  return DecodeTargetCreate(context_provider, decoded_data.data(), width,
                            height, decode_target_format);
}

}  // namespace libjpeg
}  // namespace shared
}  // namespace starboard


text:
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="com.distimo.sdk.cordova"
    version="0.0">

    <name>Distimo SDK</name>

    <description>

This is the official plugin for the Distimo SDK in Apache Cordova/PhoneGap.

The DistimoSDK plugin for Apache Cordova allows you to use Distimo Conversion Tracking
      in combination with your apps created with Apache PhoneGap/Cordova. For more information, visit
      http://www.distimo.com/conversion-tracking.

    </description>

    <license>Apache 2.0</license>

    <js-module src="js/distimosdk.js" name="DistimoSDK">
        <clobbers target="window.plugins.distimo" />
    </js-module>

    <engines>
      <engine name="cordova" version=">=3.4.0" />
    </engines>

    <platform name="android">

        <config-file target="config.xml" parent="/*">
            <feature name="DistimoSDK">
                <param name="android-package" value="com.distimo.sdk.cordova.CDVDistimoSDK"/>
            </feature>
        </config-file>

        <source-file src="src/android/CDVDistimoSDK.java" target-dir="src/com/distimo/sdk/cordova" />

        <source-file src="src/android/EventManager.java" target-dir="src/com/distimo/sdk" />
        <source-file src="src/android/Utils.java" target-dir="src/com/distimo/sdk" />
        <source-file src="src/android/OldBase64.java" target-dir="src/com/distimo/sdk" />
        <source-file src="src/android/DistimoExceptionHandler.java" target-dir="src/com/distimo/sdk" />
        <source-file src="src/android/InstallReferrerReceiver.java" target-dir="src/com/distimo/sdk" />
        <source-file src="src/android/AppLinkManager.java" target-dir="src/com/distimo/sdk" />
        <source-file src="src/android/DistimoSDK.java" target-dir="src/com/distimo/sdk" />

        <config-file target="AndroidManifest.xml" parent="/manifest">
            <uses-permission android:name="android.permission.INTERNET" />
        </config-file>

        <config-file target="AndroidManifest.xml" parent="/manifest/application">
            <receiver android:name="com.distimo.sdk.InstallReferrerReceiver" android:exported="true">
                <intent-filter>
                    <action android:name="com.android.vending.INSTALL_REFERRER" />
                </intent-filter>
            </receiver>
        </config-file>

    </platform>

    <platform name="ios">

        <config-file target="config.xml" parent="/*">
            <feature name="DistimoSDK">
                <param name="ios-package" value="CDVDistimoSDK"/>
            </feature>
        </config-file>

        <source-file src="src/ios/CDVDistimoSDK.m" compiler-flags="-fno-objc-arc" />

        <source-file src="src/ios/DistimoSDK.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKApplicationManager.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKAppLinkManager.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKEvent.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKEventLogger.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKIDManager.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKNSDataTools.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKNSStringTools.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKPasteboardManager.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKSettingsManager.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKEventManager.m" compiler-flags="-fno-objc-arc" />
        <source-file src="src/ios/DMSDKUIDeviceTools.m" compiler-flags="-fno-objc-arc" />

        <framework src="Security.framework" />

    </platform>

</plugin>


text:
package org.cat.eye.engine.common.service;

import java.lang.reflect.Parameter;

public interface BundleService {

    Object getArgument(Parameter parameter, String domain) throws Exception;

    void setArgument(Parameter parameter, String domain, Object argument) throws Exception;

    void storeArguments(Object[] args, String domain) throws Exception;

}


text:
package org.xnio.nio.test;

import static org.junit.Assert.assertNotNull;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.StreamConnection;
import org.xnio.Xnio;
import org.xnio.XnioWorker;
import org.xnio.channels.AcceptingChannel;
import org.xnio.channels.ConnectedStreamChannel;

/**
 * Test case for scenarios where an attempt to perform an illegal connection is made.
 *
 * @author Flavia Rainone
 *
 */
@SuppressWarnings("deprecation")
public class IllegalConnectionTestCase {

    private static SocketAddress bindAddress;
    private static XnioWorker worker;

    @BeforeClass
    public static void createWorker() throws IOException {
        final Xnio xnio = Xnio.getInstance("nio", IllegalConnectionTestCase.class.getClassLoader());
        worker = xnio.createWorker(OptionMap.create(Options.WORKER_WRITE_THREADS, 3, Options.WORKER_READ_THREADS, 4));
        bindAddress = new InetSocketAddress(Inet4Address.getByAddress(new byte[] { 127, 0, 0, 1 }), 12345);
    }

    @AfterClass
    public static void destroyWorker() throws InterruptedException {
        worker.shutdown();
        worker.awaitTermination(1L, TimeUnit.MINUTES);
    }

    @Test
    @Ignore
    public void illegalAcceptThreads() throws IOException {
        IllegalArgumentException expected;

        final Xnio xnio = Xnio.getInstance("nio", getClass().getClassLoader());
        final XnioWorker zeroThreadWorker = xnio.createWorker(OptionMap.create(Options.WORKER_IO_THREADS, 0));

        expected = null;
        try {
            zeroThreadWorker.createStreamConnectionServer(bindAddress, null, OptionMap.create(Options.WORKER_ESTABLISH_WRITING, true));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            zeroThreadWorker.createStreamConnectionServer(bindAddress, null, OptionMap.create(Options.WORKER_ESTABLISH_WRITING, false));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            zeroThreadWorker.createStreamServer(bindAddress, null, OptionMap.create(Options.WORKER_ESTABLISH_WRITING, true));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            zeroThreadWorker.createStreamServer(bindAddress, null, OptionMap.create(Options.WORKER_ESTABLISH_WRITING, false));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);
    }

    @Test
    public void illegalReceiveBufferSize() throws IOException {
        IllegalArgumentException expected = null;
        try {
            worker.createStreamConnectionServer(bindAddress, null, OptionMap.create(Options.RECEIVE_BUFFER, 0));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            worker.createStreamConnectionServer(bindAddress, null, OptionMap.create(Options.RECEIVE_BUFFER, -1));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            worker.createStreamServer(bindAddress, null, OptionMap.create(Options.RECEIVE_BUFFER, 0));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            worker.createStreamServer(bindAddress, null, OptionMap.create(Options.RECEIVE_BUFFER, -1));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);
    }

    @Test
    public void illegalLowWaterMark() throws IOException {
        IllegalArgumentException expected = null;
        try {
            worker.createStreamConnectionServer(bindAddress, null, OptionMap.create(Options.CONNECTION_HIGH_WATER, 2, Options.CONNECTION_LOW_WATER, 3));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            worker.createStreamConnectionServer(bindAddress, null, OptionMap.create(Options.CONNECTION_LOW_WATER, -1));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            worker.createStreamServer(bindAddress, null, OptionMap.create(Options.CONNECTION_HIGH_WATER, 2, Options.CONNECTION_LOW_WATER, 3));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            worker.createStreamServer(bindAddress, null, OptionMap.create(Options.CONNECTION_LOW_WATER, -1));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);
    }

    @Test
    public void illegalHighWaterMark() throws IOException {
        IllegalArgumentException expected = null;
        try {
            worker.createStreamConnectionServer(bindAddress, null, OptionMap.create(Options.CONNECTION_HIGH_WATER, -1));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            worker.createStreamServer(bindAddress, null, OptionMap.create(Options.CONNECTION_HIGH_WATER, -1));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);
    }

    @Test
    public void illegalSendBufferSize() throws IOException {
        IllegalArgumentException expected = null;
        try {
           worker.createStreamConnectionServer(bindAddress, null, OptionMap.create(Options.SEND_BUFFER, 0));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            worker.createStreamConnectionServer(bindAddress, null, OptionMap.create(Options.SEND_BUFFER, -2));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        final AcceptingChannel<? extends StreamConnection> server = worker.createStreamConnectionServer(bindAddress, null,
                OptionMap.EMPTY);
        expected = null;
        try {
            server.setOption(Options.SEND_BUFFER, 0);
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        server.close();
        assertNotNull(expected);

        expected = null;
        try {
            server.setOption(Options.SEND_BUFFER, -5);
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        server.close();
        assertNotNull(expected);

        expected = null;
        try {
           worker.createStreamServer(bindAddress, null, OptionMap.create(Options.SEND_BUFFER, 0));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        expected = null;
        try {
            worker.createStreamServer(bindAddress, null, OptionMap.create(Options.SEND_BUFFER, -2));
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        assertNotNull(expected);

        final AcceptingChannel<? extends ConnectedStreamChannel> serverChannel = worker.createStreamServer(bindAddress, null,
                OptionMap.EMPTY);
        expected = null;
        try {
            serverChannel.setOption(Options.SEND_BUFFER, 0);
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        serverChannel.close();
        assertNotNull(expected);

        expected = null;
        try {
            serverChannel.setOption(Options.SEND_BUFFER, -5);
        } catch (IllegalArgumentException e) {
            expected = e;
        }
        serverChannel.close();
        assertNotNull(expected);
    }

}


text:
local clib = {}
local event = require("libs.event")
local msgpack = require("msgpack")

----
--- client Helpers
----

-- Get stored data
function clib.getclient(id) -- get client assigned to id
	local client = msgpack.unpack(kvstore._get("circd:client:"..id))
	client.sock = clib.getsock(id)
	return client
end
function clib.getsock(id) -- get client assigned to id
	return kvstore._get("circd:client:sock:"..id)
end
function clib.isconnected(id) -- get connection status
	return kvstore._get("circd:client:connected:"..id)
end
function clib.getnick(id) -- get nick
	return kvstore._get("circd:client:nick:"..id)
end
function clib.getuser(id) -- get username
	return kvstore._get("circd:client:username:"..id)
end
function clib.getreal(id) -- set realname
	return kvstore._get("circd:client:realname:"..id)
end
function clib.gethost(id) -- get hostmask
	return kvstore._get("circd:client:hostmask:"..id)
end

-- Set stored data
function clib.setclient(id, client, nosock) -- set client behind id
	if not nosock then
		clib.setsock(id, client.sock)
	end
	kvstore._set("circd:client:"..id, msgpack.pack(client))
end
function clib.setsock(id, sock) -- set client behind id
	kvstore._set("circd:client:sock:"..id, sock)
end

function clib.setid(nick, id) -- set id assigned to nick
	kvstore._set("circd:client:id:"..nick, id)
end
function clib.setconnected(id, connected) -- set connection status
	kvstore._set("circd:client:connected:"..id, connected)
end
function clib.setnick(id, nick) -- setnickname
	kvstore._set("circd:client:nick:"..id, nick)
end
function clib.setuser(id, user) -- set username
	kvstore._set("circd:client:username:"..id, user)
end
function clib.setreal(id, real) -- set realname
	kvstore._set("circd:client:realname:"..id, real)
end
function clib.sethost(id, host) -- set hostmask
	kvstore._set("circd:client:hostmask:"..id, host)
end

-- disconnect
function clib.deleteuser(id, nick) -- delete user data, when disconnected and such
	if not nick then
		nick = clib.getnick(id)
	end
	kvstore.del("circd:client:nick:"..id)
	kvstore.del("circd:client:username:"..id)
	kvstore.del("circd:client:realname:"..id)
	kvstore.del("circd:client:hostmask:"..id)
	kvstore.del("circd:client:connected:"..id)
	if nick then
		kvstore.del("circd:client:id:"..nick)
	end
end

----
--- Checks
----

function clib.nick_used(nick) -- check if nick is used
	return kvstore.get("circd:client:id:"..nick) ~= nil
end
function clib.is_command(cmd)
	return kvstore._get("circd:command:is_registered:"..cmd) == true
end

----
--- Send
----

function clib.send(client, msg) -- send message to client
	net.write(client.sock, msg.."\r\n")
end
function clib.srvmsg(client, code, ...) -- server message, encoding it properly
	local id
	if type(client) == "table" then
		id = client.id
	else
		id = client
	end

	if not code then
		error("No code given!")
	end

	local p = {...}
	if (p[#p] or ""):match("%s") then
		p[#p] = ":"..p[#p]:gsub("^:?", "")
	end

	if type(code) == "number" then
		code = tostring(code)
		code = ("0"):rep(math.max(0,3-#code))..code
	end

	net.write(client.sock or clib.getsock(id), ":"..(kvstore.get("circd:servername") or "circd").." "..code.." "..table.concat(p, " ").."\r\n")
end

----
--- chan Helpers
----

-- basics, join, part and send*
function clib.join_chan(id, chan) -- join channel
	event.fire("circd:chan", "join", id, chan)
end
function clib.part_chan(id, chan, reason) -- leave channel
	event.fire("circd:chan", "part", id, chan, reason)
end
function clib.send_chan(id, chan, msg, to_sender) -- send msg to every user of the channel
	print("send_chan to "..chan)
	local id_excluded
	if not to_sender then
		id_excluded = id
	end
	event.fire("circd:chan", "send", id_excluded, chan, msg)
end
function clib.send_all_with_user(id, msg, to_sender)
	local chans = clib.get_channels(id)
	for _, chan in pairs(chans) do
		clib.send_chan(id, chan, msg, to_sender)
	end
end

-- checks
function clib.channel_exists(chan)
	return kvstore._get("circd:chan:exists:"..chan) == true
end
function clib.list_users(chan) -- get users of channel
	local c = com.create()
	event.fire("circd:chan", "getusers", nil, chan, c)
	local res = com.receive(c)
	com.close(c)
	return msgpack.unpack(res)
end
function clib.get_channels(id) -- get list of channels user is in
	local c = com.create()
	event.fire("circd:chan", "getchannels", id, nil, c)
	local res = com.receive(c)
	com.close(c)
	local users = msgpack.unpack(res)
	print("users for "..id)
	for k, v in pairs(users) do
		print(k..": "..v)
	end
	return users
end
function clib.in_channel(chan, id)
	local users = clib.list_users(chan)
	if not users then
		return false
	end
	for user, _ in pairs(users) do
		print("users: "..user)
		if user == id then
			return true
		end
	end
end

-- chan get...
function clib.gettopic(chan)
	return kvstore._get("circd:chan:topic:"..chan)
end

-- chan set...
function clib.settopic(chan, topic)
	return kvstore._get("circd:chan:topic:"..chan, topic)
end

----
--- helpers for both chan and users
----

function clib.privmsg(id, to, msg)
	print("PRIVMSG to "..to)
	local host = clib.gethost(id)
	if clib.channel_exists(to) then -- channel
		clib.send_chan(id, to, ":"..host.." PRIVMSG "..to.." :"..msg)
		return true
	else -- user
		local client = clib.getclient(to)
		if client then
			clib.send(client, ":"..host.." PRIVMSG "..to.." :"..msg)
			return true
		else
			return false
		end
	end
end
function clib.notice(id, to, msg)
	local host = clib.gethost(id)
	if to:match("^#") then -- channel
		clib.send_chan(id, to, ":"..host.." NOTICE "..to.." :"..msg)
	else -- user
		local client = clib.getclient(to)
		if client then
			clib.send(client, ":"..host.." NOTICE "..to.." :"..msg)
		end
	end
end

return clib


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.fanlehai</groupId>
		<artifactId>code</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<artifactId>design_pattern</artifactId>
	<packaging>jar</packaging>

	<name>design_pattern</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
require('./angular-locale_ss');
module.exports = 'ngLocale';


text:
define(['backbone.paginator', 'utils/kvcollection'], function(PageableCollection, KVCollection) {

  return PageableCollection.extend(_.extend({}, KVCollection, {
    mode: 'client',
    url: '/vstat/runs',

    keyAttribute: 'RUN',
    valueAttribute: 'RUNID',

    state: {
      pageSize: 15,
    },

  }))
})


text:
package de.fhg.iais.cortex.services.search;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.stub;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.solr.client.solrj.SolrServerException;
import org.jdom.JDOMException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;

import de.fhg.iais.cortex.search.Searcher;
import de.fhg.iais.cortex.search.types.Cluster;
import de.fhg.iais.cortex.search.types.Facet;
import de.fhg.iais.cortex.search.types.FacetValue;
import de.fhg.iais.cortex.search.types.Query;
import de.fhg.iais.cortex.search.types.SearchResult;
import de.fhg.iais.cortex.search.types.SearchResults;
import de.fhg.iais.cortex.search.types.SortCriterion;
import de.fhg.iais.cortex.services.SearchServiceImpl;

public class SearchServiceImplTest {

    private static final String TESTSTRING =
        "
ÖÜÄ Title:Tabula affinitatum animalium olim academico specimine edita, nunc uberiore commentario illustrata ; cum "
            + "annotationibus ad historiam naturalem animalium augendam facientibus
Creator:Hermann, "
            + "Johannes
Year:1783
Subject:Zoologica

";

    private SearchServiceImpl searchService;
    private Searcher searcher;
    private SearchResults mockResults;

    @Before
    public void setup() throws JDOMException, IOException, SolrServerException {
        createMocks();
        this.searchService = new SearchServiceImpl(this.searcher);
    }

    private void createMocks() {
        List<Cluster<SearchResult>> mockList = expectedResults();
        this.mockResults = mock(SearchResults.class);
        stub(this.mockResults.getResults()).toReturn(mockList);
        stub(this.mockResults.getNumberOfResults()).toReturn(1L);
        stub(this.mockResults.getFacets()).toReturn(new Facet[] {
            new Facet("P4f_s")
        });

        this.searcher = mock(Searcher.class);
        stub(this.searcher.getAutocompleteProposals(Matchers.<Query> any(), anyString(), anyString(), (SortCriterion) anyObject())).toReturn(new Facet[] {
            new Facet("P4f_s")
        });
    }

    private Facet[] mockFacets(Query query) {
        Facet[] facetList = new Facet[1];
        Facet facet = new Facet("Ort");

        FacetValue facetValue1 = new FacetValue();
        facetValue1.setCount(2 * query.getMinDocs());
        facetValue1.setValue("TestFacet1");
        facet.addFacetValue(facetValue1);

        FacetValue facetValue2 = new FacetValue();
        facetValue2.setCount(query.getMinDocs());
        facetValue2.setValue("TestFacet2");
        facet.addFacetValue(facetValue2);

        facetList[0] = facet;
        return facetList;
    }

    private List<Cluster<SearchResult>> expectedResults() {
        List<Cluster<SearchResult>> expectedResults = new ArrayList<Cluster<SearchResult>>();
        SearchResult result = new SearchResult();
        result.setId("175623520");
        result.setPreview(TESTSTRING);
        Cluster<SearchResult> cluster = new Cluster<SearchResult>();
        cluster.add(result);
        expectedResults.add(cluster);
        return expectedResults;
    }

    @Test
    public void testSearchAll() throws IOException {
        Query query = new Query("Tabula");
        stub(this.searcher.search(query)).toReturn(this.mockResults);
        SearchResults<SearchResult> response = this.searchService.search(query);
        assertNotNull(response);
        assertEquals(1, response.getNumberOfResults());
        assertEquals("175623520", response.getResults().get(0).getDocs().get(0).getId());
        assertEquals(TESTSTRING, response.getResults().get(0).getDocs().get(0).getPreview());
    }

    @Test
    public void searchEmptyFacetsReturnsAllFacets() throws IOException {
        Query query = new Query("tabula");
        SearchResults results = new SearchResults();
        stub(this.searcher.searchFaceted(query)).toReturn(results);

        SearchResults searchResults = this.searchService.searchFaceted(query);
        assertEquals(results, searchResults);
    }

    @Test
    public void searchAlreadyPresentFacetsArePreserved() throws IOException {
        Query query = new Query("tabula");
        query.setFacets(new Facet("sparte"));
        SearchResults mockResults = new SearchResults();
        Facet sparte = new Facet("sparte");
        sparte.addFacetValue(new FacetValue("bib", 5));
        sparte.addFacetValue(new FacetValue("mus", 4));
        sparte.setNumberOfFacets(2);
        mockResults.setFacets(new Facet[] {
            sparte
        });
        stub(this.searcher.searchFaceted(query)).toReturn(mockResults);

        SearchResults searchResults = this.searchService.searchFaceted(query);
        assertEquals(0, searchResults.getNumberOfResults());

        assertNotNull(searchResults.getFacets());
        assertEquals(1, searchResults.getFacets().length);
        Facet spartenFacet = searchResults.getFacets()[0];
        assertEquals("sparte", spartenFacet.getField());
        assertEquals(2, spartenFacet.getNumberOfFacets());
        assertEquals("bib", spartenFacet.getFacetValues().get(0).getValue());
        assertEquals(5, spartenFacet.getFacetValues().get(0).getCount());
        assertEquals("mus", spartenFacet.getFacetValues().get(1).getValue());
        assertEquals(4, spartenFacet.getFacetValues().get(1).getCount());

        assertEquals("sparte", searchResults.getFacets()[0].getField());
    }

    @Test
    public void testSearchFaceted() throws IOException {
        Query query = new Query("tabula");
        Facet facet = new Facet("P4F");
        facet.addFacetValue(new FacetValue("1809", 22));
        query.setFacets(facet);
        stub(this.searcher.searchFaceted(query)).toReturn(this.mockResults);

        SearchResults<SearchResult> searchResults = this.searchService.searchFaceted(query);
        assertEquals(1, searchResults.getNumberOfResults());
        assertEquals("175623520", searchResults.getResults().get(0).getDocs().get(0).getId());
        assertEquals(TESTSTRING, searchResults.getResults().get(0).getDocs().get(0).getPreview());

        Query query2 = new Query("tabula");
        Facet facet2 = new Facet("P4F");
        facet2.addFacetValue(new FacetValue("1782", 22));
        query2.setFacets(facet2);
        stub(this.searcher.searchFaceted(query2)).toReturn(new SearchResults());
        SearchResults searchResults2 = this.searchService.searchFaceted(query2);
        assertEquals(0, searchResults2.getNumberOfResults());
        assertEquals(0, searchResults2.getResults().size());
    }

    @Test
    public void testGetFacets() throws IOException {
        Query query = new Query("Tabula");
        query.setMinDocs(2);
        stub(this.searcher.getAutocompleteProposals(query, "R", "Ort", SortCriterion.RELEVANCE)).toReturn(mockFacets(query));
        Facet[] facets = this.searchService.getFacetAutocompleteValues(query, "R", "Ort", SortCriterion.RELEVANCE);

        assertNotNull(facets);
        assertEquals(1, facets.length);
        assertEquals("Ort", facets[0].getField());
        assertEquals(2, facets[0].getFacetValues().size());
        assertEquals("TestFacet1", facets[0].getFacetValues().get(0).getValue());
        assertEquals("TestFacet2", facets[0].getFacetValues().get(1).getValue());
    }
}


text:
package data

import (
	"bytes"
	"encoding/binary"
)

func BytesToInt32(bs []byte) int32 {
	var i int32
	buff := bytes.NewBuffer(bs)
	binary.Read(buff, binary.BigEndian, &i)
	return i
}

func BytesToUint8(bs []byte) uint8 {
	var i uint8
	buff := bytes.NewBuffer(bs)
	binary.Read(buff, binary.BigEndian, &i)
	return i
}

func Int32ToBytes(i int32) []byte {
	bs := make([]byte, 0, 4)
	buff := bytes.NewBuffer(bs)
	binary.Write(buff, binary.BigEndian, &i)
	return buff.Bytes()
}

func Uint8ToBytes(i uint8) []byte {
	bs := make([]byte, 0, 1)
	buff := bytes.NewBuffer(bs)
	binary.Write(buff, binary.BigEndian, &i)
	return buff.Bytes()
}


text:
package service

import (
	"time"

	"context"
	"go-common/app/interface/main/tv/model"
	"go-common/app/interface/main/tv/model/search"
	"go-common/library/log"
)

// cardIntervSn, makes season intervention effective for cards
func (s *Service) cardIntervSn(cards []*model.Card) (err error) {
	var (
		snMetas     map[int64]*model.SeasonCMS
		epMetas     map[int64]*model.EpCMS
		sids        []int64
		newestEPIDs []int64
	)
	for _, card := range cards {
		if card.NewEP != nil {
			sids = append(sids, int64(card.SeasonID))
			newestEPIDs = append(newestEPIDs, card.NewEP.ID)
		}
	}
	if snMetas, err = s.cmsDao.LoadSnsCMSMap(ctx, sids); err != nil {
		log.Error("[cardIntervSn] loadSnCMSMap Sids: %v, Err %v", sids, err)
		return
	}
	if epMetas, err = s.cmsDao.LoadEpsCMS(ctx, newestEPIDs); err != nil {
		log.Error("[cardIntervSn] loadEpCMS epids: %v, Err %v", newestEPIDs, err)
		return
	}
	for _, card := range cards {
		// season intervention
		sid := int64(card.SeasonID)
		if snCache, ok := snMetas[sid]; !ok {
			log.Error("LoadSnsCMS Miss Info for Sid: %d", sid)
			continue
		} else { // intervention
			if snCache.Title != "" {
				card.Title = snCache.Title
			}
			if snCache.Cover != "" {
				card.Cover = snCache.Cover
			}
			if snCache.NeedVip() { // card add vip corner mark
				card.CornerMark = &(*s.conf.Cfg.SnVipCorner)
			}
		}
		// ep intervention
		epid := card.NewEP.ID
		if epCache, ok := epMetas[epid]; !ok {
			log.Error("LoadSnsCMS Miss Info for Sid: %d", epid)
			continue
		} else { // intervention
			if epCache.Cover != "" {
				card.NewEP.Cover = epCache.Cover
			}
		}
	}
	return
}

// load index show proc
func (s *Service) indexShowproc() {
	for {
		time.Sleep(time.Duration(s.conf.Cfg.IndexShowReload))
		s.indexShow()
	}
}

func (s *Service) indexShow() (err error) {
	defer elapsed("indexShow")()
	var (
		indexShows map[int64]string
		sids       []int64
	)
	if sids, err = s.dao.PassedSns(ctx); err != nil {
		log.Error("[loadIndexShow] AllIntervs Error %v", err)
		return
	}
	if indexShows, err = s.PgcCards(sids); err != nil {
		log.Error("[loadIndexShow] AllIntervs Error %v", err)
		return
	}
	log.Info("Reload Types For Index_Show, Origin:%d, Length: %d", len(sids), len(indexShows))
	if len(indexShows) > 0 {
		s.PGCIndexShow = indexShows
	}
	return
}

func (s *Service) filterIntervs(ctx context.Context) (err error) {
	defer elapsed("filterIntervs")()
	var (
		sids, aids, rmSids, rmAids []int64
		pgcAuth                    map[int64]*model.SnAuth
		ugcAuth                    map[int64]*model.ArcCMS
	)
	if sids, aids, err = s.dao.AllIntervs(ctx); err != nil {
		log.Error("[filterIntervs] AllIntervs Error %v", err)
		return
	}
	if pgcAuth, err = s.cmsDao.LoadSnsAuthMap(ctx, sids); err != nil {
		log.Error("[filterIntervs] LoadSnsAuthMap Error %v, Sids %v", err, sids)
		return
	}
	if ugcAuth, err = s.cmsDao.LoadArcsMediaMap(ctx, aids); err != nil {
		log.Error("[filterIntervs] LoadArcsMediaMap Error %v, Aids %v", err, aids)
		return
	}
	for sid, pAuth := range pgcAuth {
		if !pAuth.CanPlay() {
			rmSids = append(rmSids, sid)
		}
	}
	for aid, arcAuth := range ugcAuth {
		if !arcAuth.CanPlay() {
			rmAids = append(rmAids, aid)
		}
	}
	if len(rmSids) > 0 || len(rmAids) > 0 {
		if err = s.dao.RmInterv(ctx, rmAids, rmSids); err != nil {
			log.Error("RmInterv Aids %v, Sids %v, Err %v", aids, sids, err)
			return
		}
		log.Warn("[filterIntervs] Ori Sids %d, Aids %d, To Remove Sids %v, Aids %v", len(sids), len(aids), rmSids, rmAids)
	}
	return
}

func (s *Service) ppIdxIntev(ctx context.Context) (err error) {
	var (
		newIdx *search.IdxIntervSave
	)
	if newIdx, err = s.dao.IdxIntervs(ctx); err != nil {
		log.Error("prepareIdxIntervs Err %v")
		return
	}
	s.IdxIntervs = newIdx
	log.Info("ppIdxInterv refresh, PGC %d, UGC %d", len(newIdx.Pgc), len(newIdx.Ugc))
	return
}

func (s *Service) ppIdxIntervproc() {
	for {
		time.Sleep(time.Duration(s.conf.Cfg.EsIntervReload))
		s.ppIdxIntev(context.Background())
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /><title>JspParserVisitorAdapter xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />

View Javadoc

1   package net.sourceforge.pmd.jsp.ast;
2
3
4   public class JspParserVisitorAdapter implements JspParserVisitor {
5
6       public Object visit(SimpleNode node, Object data) {
7           node.childrenAccept(this, data);
8           return null;
9       }
10
11      public Object visit(ASTCompilationUnit node, Object data) {
12          return visit((SimpleNode) node, data);
13      }
14
15      public Object visit(ASTContent node, Object data) {
16          return visit((SimpleNode) node, data);
17      }
18
19      public Object visit(ASTJspDirective node, Object data) {
20          return visit((SimpleNode) node, data);
21      }
22
23      public Object visit(ASTJspDirectiveAttribute node, Object data) {
24          return visit((SimpleNode) node, data);
25      }
26
27      public Object visit(ASTJspScriptlet node, Object data) {
28          return visit((SimpleNode) node, data);
29      }
30
31      public Object visit(ASTJspExpression node, Object data) {
32          return visit((SimpleNode) node, data);
33      }
34
35      public Object visit(ASTJspDeclaration node, Object data) {
36          return visit((SimpleNode) node, data);
37      }
38
39      public Object visit(ASTJspComment node, Object data) {
40          return visit((SimpleNode) node, data);
41      }
42
43      public Object visit(ASTText node, Object data) {
44          return visit((SimpleNode) node, data);
45      }
46
47      public Object visit(ASTUnparsedText node, Object data) {
48          return visit((SimpleNode) node, data);
49      }
50
51      public Object visit(ASTElExpression node, Object data) {
52          return visit((SimpleNode) node, data);
53      }
54
55      public Object visit(ASTValueBinding node, Object data) {
56          return visit((SimpleNode) node, data);
57      }
58
59      public Object visit(ASTCData node, Object data) {
60          return visit((SimpleNode) node, data);
61      }
62
63      public Object visit(ASTElement node, Object data) {
64          return visit((SimpleNode) node, data);
65      }
66
67      public Object visit(ASTAttribute node, Object data) {
68          return visit((SimpleNode) node, data);
69      }
70
71      public Object visit(ASTAttributeValue node, Object data) {
72          return visit((SimpleNode) node, data);
73      }
74
75      public Object visit(ASTJspExpressionInAttribute node, Object data) {
76          return visit((SimpleNode) node, data);
77      }
78
79      public Object visit(ASTCommentTag node, Object data) {
80          return visit((SimpleNode) node, data);
81      }
82
83      public Object visit(ASTDeclaration node, Object data) {
84          return visit((SimpleNode) node, data);
85      }
86
87      public Object visit(ASTDoctypeDeclaration node, Object data) {
88          return visit((SimpleNode) node, data);
89      }
90
91      public Object visit(ASTDoctypeExternalId node, Object data) {
92          return visit((SimpleNode) node, data);
93      }
94
95      public Object visit(ASTHtmlScript node, Object data) {
96          return visit((SimpleNode) node, data);
97      }
98  }

This page was automatically generated by Maven


text:
var assert = require('assert');
var _ = require('@sailshq/lodash');

describe('SQL Interface', function() {
  describe('.find()', function() {
    before(function(done) {

      // Insert 10 Users
      var users = [];

      for(var i=0; i<10; i++) {
        users.push({first_name: 'find_user' + i, type: 'find test', age: i*10 });
      }

      users.push({first_name: 'blackbeard\'s ghost', type: 'find test', age: 999});

      Sql.Userforsqlinterface.createEach(users, function(err, users) {
        if (err) {
          return done(err);
        }

        return done();
      });
    });

    it('should escape attribute names to prevent SQL injection attacks', function(done) {
      Sql.Userforsqlinterface.find({ type: 'find_test', 'first_name`IS NULL OR 1=1 #': 'whatever' }, function(err, users) {
        assert(err, 'Should have escaped field name and prevented data from being returned (caused an error)');
        assert(!users || !users.length, 'Should have escaped field name and prevented data from being returned');

        return done();
      });
    });

    it('should escape values when using startsWith modifier to prevent SQL injection attacks', function(done) {
      var part = '\\\\\\" OR 1=1; -- %_';
      Sql.Userforsqlinterface.find({ first_name: { startsWith: part }}, function(err, users) {
        if (err) {
          return done(err);
        }

        assert(!users.length);

        return done();
      });
    });

    it('should escape values when using endsWith modifier to prevent SQL injection attacks', function(done) {
      var part = '\\\\\\" OR 1=1; -- %_';
      Sql.Userforsqlinterface.find({ first_name: { endsWith: part }}, function(err, users) {
        if (err) {
          return done(err);
        }

        assert(!users.length);

        return done();
      });
    });

    it('should escape values when using contains modifier to prevent SQL injection attacks', function(done) {
      var part = '\\\\\\" OR 1=1; -- %_';
      Sql.Userforsqlinterface.find({ first_name: { contains: part }}, function(err, users) {
        if (err) {
          return done(err);
        }

        assert(!users.length);

        return done();
      });
    });

    it('should escape values when using like modifier to prevent SQL injection attacks', function(done) {
      var part = '\\\\\\" OR 1=1; -- %_';
      Sql.Userforsqlinterface.find({ first_name: { like: part }}, function(err, users) {
        if (err) {
          return done(err);
        }

        assert(!users.length);

        return done();
      });
    });

    it('should not unneccessarily escape values in criteria', function(done) {
      Sql.Userforsqlinterface.findOne({ first_name: 'blackbeard\'s ghost'}, function(err, user) {
        if (err) {
          return done(err);
        }

        assert(user);
        assert.equal(user.first_name, 'blackbeard\'s ghost');

        return done();
      });
    })
  });
});


text:
"use strict";

// No JSHint errors
var foo = "bar";
foo;


text:
/**
 * Main config for the project
 * @type {Object}
 */
module.exports = {
  /** @type {String} Private app name */
  appName: 'gamejam-server',
  /** @type {Number} HTTP Port */
  httpPort: 3000,
  /** @type {Number} Socket port */
  socketPort: 3030,
  /** @type {String} Environment variable */
  environment: 'development',

  mongo: {
    host: 'localhost',
    port: '27017',
    database: 'test_dev',
    username: '',
    password: '',
    uri: function () {
      if (this.username.length >= 1)
        return `mongodb://${this.username}:${this.password}@${this.host}:${this.port}/${this.database}`;
      return `mongodb://${this.host}:${this.port}/${this.database}`;
    },
    options: {
      server: {
        autoReconnect: true,
        poolSize: 10,
        socket_option: {
          keepAlive: true
        }
      }
    }
  }
}


text:
using System;

#if __UNIFIED__
using UIKit;
#else
using MonoTouch.UIKit;
#endif

namespace ZXing.Mobile
{
	public interface IScannerViewController
	{
		void Torch(bool on);

		void ToggleTorch();
		void Cancel();

		bool IsTorchOn { get; }

		event Action<ZXing.Result> OnScannedResult;

		MobileBarcodeScanningOptions ScanningOptions { get;set; }
		MobileBarcodeScanner Scanner { get;set; }

		UIViewController AsViewController();
	}
}


text:
module Gitlab
  module BackgroundMigration
    # EncryptColumn migrates data from an unencrypted column - `foo`, say - to
    # an encrypted column - `encrypted_foo`, say.
    #
    # To avoid depending on a particular version of the model in app/, add a
    # model to `lib/gitlab/background_migration/models/encrypt_columns` and use
    # it in the migration that enqueues the jobs, so code can be shared.
    #
    # For this background migration to work, the table that is migrated _has_ to
    # have an `id` column as the primary key. Additionally, the encrypted column
    # should be managed by attr_encrypted, and map to an attribute with the same
    # name as the unencrypted column (i.e., the unencrypted column should be
    # shadowed), unless you want to define specific methods / accessors in the
    # temporary model in `/models/encrypt_columns/your_model.rb`.
    #
    class EncryptColumns
      def perform(model, attributes, from, to)
        model = model.constantize if model.is_a?(String)

        # If sidekiq hasn't undergone a restart, its idea of what columns are
        # present may be inaccurate, so ensure this is as fresh as possible
        model.reset_column_information
        model.define_attribute_methods

        attributes = expand_attributes(model, Array(attributes).map(&:to_sym))

        model.transaction do
          # Use SELECT ... FOR UPDATE to prevent the value being changed while
          # we are encrypting it
          relation = model.where(id: from..to).lock

          relation.each do |instance|
            encrypt!(instance, attributes)
          end
        end
      end

      def clear_migrated_values?
        true
      end

      private

      # Build a hash of { attribute => encrypted column name }
      def expand_attributes(klass, attributes)
        expanded = attributes.flat_map do |attribute|
          attr_config = klass.encrypted_attributes[attribute]
          crypt_column_name = attr_config&.fetch(:attribute)

          raise "Couldn't determine encrypted column for #{klass}##{attribute}" if
            crypt_column_name.nil?

          raise "#{klass} source column: #{attribute} is missing" unless
            klass.column_names.include?(attribute.to_s)

          # Running the migration without the destination column being present
          # leads to data loss
          raise "#{klass} destination column: #{crypt_column_name} is missing" unless
            klass.column_names.include?(crypt_column_name.to_s)

          [attribute, crypt_column_name]
        end

        Hash[*expanded]
      end

      # Generate ciphertext for each column and update the database
      def encrypt!(instance, attributes)
        to_clear = attributes
          .map { |plain, crypt| apply_attribute!(instance, plain, crypt) }
          .compact
          .flat_map { |plain| [plain, nil] }

        to_clear = Hash[*to_clear]

        if instance.changed?
          instance.save!

          if clear_migrated_values?
            instance.update_columns(to_clear)
          end
        end
      end

      def apply_attribute!(instance, plain_column, crypt_column)
        plaintext = instance[plain_column]
        ciphertext = instance[crypt_column]

        # No need to do anything if the plaintext is nil, or an encrypted
        # value already exists
        return nil unless plaintext.present? && !ciphertext.present?

        # attr_encrypted will calculate and set the expected value for us
        instance.public_send("#{plain_column}=", plaintext) # rubocop:disable GitlabSecurity/PublicSend

        plain_column
      end
    end
  end
end


text:
{% comment %}
TODO: Move dynamically generated javascript to static files for performance
{% endcomment %}

var objectsColumnName = "Objects Data"

function addObjectsHandler(table, selectedArray, isRefreshWhileDialogOpen) {
    if(typeof isRefreshWhileDialogOpen === 'undefined') {
        isRefreshWhileDialogOpen = true;
    }

    var startRow = selectedArray[0];
    var endRow = selectedArray[2];
    var tableName = "object_inline";
    var objectRowName = 'object_row';

    if(startRow > endRow) {
        var tmp = startRow;
        startRow = endRow;
        endRow = tmp;
    }

    var titleText = "";

    if(startRow === endRow) {
        titleText = "Bulk add objects for row: " + (parseInt(startRow) + 1);
    } else {
        titleText = "Bulk add objects for rows: " + (parseInt(startRow) + 1) + " - " + (parseInt(endRow) + 1);
    }

    var tableList;
    var recreateObjectsDialogFunction = function() {
        tableList = $('#handsontable_' + tableName + '_list');

        removeInlineObjectTables(tableList, objectRowName);

        createInlineObjectTables(table, tableList, startRow, endRow, objectRowName);
    };

    // check if the dialog has already been initialized
    if($('#handsontable_object').hasClass('ui-dialog-content')) {
        // the dialog has already been initialized
        $('#handsontable_object').off('dialogopen');

        $('#handsontable_object').on('dialogopen', function(event, ui) {
            recreateObjectsDialogFunction();
        });

        $('#validate-' + tableName + '-inline-table').off('click');

        // these button events need to be here because the load() function
        // is asynchronous outside of this "open" event and the buttons need to exist first
        $('#validate-' + tableName + '-inline-table').click(function() {
            for(var rowCounter = startRow; rowCounter <= endRow; rowCounter++) {
                rowTableName = objectRowName + rowCounter;
                uploadTable(rowTableName, null, true, {}, "{% url 'cripts.objects.views.bulk_add_object_inline' %}");
            }
        });
    }
    else {
        // the dialog has not been initialized yet
        appendObjectsColumn(table);

        $('#handsontable_object').dialog({
            autoOpen: false,
            height: 400,
            width: 600
        });

        $('#handsontable_object').on('dialogopen', function(event, ui) {
            $(this).load("{% url 'cripts.objects.views.bulk_add_object_inline' %}?" + $.param({'isPreventInitialTable': true}),
                function() {
                    var objectsColumnIndex = getColumnIndexFromName(table, objectsColumnName);

                    $('#handsontable_object_inline').prepend('

');
                    tableList = $('#handsontable_' + tableName + '_list');

                    createInlineObjectTables(table, tableList, startRow, endRow, objectRowName);

                    $('#update-' + tableName + '-inline-table span').text('Add Objects');

                    // these button events need to be here because the load() function
                    // is asynchronous outside of this "open" event and the buttons need to exist first
                    $('#update-' + tableName + '-inline-table').click(function() {
                        var objectsDataArray = [];

                        $(tableList).find('div[id^=handsontable_' + objectRowName + "]").each(function( index, rowTable ) {
                            var rowID = $(rowTable).attr('id');
                            var rowNumber = rowID.replace('handsontable_' + objectRowName, '');
                            //var cleanedData = getCleanedData($(this));
                            var totalRows = $(this).handsontable('countRows');
                            var totalCols = $(this).handsontable('countCols');

                            var rawArrayData = $(this).handsontable('getData', 0, 0, totalRows - 1, totalCols - 1);
                            var cleanedArrayData = getCleaned2DArray($(this), rawArrayData);

                            if(objectsColumnIndex > 0 && cleanedArrayData.length > 0) {
                                objectsDataArray.push([rowNumber, objectsColumnIndex, JSON.stringify(cleanedArrayData)]);
                            }
                        });

                        table.handsontable('setDataAtCell', objectsDataArray);
                        $('#handsontable_object').dialog('close');
                    });

                    $('#validate-' + tableName + '-inline-table').off('click');

                    // these button events need to be here because the load() function
                    // is asynchronous outside of this "open" event and the buttons need to exist first
                    $('#validate-' + tableName + '-inline-table').click(function() {
                        for(var rowCounter = startRow; rowCounter <= endRow; rowCounter++) {
                            rowTableName = objectRowName + rowCounter;
                            uploadTable(rowTableName, null, true, {}, "{% url 'cripts.objects.views.bulk_add_object_inline' %}");
                        }
                    });
                }
            );
        });
    }

    var isDialogOpen = $('#handsontable_object').dialog('isOpen');

    // only refresh the dialog if requested -- or, it not requested
    // then only refresh if the dialog is not already open
    if(isRefreshWhileDialogOpen === true || (isRefreshWhileDialogOpen === false && isDialogOpen === false)) {
        $('#handsontable_object').dialog('option', 'title', titleText);

        if(isDialogOpen === true) {
            recreateObjectsDialogFunction();
        } else {
            $('#handsontable_object').dialog('open');
        }
    }
}

function appendObjectsColumn(table) {

    var objectsColumnIndex = getColumnIndexFromName(table, objectsColumnName);

    if(objectsColumnIndex === -1) {
        appendColumns(table, [{type: 'text'}], [objectsColumnName]);
        setObjectsClickEventAllCols(table);
    }

    return objectsColumnIndex;
}

function createInlineObjectTables(table, createObjectsInElem, startRow, endRow, tablePrefix) {

    var objectsColumnIndex = getColumnIndexFromName(table, objectsColumnName);

    for(var rowCounter = startRow; rowCounter <= endRow; rowCounter++) {
        var rowTableName = tablePrefix + rowCounter;
        var firstColumnName = $(table).handsontable('getColHeader', 0);
        var newFullTableName = 'handsontable_' + rowTableName;

        var firstColumnValue = table.handsontable('getDataAtCell', rowCounter, 0);

        if(firstColumnValue === null) {
            firstColumnValue = "";
        }

        $(createObjectsInElem).append('
Row ' + (parseInt(rowCounter) + 1) + ' [' + firstColumnName + ": " + firstColumnValue + ']
');
        $(createObjectsInElem).append('

');
        $(createObjectsInElem).append('

');
        $(createObjectsInElem).append('
');

        initializeHandsOnTableInline(newFullTableName, rowTableName);

        // try and load array data from the main table
        var existentData = table.handsontable('getDataAtCell', rowCounter, objectsColumnIndex);

        if(typeof existentData === 'string' && $.trim(existentData)) {
            try {
                var data = JSON.parse(existentData);
                //$('#' + newFullTableName).handsontable('loadData', JSON.parse(existentData))
                // Use the populateFromArray instead of loadData to force
                // the change events to fire off.
                $('#' + newFullTableName).handsontable('populateFromArray', 0, 0, data);
            } catch(ex) {
                alert("Error parsing object string data: " + existentData);
            }
        }
    }
}

function getObjectsTDFromRow(table, row) {
    var objectsColumnIndex = getColumnIndexFromName(table, objectsColumnName);
    var returnValue = null;

    if(objectsColumnIndex > 0) {
        returnValue = $(table).find("tr:eq(" + (row + 1) + ") td[data-column=" + objectsColumnIndex + "]");
    }

    return returnValue;
}

function setObjectsClickEvent(table, td) {
    $(td).on('dblclick', function(event, ui) {
        var row = td.attr('data-row');
        var col = td.attr('data-col');
        addObjectsHandler(table, [row,col,row,col], false);
    });
}

function setObjectsClickEventAllCols(table) {
    var totalRows = table.handsontable('countRows');
    var objectsColumnIndex = getColumnIndexFromName(table, objectsColumnName);

    // set the objects click event only if the objects column exists
    if(objectsColumnIndex > 0) {
        for(var row = 0; row < totalRows; row++) {
            setObjectsClickEventForRow(table, row);
        }
    }
}

function setObjectsClickEventForVisibleRows(table) {
    var totalVisibleRows = table.handsontable('countVisibleRows');

    for(var i = 0; i < totalVisibleRows; i++) {
        setObjectsClickEventForRow(table, i);
    }
}

function setObjectsClickEventForRow(table, row) {
    var td = getObjectsTDFromRow(table, row);
    if((td !== null) && (typeof td !== 'undefined')) {
        setObjectsClickEvent(table, td);
    }
}

function setObjectsClickEventForRows(table, rows) {
    for(var row = 0; row < rows.length; row++) {
        setObjectsClickEventForRow(table, rows[row]);
    }
}

function removeInlineObjectTables(table, tablePrefix) {

    $(table).find('div[id^=handsontable_' + tablePrefix + "]").remove();
    $(table).find('p.row_title').remove();
    $(table).find('div[id^=' + tablePrefix + "]").remove();
    $(table).find('hr').remove();
}


text:
var test = require("tape")
var EvStore = require("ev-store")

var h = require("../index.js")
var createElement = require("../../vdom/create-element")
var patch = require("../../vdom/patch")
var diff = require("../../vtree/diff")

test("h with events", function (assert) {
    function one() {}

    var left = h(".foo", {
        "ev-click": one
    })

    var right = h(".bar", {})

    var elem = createElement(left)

    var ds1 = EvStore(elem)
    assert.ok(ds1)
    assert.equal(ds1.click, one)

    var patches = diff(left, right)

    patch(elem, patches)

    var ds2 = EvStore(elem)
    assert.ok(ds2)
    assert.equal(ds1, ds2)
    assert.equal(ds2.click, undefined)

    assert.end()
})


text: This folder contains all the images that explain the heatmap in Writeup.md.


text:
package info.guardianproject.otr.app.im.provider;

public class ImpsAddressUtils {

    public static String getDisplayableAddress(String impsAddress) {
        if (impsAddress.startsWith("wv:")) {
            return impsAddress.substring(3);
        }
        return impsAddress;
    }
}


text:
var utils = require('./utils');

module.exports = function(config){
  var transFn = utils.lookupFn(config.path);
  return function(req, res, next){
    res.locals = transFn(res.locals);
    next();
  };
};


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package erp.mfin.data;

/**
 *
 * @author Alfonso Flores
 */
public class SDataTaxGroupEntryRow extends erp.lib.table.STableRow {

    public SDataTaxGroupEntryRow(java.lang.Object data) {
        moData = data;
        prepareTableRow();
    }

    @Override
    public void prepareTableRow() {
        SDataTaxGroupEntry entry = (SDataTaxGroupEntry) moData;

        mvValues.clear();
        mvValues.add(entry.getDbmsTaxIdentityEmisorType());
        mvValues.add(entry.getDbmsTaxIdentityReceptorType());
        mvValues.add(entry.getDateStart());
        mvValues.add(entry.getDateEnd_n());
        mvValues.add(entry.getDbmsTax());
        mvValues.add(entry.getApplicationOrder());
    }
}


text:
import { inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { EventAggregator } from 'aurelia-event-aggregator';
import { AuthConfig } from './auth0-config';

import auth0 from 'auth0-js';

@inject(Router, EventAggregator)
export class Auth0Service {

  constructor(router, eventAggregator) {
    this.router = router;
    this.eventAggregator = eventAggregator;
    this.returnRoute = '';
    this.userProfile;
    this.refreshSubscription = false;

    this.auth0Service = this;

    this.auth0 = new auth0.WebAuth({
      clientID: AuthConfig.clientID,
      domain: AuthConfig.domain,
      responseType: 'token id_token',
      audience: AuthConfig.audience,
      redirectUri: AuthConfig.callbackURL
    });
  }

  login() {
    //
    // The next call causes application's reset - the control
    // continues in handleAuthenticaton method below, invoked
    // from app.js attached() callback
    ///
    this.auth0.authorize();
  }

  logout() {
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('expires_at');
    this.eventAggregator.publish('authChannel', 'Login');
    this.router.navigate('home');
  }

  handleAuthentication() {
    let auth0Service = this.auth0Service;

    this.auth0.parseHash(window.location.hash, (err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        //
        // persist the settings we care about
        //
        this.setSession(authResult);

        //
        // go to the page that triggered authentication
        //
        let returnRoute = localStorage.getItem('returnRoute');
        this.router.navigate(returnRoute);

        //
        // tell navbar to set the "logged in state" ui
        //
        auth0Service.eventAggregator.publish('authChannel', 'Logout');
      } else if (err) {
        //
        // TODO: better error handling
        //
        console.log(err);
      }
    });
  }

  getProfile(cb) {
    const accessToken = localStorage.getItem('access_token');
    if (!accessToken) {
      throw new Error('Access token must exist to fetch profile');
    }

    const self = this;
    this.auth0Service.client.userInfo(accessToken, (err, profile) => {
      if (profile) {
        self.userProfile = profile;
      }
      cb(err, profile);
    });
  }

  setSession(authResult) {
    let expiresAt = JSON.stringify(
      authResult.expiresIn * 1000 + new Date().getTime()
    );
    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('expires_at', expiresAt);

    console.log('id_token:   ' + authResult.idToken);
    console.log('access_token: ' + authResult.accessToken);
    console.log('expires_at', expiresAt);
  }

  isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiration time
    let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }

}


text:
// Module dependencies
var express = require('express');
var fs = require('fs');
var passport = require('passport');
var http = require('http');
//var socket = require('./socket');

// Load configurations
// if test env, load example file
var env = process.env.NODE_ENV || 'development';
var config = require('./config/config')[env];
var mongoose = require('mongoose');

// Connect to DB
mongoose.connect(config.db);

// Bootstrap models
var modelsPath = __dirname + '/models';
fs.readdirSync(modelsPath).forEach(function (file) {
    require(modelsPath + '/' + file);
});

// bootstrap passport config
require('./config/passport')(passport, config);

// Setup express
var app = express();
var server = http.createServer(app);

// express settings
require('./config/express')(app, config, passport);

var port = process.env.PORT || config.port;
server.listen(port);
/*global exports:true*/
//socket.listen(server);
console.log('App started on port ' + port);
exports = module.exports = app;


text:
class AddStepOneFieldsToAgreements < ActiveRecord::Migration[4.2]
  def change
    add_column :agreements, :current_step, :integer, null: false, default: 0

    add_column :agreements, :data_user, :string
    add_column :agreements, :data_user_type, :string, null: false, default: 'individual'

    add_column :agreements, :individual_institution_name, :string
    add_column :agreements, :individual_title, :string
    add_column :agreements, :individual_telephone, :string
    add_column :agreements, :individual_fax, :string
    add_column :agreements, :individual_address, :text

    add_column :agreements, :organization_business_name, :string
    add_column :agreements, :organization_contact_name, :string
    add_column :agreements, :organization_contact_title, :string
    add_column :agreements, :organization_contact_telephone, :string
    add_column :agreements, :organization_contact_fax, :string
    add_column :agreements, :organization_contact_email, :string
    add_column :agreements, :organization_address, :text
  end
end


text:
namespace Exceptions_Homework
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public class ExceptionsHomework
    {
        public static void Main()
        {
            try
            {
                var substr = Subsequence("Hello!".ToCharArray(), 2, 3);
                Console.WriteLine(substr);

                var subarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 2);
                Console.WriteLine(string.Join(" ", subarr));

                var allarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 4);
                Console.WriteLine(string.Join(" ", allarr));

                var emptyarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 0);
                Console.WriteLine(string.Join(" ", emptyarr));

                Console.WriteLine(ExtractEnding("I love C#", 2));
                Console.WriteLine(ExtractEnding("Nakov", 4));
                Console.WriteLine(ExtractEnding("beer", 4));
                // Console.WriteLine(ExtractEnding("Hi", 100));

                bool is23Prime = CheckPrime(23);
                Console.WriteLine(is23Prime ? "23 is prime." : "23 is not prime.");
                bool is33Prime = CheckPrime(33);
                Console.WriteLine(is33Prime ? "33 is prime." : "33 is not prime.");

                List<Exam> peterExams = new List<Exam>()
                {
                    new SimpleMathExam(2),
                    new CSharpExam(55),
                    new CSharpExam(100),
                    new SimpleMathExam(1),
                    new CSharpExam(0),
                };
                Student peter = new Student("Peter", "Petrov", peterExams);
                double peterAverageResult = peter.CalcAverageExamResultInPercents();
                Console.WriteLine("Average results = {0:p0}", peterAverageResult);
            }
            catch (ArgumentNullException ex)
            {
                PrintErrorMessage(ex);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                PrintErrorMessage(ex);
            }
            catch (InvalidOperationException ex)
            {
                PrintErrorMessage(ex);
            }
            catch (Exception ex)
            {
                PrintErrorMessage(ex);
            }
        }

        public static T[] Subsequence<T>(T[] arr, int startIndex, int count)
        {
            if (arr == null)
            {
                throw new ArgumentNullException("Argument arr cannot be null");
            }

            if (startIndex < 0 || startIndex >= arr.Length)
            {
                throw new ArgumentOutOfRangeException("Invalid start index");
            }

            if (count < 0 || count > arr.Length - startIndex)
            {
                throw new ArgumentOutOfRangeException("Invalid count");
            }

            List<T> result = new List<T>();
            for (int i = startIndex; i < startIndex + count; i++)
            {
                if (arr[i] == null)
                {
                    throw new InvalidOperationException("Elements of the array should not be null");
                }

                result.Add(arr[i]);
            }

            return result.ToArray();
        }

        public static string ExtractEnding(string str, int count)
        {
            if (str == null)
            {
                throw new ArgumentNullException("Str cannot be null");
            }

            if (count < 0 || count > str.Length)
            {
                throw new ArgumentOutOfRangeException("Invalid count");
            }

            StringBuilder result = new StringBuilder();
            for (int i = str.Length - count; i < str.Length; i++)
            {
                result.Append(str[i]);
            }

            return result.ToString();
        }

        public static bool CheckPrime(int number)
        {
            bool isPrime = true;

            if (number < 2)
            {
                return !isPrime;
            }

            for (int divisor = 2; divisor <= Math.Sqrt(number); divisor++)
            {
                if (number % divisor == 0)
                {
                    isPrime = false;
                    break;
                }
            }

            return isPrime;
        }

        private static void PrintErrorMessage(Exception ex)
        {
            Console.WriteLine($"-------------");
            Console.WriteLine($"Calculation failed: \r\n{ex.Message}");
            Console.WriteLine($"-------------");
            Console.WriteLine(ex.StackTrace);
        }
    }
}


text:
import time
from colorama import Fore

from toolset.utils.output_helper import log

class TimeLogger:
    '''
    Class for keeping track of and logging execution times
    for suite actions
    '''

    def __init__(self):
        self.start = time.time()

        self.benchmarking_start = 0
        self.benchmarking_total = 0
        self.database_starting = 0
        self.database_started = 0
        self.build_start = 0
        self.build_total = 0
        self.test_started = 0
        self.accepting_requests = 0
        self.test_start = 0
        self.test_total = 0
        self.verify_start = 0
        self.verify_total = 0
        self.build_logs = []

    @staticmethod
    def output(sec):
        output = ""
        h = sec // 3600
        m = (sec // 60) % 60
        s = sec % 60
        if h > 0:
            output = "%sh" % h
        if m > 0:
            output = output + "%sm " % m
        output = output + "%ss" % s
        return output

    def mark_starting_database(self):
        self.database_starting = time.time()

    def mark_started_database(self):
        self.database_started = int(time.time() - self.database_starting)

    def log_database_start_time(self, log_prefix, file):
        log("Time starting database: %s" % TimeLogger.output(
            self.database_started),
            prefix=log_prefix,
            file=file,
            color=Fore.YELLOW)

    def mark_benchmarking_start(self):
        self.benchmarking_start = time.time()

    def log_benchmarking_end(self, log_prefix, file):
        total = int(time.time() - self.benchmarking_start)
        self.benchmarking_total = self.benchmarking_total + total
        log("Benchmarking time: %s" % TimeLogger.output(total),
            prefix=log_prefix,
            file=file,
            color=Fore.YELLOW)

    def mark_build_start(self):
        self.build_start = time.time()

    def log_build_end(self, log_prefix, file):
        total = int(time.time() - self.build_start)
        self.build_total = self.build_total + total
        log_str = "Build time: %s" % TimeLogger.output(total)
        self.build_logs.append({'log_prefix': log_prefix, 'str': log_str})
        log(log_str, prefix=log_prefix, file=file, color=Fore.YELLOW)

    def log_build_flush(self, file):
        for b_log in self.build_logs:
            log(b_log['str'],
                prefix=b_log['log_prefix'],
                file=file,
                color=Fore.YELLOW)
        self.build_logs = []

    def mark_test_starting(self):
        self.test_started = time.time()

    def mark_test_accepting_requests(self):
        self.accepting_requests = int(time.time() - self.test_started)

    def log_test_accepting_requests(self, log_prefix, file):
        log("Time until accepting requests: %s" % TimeLogger.output(
            self.accepting_requests),
            prefix=log_prefix,
            file=file,
            color=Fore.YELLOW)

    def mark_test_start(self):
        self.test_start = time.time()

    def log_test_end(self, log_prefix, file):
        total = int(time.time() - self.test_start)
        log("Total test time: %s" % TimeLogger.output(total),
            prefix=log_prefix,
            file=file,
            color=Fore.YELLOW)
        log("Total time building so far: %s" % TimeLogger.output(
            self.build_total),
            prefix="tfb: ",
            file=file,
            color=Fore.YELLOW)
        log("Total time verifying so far: %s" % TimeLogger.output(
            self.verify_total),
            prefix="tfb: ",
            file=file,
            color=Fore.YELLOW)
        if self.benchmarking_total > 0:
            log("Total time benchmarking so far: %s" % TimeLogger.output(
                self.benchmarking_total),
                prefix="tfb: ",
                file=file,
                color=Fore.YELLOW)
        running_time = int(time.time() - self.start)
        log("Total execution time so far: %s" %
            TimeLogger.output(running_time),
            prefix="tfb: ",
            file=file,
            color=Fore.YELLOW)

    def mark_verify_start(self):
        self.verify_start = time.time()

    def log_verify_end(self, log_prefix, file):
        total = int(time.time() - self.verify_start)
        self.verify_total = self.verify_total + total
        log("Verify time: %s" % TimeLogger.output(total),
            prefix=log_prefix,
            file=file,
            color=Fore.YELLOW)


text:
var fs = require("fs");
var http = require("http");
var path = require("path");

var sessions = {};
var usersInSessionLimit = 2;

var port = process.env.PORT || 8080;
if (process.argv.length == 3) {
    port = process.argv[2];
}

var serverDir = path.dirname(__filename)
var clientDir = path.join(serverDir, "client/");

var contentTypeMap = {
    ".html": "text/html;charset=utf-8",
    ".js": "text/javascript",
    ".css": "text/css"
};

var server = http.createServer(function (request, response) {
    var headers = {
        "Cache-Control": "no-cache, no-store",
        "Pragma": "no-cache",
        "Expires": "0"
    };

    var parts = request.url.split("/");

    // handle "client to server" and "server to client"
    if (parts[1] == "ctos" || parts[1] == "stoc") {
        var sessionId = parts[2];
        var userId = parts[3];
        if (!sessionId || !userId) {
            response.writeHead(400);
            response.end();
            return;
        }

        if (parts[1] == "stoc") {
            console.log("@" + sessionId + " - " + userId + " joined.");

            headers["Content-Type"] = "text/event-stream";
            response.writeHead(200, headers);
            function keepAlive(resp) {
                resp.write(":\n");
                resp.keepAliveTimer = setTimeout(arguments.callee, 30000, resp);
            }
            keepAlive(response);  // flush headers + keep-alive

            var session = sessions[sessionId];
            if (!session)
                session = sessions[sessionId] = {"users" : {}};

            if (Object.keys(session.users).length > usersInSessionLimit - 1) {
                console.log("user limit for session reached (" + usersInSessionLimit + ")");
                response.write("event:busy\ndata:" + sessionId + "\n\n");
                clearTimeout(response.keepAliveTimer);
                response.end();
                return;
            }

            var user = session.users[userId];
            if (!user) {
                user = session.users[userId] = {};
                for (var pname in session.users) {
                    var esResp = session.users[pname].esResponse;
                    if (esResp) {
                        clearTimeout(esResp.keepAliveTimer);
                        keepAlive(esResp);
                        esResp.write("event:join\ndata:" + userId + "\n\n");
                        response.write("event:join\ndata:" + pname + "\n\n");
                    }
                }
            }
            else if (user.esResponse) {
                user.esResponse.end();
                clearTimeout(user.esResponse.keepAliveTimer);
                user.esResponse = null;
            }
            user.esResponse = response;

            request.on("close", function () {
                for (var pname in session.users) {
                    if (pname == userId)
                        continue;
                    var esResp = session.users[pname].esResponse;
                    esResp.write("event:leave\ndata:" + userId + "\n\n");
                }
                delete session.users[userId];
                clearTimeout(response.keepAliveTimer);
                console.log("@" + sessionId + " - " + userId + " left.");
                console.log("users in session " + sessionId + ": " + Object.keys(session.users).length);
            });

        } else { // parts[1] == "ctos"
            var peerId = parts[4];
            var peer;
            var session = sessions[sessionId];
            if (!session || !(peer = session.users[peerId])) {
                response.writeHead(400, headers);
                response.end();
                return;
            }

            var body = "";
            request.on("data", function (data) { body += data; });
            request.on("end", function () {
                console.log("@" + sessionId + " - " + userId + " => " + peerId + " :");
                // console.log(body);
                var evtdata = "data:" + body.replace(/\n/g, "\ndata:") + "\n";
                peer.esResponse.write("event:user-" + userId + "\n" + evtdata + "\n");
            });

            // to avoid "no element found" warning in Firefox (bug 521301)
            headers["Content-Type"] = "text/plain";
            response.writeHead(204, headers);
            response.end();
        }

        return;
    }

    var url = request.url.split("?", 1)[0];
    var filePath = path.join(clientDir, url);
    if (filePath.indexOf(clientDir) != 0 || filePath == clientDir)
        filePath = path.join(clientDir, "/webrtc_example.html");

    fs.stat(filePath, function (err, stats) {
        if (err || !stats.isFile()) {
            response.writeHead(404);
            response.end("404 Not found");
            return;
        }

        var contentType = contentTypeMap[path.extname(filePath)] || "text/plain";
        response.writeHead(200, { "Content-Type": contentType });

        var readStream = fs.createReadStream(filePath);
        readStream.on("error", function () {
            response.writeHead(500);
            response.end("500 Server error");
        });
        readStream.pipe(response);
    });
});

console.log('The server is listening on port ' + port);
server.listen(port);


text:
/* jspsych-text.js
 * Josh de Leeuw
 *
 * This plugin displays text (including HTML formatted strings) during the experiment.
 * Use it to show instructions, provide performance feedback, etc...
 *
 * documentation: docs.jspsych.org
 *
 *
 */

/**
 * @name Text
 * @param {string} text - A string containing HTML formatted text (no HTML code is necessary, but it is allowed).
 * @param {array|string=} [cont_key=[]] - This array contains the keys that the subject is allowed to press in order to advance to the next trial. Keys can be specified as their numeric key code or as characters (e.g. 'a', 'q'). The default value of an empty array means that all keys will be accepted as valid responses. If the value of 'mouse' is used, then clicking the mouse will advance to the next trial.
 */
jsPsych.plugins.text = (function() {

  var plugin = {};

  plugin.trial = function(display_element, trial) {

    trial.cont_key = trial.cont_key || [];

    // if any trial variables are functions
    // this evaluates the function and replaces
    // it with the output of the function
    trial = jsPsych.pluginAPI.evaluateFunctionParameters(trial);

    // set the HTML of the display target to replaced_text.
    display_element.html(trial.text);

    var after_response = function(info) {

      display_element.html(''); // clear the display

      var trialdata = {
        "rt": info.rt,
        "key_press": info.key
      }

      jsPsych.finishTrial(trialdata);

    };

    var mouse_listener = function(e) {

      var rt = (new Date()).getTime() - start_time;

      display_element.unbind('click', mouse_listener);

      after_response({
        key: 'mouse',
        rt: rt
      });

    };

    // check if key is 'mouse'
    if (trial.cont_key == 'mouse') {
      display_element.click(mouse_listener);
      var start_time = (new Date()).getTime();
    } else {
      jsPsych.pluginAPI.getKeyboardResponse({
        callback_function: after_response,
        valid_responses: trial.cont_key,
        rt_method: 'date',
        persist: false,
        allow_held_key: false
      });
    }

  };

  return plugin;
})();


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Leptosphaeria typharum f. scirpi Boyer & Jacz.

### Remarks
null


text:
.. _security:

========
Security
========

Overview
========

While the Bare Metal service is intended to be a secure application, it is
important to understand what it does and does not cover today.

Deployers must properly evaluate their use case and take the appropriate
actions to secure their environment appropriately. This document is intended to
provide an overview of what risks an operator of the Bare Metal service should
be aware of. It is not intended as a How-To guide for securing a data center
or an OpenStack deployment.

.. TODO: add "Security Considerations for Network Boot" section

.. TODO: add "Credential Storage and Management" section

.. TODO: add "Securing Ironic's REST API" section

.. TODO: add "Multi-tenancy Considerations" section

Firmware security
=================

When the Bare Metal service deploys an operating system image to a server, that
image is run natively on the server without virtualization. Any user with
administrative access to the deployed instance has administrative access to
the underlying hardware.

Most servers' default settings do not prevent a privileged local user from
gaining direct access to hardware devices.  Such a user could modify device or
firmware settings, and potentially flash new firmware to the device, before
deleting their instance and allowing the server to be allocated to another
user.

If the ``[conductor]/automated_clean`` configuration option is enabled (and
the ``[deploy]/erase_devices_priority`` configuration option is not zero),
the Bare Metal service will securely erase all local disk devices within a
machine during instance deletion. However, the service does not ship with
any code that will validate the integrity of, or make any modifications to,
system or device firmware or firmware settings.

Operators are encouraged to write their own hardware manager plugins for the
``ironic-python-agent`` ramdisk.  This should include custom ``clean steps``
that would be run during the `automated cleaning`_ process, as part of Node
de-provisioning. The ``clean steps``
would perform the specific actions necessary within that environment to ensure
the integrity of each server's firmware.

Ideally, an operator would work with their hardware vendor to ensure that
proper firmware security measures are put in place ahead of time. This could
include:

  - installing signed firmware for BIOS and peripheral devices
  - using a TPM (Trusted Platform Module) to validate signatures at boot time
  - booting machines in `UEFI Secure Boot mode`_, rather than BIOS mode, to
    validate kernel signatures
  - disabling local (in-band) access from the host OS to the management controller (BMC)
  - disabling modifications to boot settings from the host OS

Additional references:
  - `automated cleaning`_
  - `trusted boot with partition image`_
  - `UEFI Secure Boot mode`_

.. _automated cleaning: http://docs.openstack.org/developer/ironic/deploy/cleaning.html#automated-cleaning
.. _trusted boot with partition image: http://docs.openstack.org/developer/ironic/deploy/install-guide.html?highlight=txt#trusted-boot-with-partition-image
.. _UEFI Secure Boot mode: http://docs.openstack.org/developer/ironic/drivers/ilo.html?highlight=secure%20boot#uefi-secure-boot-support


text:
#include "arm_math.h"

/**
 * @ingroup groupFilters
 */

/**
 * @addtogroup IIR_Lattice
 * @{
 */

  /**
   * @brief Initialization function for the Q31 IIR lattice filter.
   * @param[in] *S points to an instance of the Q31 IIR lattice structure.
   * @param[in] numStages number of stages in the filter.
   * @param[in] *pkCoeffs points to the reflection coefficient buffer.  The array is of length numStages.
   * @param[in] *pvCoeffs points to the ladder coefficient buffer.  The array is of length numStages+1.
   * @param[in] *pState points to the state buffer.  The array is of length numStages+blockSize.
   * @param[in] blockSize number of samples to process.
   * @return none.
   */

void arm_iir_lattice_init_q31(
  arm_iir_lattice_instance_q31 * S,
  uint16_t numStages,
  q31_t * pkCoeffs,
  q31_t * pvCoeffs,
  q31_t * pState,
  uint32_t blockSize)
{
  /* Assign filter taps */
  S->numStages = numStages;

  /* Assign reflection coefficient pointer */
  S->pkCoeffs = pkCoeffs;

  /* Assign ladder coefficient pointer */
  S->pvCoeffs = pvCoeffs;

  /* Clear state buffer and size is always blockSize + numStages */
  memset(pState, 0, (numStages + blockSize) * sizeof(q31_t));

  /* Assign state pointer */
  S->pState = pState;

}

/**
 * @} end of IIR_Lattice group
 */


text:
<?php

namespace Elasticsearch\Endpoints\Cat;

use Elasticsearch\Endpoints\AbstractEndpoint;

/**
 * Class Count
 *
 * @category Elasticsearch
 * @package  Elasticsearch\Endpoints\Cat
 * @author   Zachary Tong <zach@elastic.co>
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache2
 * @link     http://elastic.co
 */
class Count extends AbstractEndpoint
{
    /**
     * @return string
     */
    public function getURI()
    {
        $index = $this->index;
        $uri   = "/_cat/count";

        if (isset($index) === true) {
            $uri = "/_cat/count/$index";
        }

        return $uri;
    }

    /**
     * @return string[]
     */
    public function getParamWhitelist()
    {
        return array(
            'local',
            'master_timeout',
            'h',
            'help',
            'v',
            's'
        );
    }

    /**
     * @return string
     */
    public function getMethod()
    {
        return 'GET';
    }
}