text:
namespace infobars {
class InfoBar;
}

namespace confirm_infobar_overlays {

// Configuration object for OverlayRequests for the banner UI for an InfoBar
// with a ConfirmInfoBarDelegate.
class ConfirmBannerRequestConfig
    : public OverlayRequestConfig<ConfirmBannerRequestConfig> {
 public:
  ~ConfirmBannerRequestConfig() override;

  // The title text.
  std::u16string title_text() const { return title_text_; }

  // The message text.
  std::u16string message_text() const { return message_text_; }

  // The button label text.
  std::u16string button_label_text() const { return button_label_text_; }

  // The infobar's icon image.
  gfx::Image icon_image() const { return icon_image_; }

  // Whether to present the Infobar's banner for a longer amount of time.
  bool is_high_priority() const { return is_high_priority_; }

  // Whether to use a background tint for the icon image.
  bool use_icon_background_tint() const { return use_icon_background_tint_; }

 private:
  OVERLAY_USER_DATA_SETUP(ConfirmBannerRequestConfig);
  explicit ConfirmBannerRequestConfig(infobars::InfoBar* infobar);

  // OverlayUserData:
  void CreateAuxiliaryData(base::SupportsUserData* user_data) override;

  // The InfoBar causing this banner.
  infobars::InfoBar* infobar_ = nullptr;
  // Configuration data extracted from |infobar_|'s confirm delegate.
  std::u16string title_text_;
  std::u16string message_text_;
  std::u16string button_label_text_;
  gfx::Image icon_image_;
  // True if the icon image should apply a background tint.
  bool use_icon_background_tint_ = true;
  // True if the infobar's banner should be presented for a longer time.
  bool is_high_priority_ = false;
};

}  // namespace confirm_infobar_overlays

#endif  // IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_INFOBAR_BANNER_CONFIRM_INFOBAR_BANNER_OVERLAY_REQUEST_CONFIG_H_

redpajama_set_name: RedPajamaGithub


text:
@interface Level1 : Level

@end


text:
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { mapToCssModules, tagPropType } from './utils';

const propTypes = {
  children: PropTypes.node,
  tag: tagPropType,
  className: PropTypes.string,
  cssModule: PropTypes.object,
  valid: PropTypes.bool,
  tooltip: PropTypes.bool
};

const defaultProps = {
  tag: 'div',
  valid: undefined
};

const FormFeedback = (props) => {
  const {
    className,
    cssModule,
    valid,
    tooltip,
    tag: Tag,
    ...attributes
  } = props;

  const validMode = tooltip ? 'tooltip' : 'feedback';

  const classes = mapToCssModules(
    classNames(
      className,
      valid ? `valid-${validMode}` : `invalid-${validMode}`
    ),
    cssModule
  );

  return <Tag {...attributes} className={classes} />;
};

FormFeedback.propTypes = propTypes;
FormFeedback.defaultProps = defaultProps;

export default FormFeedback;


text:
// Copyright (c) 2013-present, febit.org. All Rights Reserved.
package org.febit.wit.util.bean;

import org.febit.wit.util.ClassUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author zqq90
 */
public class FieldInfoResolver {

    private final Class<?> beanType;
    private final Map<String, FieldInfo> fieldInfos;

    private FieldInfoResolver(Class<?> beanClass) {
        this.beanType = beanClass;
        this.fieldInfos = new HashMap<>();
    }

    public static Stream<FieldInfo> resolve(Class<?> beanClass) {
        return new FieldInfoResolver(beanClass).resolve();
    }

    @SuppressWarnings({
            "squid:S3776" // Cognitive Complexity of methods should not be too high
    })
    private Stream<FieldInfo> resolve() {
        for (Field field : beanType.getFields()) {
            if (!ClassUtil.isStatic(field)) {
                registerField(field);
            }
        }
        for (Method method : beanType.getMethods()) {
            if (ClassUtil.isStatic(method)
                    || method.getDeclaringClass() == Object.class) {
                continue;
            }
            int argsCount = method.getParameterCount();
            String methodName = method.getName();
            int methodNameLength = methodName.length();
            if (argsCount == 0
                    && method.getReturnType() != void.class) {
                if (methodNameLength > 3
                        && methodName.startsWith("get")) {
                    registerGetterMethod(cutFieldName(methodName, 3), method);
                } else if (methodNameLength > 2
                        && methodName.startsWith("is")) {
                    registerGetterMethod(cutFieldName(methodName, 2), method);
                }
            } else if (argsCount == 1
                    && methodNameLength > 3
                    && method.getReturnType() == void.class
                    && methodName.startsWith("set")) {
                registerSetterMethod(cutFieldName(methodName, 3), method);
            }
        }
        return fieldInfos.values().stream();
    }

    private FieldInfo getOrCreateFieldInfo(String name) {
        return fieldInfos.computeIfAbsent(name, key -> new FieldInfo(beanType, key));
    }

    private void registerField(Field field) {
        getOrCreateFieldInfo(field.getName()).field = field;
    }

    private void registerGetterMethod(String name, Method method) {
        getOrCreateFieldInfo(name).getterMethod = method;
    }

    private void registerSetterMethod(String name, Method method) {
        getOrCreateFieldInfo(name).setterMethod = method;
    }

    static String cutFieldName(final String string, final int from) {
        final int nextIndex = from + 1;
        final int len = string.length();
        if (len > nextIndex) {
            char c = string.charAt(nextIndex);
            if (c >= 'A' && c <= 'Z') {
                return string.substring(from);
            }
        }
        char[] buffer = new char[len - from];
        string.getChars(from, len, buffer, 0);
        char c = buffer[0];
        if (c >= 'A' && c <= 'Z') {
            buffer[0] = (char) (c + 0x20);
        }
        return new String(buffer);
    }
}


text:
div.example {
	margin-top: 3em;
	margin-bottom: 3em;
	border: 1px solid #ccc;
}

div.example h1, div.example h2, div.example h3, div.example h4, div.example h5 {
	margin-bottom: 0.5em;
}

div.example h1, div.example h2 {
	background-color: #edf3fe;
	padding: 0.5em;
}

div.example h3, div.example h4 {
	padding-left: 3em;
	margin: 1em 0 0 0;
	background-color: inherit;
}

div.example p, div.example li {
	line-height: 1.4em;
	font-size: 120%;
}

div.example p {
	padding: 0.5em 3em;
}

div.example li {
	list-style: disc;
	padding-bottom: 1em;
}

div.example li.last {
	padding-bottom: 0em;
}

div.example ul {
	list-style: disc;
	padding-left: 3em;
	margin-left: 3em;
	margin-top: 1em;
	margin-bottom: 1em;
}

div.example td, div.example th {
	border: 0;
}

div.example th {
	background-color: inherit;
	font-size: small;
    background-color: #edf3fe;
	color: black;
	font-weight: normal;
}

div.example table {
	margin-left: 3em;
	margin-right: 3em;
	width: 93%;
}

div.example .border td, div.example .border th {
	border: 1px solid #ccc;
	padding: 0.3em;
	font-size: small;
}

div.example .border caption {
	padding-left: 2.5em;
}


text:
Puppet::Type.type(:pg_database).provide(:default) do

  desc "A default pg_database provider which just fails."

  def create
    return false
  end

  def destroy
    return false
  end

  def exists?
    fail('This is just the default provider for pg_database, all it does is fail')
  end

end


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

<title>StartCloud</title>
<meta name="date" content="2016-01-21">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

de.orolle.bigsense.server

Class StartCloud

java.lang.Object

org.vertx.java.platform.Verticle

de.orolle.bigsense.server.StartCloud

public class StartCloud
extends org.vertx.java.platform.Verticle

Main for BigSenseWeb. It is executed as Vert.x has loaded this class and than instantiates it.

Author:

Oliver Rolle, Martin Hellwig

Field Summary

Fields

Modifier and Type
Field and Description

private java.lang.String
apkWriterPath

File System Folders for apk files.

private java.lang.String
authAddress

Event bus addresses for authentication.

private java.util.HashMap<java.lang.Integer,java.lang.Boolean>
listenPorts

Used Server Ports.

static org.vertx.java.core.logging.Logger
log

Vert.x logger

private long
reverse_connection_timeout

Latest time to close a reverse connection.

private static java.lang.String
SSH_SERVER_ADDRESS

The Constant SSH_SERVER_ADDRESS.

private java.lang.String
sshClientAddress

Event bus addresses for ssh client.

private static java.lang.String
WEB_ADDRESS

The Constant WEB_ADDRESS.

private java.lang.String
webAuthSSID

Session id of logged in user.

Fields inherited from class org.vertx.java.platform.Verticle

container, vertx

Constructor Summary

Constructors

Constructor and Description

StartCloud()

Method Summary

Methods

Modifier and Type
Method and Description

private void
deploySSH(org.vertx.java.core.Handler<org.vertx.java.core.AsyncResult<? extends java.lang.Object>> handler)

Deploys the SSHVerticle as worker in Vert.x environment, therefore providing
 SSH functionality for the update process by BigSenseUpdater.

private void
deployWebAuthentication(org.vertx.java.core.Handler<org.vertx.java.core.AsyncResult<? extends java.lang.Object>> handler)

Deploys Authentication Service for web-interface.

private void
makeReverseConnectionServer(org.vertx.java.core.net.NetSocket androidSSH,
                           int remotePort,
                           org.vertx.java.core.buffer.Buffer storeBuffer)

Creates a ReverseConnectionServer which waits on SSHClient to connect.

void
start(org.vertx.java.core.Future<java.lang.Void> startedResult)

Initalizes and start all components of BigSenseWeb.

Methods inherited from class org.vertx.java.platform.Verticle

getContainer, getVertx, setContainer, setVertx, start, stop

Methods inherited from class java.lang.Object

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

Field Detail

log

public static org.vertx.java.core.logging.Logger log

Vert.x logger

apkWriterPath

private java.lang.String apkWriterPath

File System Folders for apk files.

authAddress

private java.lang.String authAddress

Event bus addresses for authentication.

sshClientAddress

private java.lang.String sshClientAddress

Event bus addresses for ssh client.

SSH_SERVER_ADDRESS

private static final java.lang.String SSH_SERVER_ADDRESS

The Constant SSH_SERVER_ADDRESS.

See Also:

Constant Field Values

WEB_ADDRESS

private static final java.lang.String WEB_ADDRESS

The Constant WEB_ADDRESS.

See Also:

Constant Field Values

webAuthSSID

private java.lang.String webAuthSSID

Session id of logged in user.

reverse_connection_timeout

private final long reverse_connection_timeout

Latest time to close a reverse connection.

See Also:

Constant Field Values

listenPorts

private java.util.HashMap<java.lang.Integer,java.lang.Boolean> listenPorts

Used Server Ports.

Constructor Detail

StartCloud

public StartCloud()

Method Detail

start

public void start(org.vertx.java.core.Future<java.lang.Void> startedResult)

Initalizes and start all components of BigSenseWeb.

Overrides:

start in class org.vertx.java.platform.Verticle

Parameters:

startedResult - the started result

deploySSH

private void deploySSH(org.vertx.java.core.Handler<org.vertx.java.core.AsyncResult<? extends java.lang.Object>> handler)

Deploys the SSHVerticle as worker in Vert.x environment, therefore providing
 SSH functionality for the update process by BigSenseUpdater.

Parameters:

handler - Handler is called after deployment

deployWebAuthentication

private void deployWebAuthentication(org.vertx.java.core.Handler<org.vertx.java.core.AsyncResult<? extends java.lang.Object>> handler)

Deploys Authentication Service for web-interface.
 (IT IS NOT USED BY WEB)

Parameters:

handler - Handler is called after deployment

makeReverseConnectionServer

private void makeReverseConnectionServer(org.vertx.java.core.net.NetSocket androidSSH,
                               int remotePort,
                               org.vertx.java.core.buffer.Buffer storeBuffer)

Creates a ReverseConnectionServer which waits on SSHClient to connect.
 The data which received on this server is passed to the TCP connection made by the
 Android Smartphone.

Parameters:

androidSSH - Android Connection

remotePort - Port to listen on for SSHClient connection

storeBuffer - the store buffer

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<!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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>wlan-decoder-java: fr.bmartel.protocol.wlan.frame.management.element.impl.SupportedRateElement Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

wlan-decoder-java
    1.0

Main Page

Packages

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Namespaces Functions Variables Pages

fr

bmartel

protocol

wlan

frame

management

element

impl

SupportedRateElement

Public Member Functions |
Static Public Attributes |
List of all members

fr.bmartel.protocol.wlan.frame.management.element.impl.SupportedRateElement Class Reference

Inheritance diagram for fr.bmartel.protocol.wlan.frame.management.element.impl.SupportedRateElement:

<map name="fr_8bmartel_8protocol_8wlan_8frame_8management_8element_8impl_8_supported_rate_element_inherit__map" id="fr_8bmartel_8protocol_8wlan_8frame_8management_8element_8impl_8_supported_rate_element_inherit__map">
<area shape="rect" id="node2" href="classfr_1_1bmartel_1_1protocol_1_1wlan_1_1frame_1_1management_1_1element_1_1_wlan_element_abstr.html" title="fr.bmartel.protocol.wlan.frame.management.element.\lWlanElementAbstr" alt="" coords="396,5,724,51"/><area shape="rect" id="node4" href="interfacefr_1_1bmartel_1_1protocol_1_1wlan_1_1frame_1_1management_1_1element_1_1_i_wlan_element.html" title="fr.bmartel.protocol.wlan.frame.management.element.\lIWlanElement" alt="" coords="5,5,333,51"/><area shape="rect" id="node6" href="interfacefr_1_1bmartel_1_1protocol_1_1wlan_1_1frame_1_1management_1_1element_1_1inter_1_1_i_supported_rate_element.html" title="fr.bmartel.protocol.wlan.frame.management.element.inter.\lISupportedRateElement" alt="" coords="381,74,739,121"/></map>
[legend]

Collaboration diagram for fr.bmartel.protocol.wlan.frame.management.element.impl.SupportedRateElement:

<map name="fr_8bmartel_8protocol_8wlan_8frame_8management_8element_8impl_8_supported_rate_element_coll__map" id="fr_8bmartel_8protocol_8wlan_8frame_8management_8element_8impl_8_supported_rate_element_coll__map">
<area shape="rect" id="node2" href="classfr_1_1bmartel_1_1protocol_1_1wlan_1_1frame_1_1management_1_1element_1_1_wlan_element_abstr.html" title="fr.bmartel.protocol.wlan.frame.management.element.\lWlanElementAbstr" alt="" coords="396,5,724,51"/><area shape="rect" id="node4" href="interfacefr_1_1bmartel_1_1protocol_1_1wlan_1_1frame_1_1management_1_1element_1_1_i_wlan_element.html" title="fr.bmartel.protocol.wlan.frame.management.element.\lIWlanElement" alt="" coords="5,5,333,51"/><area shape="rect" id="node6" href="interfacefr_1_1bmartel_1_1protocol_1_1wlan_1_1frame_1_1management_1_1element_1_1inter_1_1_i_supported_rate_element.html" title="fr.bmartel.protocol.wlan.frame.management.element.inter.\lISupportedRateElement" alt="" coords="381,74,739,121"/></map>
[legend]

Public Member Functions

 	SupportedRateElement (byte[] data)

int 	getMaxRate ()

byte 	getElementId ()

byte[] 	getDataRate ()

 Public Member Functions inherited from fr.bmartel.protocol.wlan.frame.management.element.WlanElementAbstr

 	WlanElementAbstr (byte[] data)

byte[] 	getData ()

Static Public Attributes

static final int 	id = 1

Detailed Description

Define data rate

element id : 1 Byte

length : 1 Byte

data : 1 - 8 Bytes

Author

Bertrand Martel

Member Function Documentation

          byte fr.bmartel.protocol.wlan.frame.management.element.impl.SupportedRateElement.getElementId
          (
          )

retrieve element id

Returns

Implements fr.bmartel.protocol.wlan.frame.management.element.IWlanElement.

          int fr.bmartel.protocol.wlan.frame.management.element.impl.SupportedRateElement.getMaxRate
          (
          )

retrieve max rate in Mbps

Returns

The documentation for this class was generated from the following file:

/home/abathur/Bureau/wlandecoder/wlandecoder/src/fr/bmartel/protocol/wlan/frame/management/element/impl/SupportedRateElement.java

<address class="footer">
Generated on Tue May 5 2015 23:30:27 for wlan-decoder-java by

 1.8.4
</address>


text:
"""Tests for parallize."""
import os
from absl import logging
from absl.testing import absltest
from PIL import Image
from PIL import ImageFile
import parallelize
import convert

TESTDATA_DIR = 'testdata'

class ParallelizeTests(absltest.TestCase):

  def setUp(self):
    self.testdata_dir = os.path.join(os.getcwd(), TESTDATA_DIR)

    # Ensure setting is set to default for each test.
    try:
      ImageFile.LOAD_TRUNCATED_IMAGES = False
    except AttributeError as e:
      logging.warning('Are you using PILLOW and not a very old version of PIL? '
                      'Unable to force load of truncated image files: %s', e)

  def testGetAndConvertOneImageFromLocalFile(self):
    # Test parallelization of a single image succeeds.
    testfile_path = os.path.join(self.testdata_dir,
                                 'Googleplex-Patio-Aug-2014.JPG')
    expected_output_image_size = (100, 100)
    image_convert_settings = convert.ImageConvertSettings(
        img_format='png', width=100, height=100)

    output_image, status = parallelize.get_and_convert_image(
        testfile_path, image_convert_settings)
    del status  # linter

    self.assertSameElements(output_image.size, expected_output_image_size)

  def testGetAndConvertOneImageMissingFile(self):
    # Returns None if can't open file.
    testfile_path = os.path.join(self.testdata_dir,
                                 'file_doesnt_exist.png')
    image_convert_settings = convert.ImageConvertSettings(
        img_format='png', width=100, height=100)

    output_image, status = parallelize.get_and_convert_image(
        testfile_path, image_convert_settings)
    del status  # linter

    self.assertEqual(output_image, None)

  def testGetAndConvertOneImageNotImageFile(self):
    # Returns None if can't open file.
    testfile_path = os.path.join(self.testdata_dir,
                                 'attributions.txt')
    image_convert_settings = convert.ImageConvertSettings(
        img_format='png', width=100, height=100)

    output_image, status = parallelize.get_and_convert_image(
        testfile_path, image_convert_settings)
    del status  # linter

    self.assertEqual(output_image, None)

  def testGetAndConvertTruncatedImageFail(self):
    # Should note fail but return None when PIL fails on truncated image.
    # To test image truncation, we actually need to write a file to disk.
    img_filepath = os.path.join(self.testdata_dir, 'test_img.png')

    try:
      orig_img = Image.new('RGBA', (500, 500))
      orig_img.save(img_filepath)
      filesize = os.path.getsize(img_filepath)

      with open(img_filepath, 'r+') as img_on_disk:
        img_on_disk.truncate(filesize - 100)

      image_convert_settings = convert.ImageConvertSettings(
          img_format='png', width=100, height=100)

      output_image_with_status = parallelize.get_and_convert_image(
          img_filepath, image_convert_settings)

      self.assertIsNone(output_image_with_status[0])
      self.assertTrue(output_image_with_status[1])  # Has error message.
    except:
      raise
    finally:
      # Cleanup.
      if os.path.isfile(img_filepath):
        os.remove(img_filepath)

  def testGetAndConvertAllowTruncatedImage(self):
    # Should return a converted image if we tolerate truncated images.
    # To test image truncation, we actually need to write a file to disk.
    img_filepath = os.path.join(self.testdata_dir, 'test_img.png')

    try:
      orig_img = Image.new('RGBA', (500, 500))
      orig_img.save(img_filepath)
      filesize = os.path.getsize(img_filepath)

      with open(img_filepath, 'r+') as img_on_disk:
        img_on_disk.truncate(filesize - 100)

      image_convert_settings = convert.ImageConvertSettings(
          img_format='png', width=100, height=100)

      output_image_with_status = parallelize.get_and_convert_image(
          img_filepath, image_convert_settings, allow_truncated_images=True)

      self.assertEqual(output_image_with_status[0].size, (100, 100))
    except:
      raise
    finally:
      # Cleanup.
      if os.path.isfile(img_filepath):
        os.remove(img_filepath)

  def testGetAndConvertOneImageBadUrl(self):
    # Returns None if can't open file.
    testfile_path = 'http://www.google.com'
    image_convert_settings = convert.ImageConvertSettings(
        img_format='png', width=100, height=100)

    output_image, status = parallelize.get_and_convert_image(
        testfile_path, image_convert_settings)
    del status  # linter

    self.assertEqual(output_image, None)

  def testParallelizeConvertImagesFromLocalfile(self):
    # Test parallelization with multiple reads of the same image file produces
    # expected output images with correct sizes.
    testfile_path = os.path.join(self.testdata_dir,
                                 'Googleplex-Patio-Aug-2014.JPG')
    testfile_locations = [testfile_path] * 3
    expected_output_image_sizes = [(100, 100)] * 3
    image_convert_settings = convert.ImageConvertSettings(
        img_format='png', width=100, height=100)

    output_imgs_with_status = parallelize.get_and_convert_images_parallel(
        testfile_locations, image_convert_settings, verbose=1)

    resulting_image_sizes = []
    for (image, status) in output_imgs_with_status:
      del status  # linter
      resulting_image_sizes.append(image.size)

    self.assertSameElements(resulting_image_sizes, expected_output_image_sizes)

  def testParallelizeConvertWithFailures(self):
    # 3 images are attempted, the last one should fail.
    testfile_path = os.path.join(self.testdata_dir,
                                 'Googleplex-Patio-Aug-2014.JPG')
    bad_testfile_path = os.path.join(self.testdata_dir,
                                     'attributions.txt')
    testfile_locations = [testfile_path, testfile_path, bad_testfile_path]
    expected_image_size = (100, 100)

    image_convert_settings = convert.ImageConvertSettings(
        img_format='png', width=100, height=100)

    output_images = parallelize.get_and_convert_images_parallel(
        testfile_locations, image_convert_settings, verbose=1)

    first_converted_img = output_images[0][0]
    second_converted_img = output_images[1][0]
    third_converted_img = output_images[2][0]
    self.assertSameElements(first_converted_img.size, expected_image_size)
    self.assertSameElements(second_converted_img.size, expected_image_size)
    self.assertEqual(third_converted_img, None)  # Failed conversion.

  def testConvertDefaultImageSucceeds(self):
    testfile_path = os.path.join(self.testdata_dir,
                                 'Googleplex-Patio-Aug-2014.JPG')
    image_convert_settings = convert.ImageConvertSettings(
        img_format='png', width=100, height=100)

    img = parallelize.convert_default_image(testfile_path,
                                            image_convert_settings)

    self.assertEqual(img.size, (100, 100))

  def testConvertDefaultImageFails(self):
    testfile_path = os.path.join(self.testdata_dir, 'attributions.txt')
    image_convert_settings = convert.ImageConvertSettings(
        img_format='png', width=100, height=100)

    with self.assertRaises(IOError):
      parallelize.convert_default_image(testfile_path, image_convert_settings)

if __name__ == '__main__':
  absltest.main()


text:
{L_FORUM}{L_COLON} {FORUM_NAME}

<form method="post" id="mcp" action="{S_MCP_ACTION}">

			{TOTAL_TOPICS}

				 • {PAGE_NUMBER}

{L_TOPICS}

{L_REPLIES}

{L_LAST_POST}

{L_MARK}

					[ {L_SELECT_MERGE} ]

					{topicrow.TOPIC_TITLE}

					{topicrow.UNAPPROVED_IMG}
					{topicrow.DELETED_IMG}
					{REPORTED_IMG}
					 [ {L_DELETE_SHADOW_TOPIC} ]

						{topicrow.ATTACH_ICON_IMG}
						{L_LAST_POST} {L_POST_BY_AUTHOR} {topicrow.LAST_POST_AUTHOR_FULL} « {topicrow.LAST_POST_TIME}

					{L_REPLIES}{L_COLON} {topicrow.REPLIES}

{topicrow.pagination.PAGE_NUMBER}

{L_ELLIPSIS}

{topicrow.pagination.PAGE_NUMBER}

						{topicrow.ATTACH_ICON_IMG}
						{L_POST_BY_AUTHOR} {topicrow.TOPIC_AUTHOR_FULL} » {topicrow.FIRST_POST_TIME}

{topicrow.REPLIES} <dfn>{L_REPLIES}</dfn>

<dfn>{L_LAST_POST} </dfn>{L_POST_BY_AUTHOR} {topicrow.LAST_POST_AUTHOR_FULL}
{topicrow.LAST_POST_TIME}

					<input type="checkbox" name="topic_id_list[]" value="{topicrow.TOPIC_ID}" checked="checked" />

{L_NO_TOPICS}

	<fieldset class="display-options">
		{L_DISPLAY_TOPICS}{L_COLON} {S_SELECT_SORT_DAYS}
		{L_SORT_BY} {S_SELECT_SORT_KEY}
		{S_SELECT_SORT_DIR}
		<input type="submit" name="sort" value="{L_GO}" class="button2" />
	</fieldset>

			{TOTAL_TOPICS}

				 • {PAGE_NUMBER}

<fieldset class="display-actions">

	<select name="action">
		<option value="" selected="selected">{L_SELECT_ACTION}</option>
		<option value="delete_topic">{L_DELETE}</option>
		<option value="restore_topic">{L_RESTORE}</option>
		<option value="merge_topics">{L_MERGE}</option>
		<option value="move">{L_MOVE}</option>
		<option value="fork">{L_FORK}</option>
		<option value="lock">{L_LOCK}</option><option value="unlock">{L_UNLOCK}</option>
		<option value="resync">{L_RESYNC}</option>
		<option value="make_normal">{L_MAKE_NORMAL}</option>
		<option value="make_sticky">{L_MAKE_STICKY}</option>

			<option value="make_announce">{L_MAKE_ANNOUNCE}</option>
			<option value="make_global">{L_MAKE_GLOBAL}</option>

	</select>
	<input class="button2" type="submit" value="{L_SUBMIT}" />

{L_MARK_ALL} :: {L_UNMARK_ALL}

	{S_FORM_TOKEN}
</fieldset>
</form>


text:
package com.UtilityClasses;

import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.util.Log;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * Created by MacMini on 7/18/16.
 */

public class Files {
    private Files(){}

    /*
        New users are assigned new files for tagging, indexing, and syncing purposes. Method checks to see if those files are made, if not then they are generated for the user.
         */
    public static void checkForAppFiles(final File filesDir, final AssetManager assets, final ContentResolver contentResolver){
        new Thread(){
            String line;
            InputStreamReader inputStream;
            BufferedReader reader;
            BufferedWriter writer;

            public void run(){
                File filesXML = new File(filesDir, XML.XML_FILE);
                if (! filesXML.exists() ) {			 // creats files file. It indexes all the files along with their associated tags, pictures and other info.
                    try {
                        filesXML.createNewFile();

                        inputStream = new InputStreamReader(assets.open(XML.XML_FILE));

                        reader = new BufferedReader(inputStream);
                        writer  = new BufferedWriter(new FileWriter(filesXML));

                        line = (reader.readLine());
                        while (line != null) {

                            writer.write(line + "\n");
                            line = (reader.readLine());
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        try { // closes streams in order they were open in case there's an exception to catch. Minimizes the risk of memory leak.
                            inputStream.close();
                            reader.close();
                            writer.close();
                        }catch (IOException ignored){

                        }
                    }
                }

                File changesXML = new File(filesDir, "Changes_" + Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) + ".xml");
                if (! changesXML.exists() ) {		// creates a changes xml file

                    try {       // writes file for changes. Used for suyncing
                        changesXML.createNewFile();
                        inputStream = new InputStreamReader(assets.open("Changes.xml"));
                        reader = new BufferedReader(inputStream);

                        writer  = new BufferedWriter(new FileWriter(changesXML));

                        line =(reader.readLine());
                        while (line != null) {
                            writer.write(line + "\n");
                            line = (reader.readLine());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        try { // closes streams in order they were open in case theres an exception to catch. Minimizes the risk of memory leak.
                            inputStream.close();
                            reader.close();
                            writer.close();
                        }catch (IOException ignored){

                        }
                    }
                }

            }
        }.start();
    }

    public static void deleteMultipleEntries(final Context context, final ArrayList<String> deletedFilesArr){

        // deletes all references of files from xml file
        new Thread(new Runnable() {
            @Override
            public void run() {

                XML.deleteMultipleEntriesFromXML(context.getFilesDir(), deletedFilesArr);
            }
        }).start();

        // deletes all references of files in file system
        new Thread(new Runnable() {
            @Override
            public void run() {

                for(String file: deletedFilesArr){
                    Files.deleteEntry(context.getFilesDir(), file);
                }
            }
        }).start();

    }

    public static void deleteEntry(File filesDir, String filename){         // takes filesDir and filename without extension and deletes all files with name  passed that were used to store txt, photos and audio.
       if (filename.contains(".txt")){
           filename = filename.substring(0, filename.indexOf('.'));
       }

        StringBuilder txtFilename = new StringBuilder(filename);
        StringBuilder mpegFilename = new StringBuilder(filename);
        StringBuilder pngFilename = new StringBuilder(filename);

        txtFilename.append(".txt");
        mpegFilename.append(".mpeg4");

        File txtFile = new File(filesDir, txtFilename.toString());
        txtFile.delete();

        File audioFile = new File(filesDir, mpegFilename.toString());
        audioFile.delete();

        int photoNum = 1;
        pngFilename.append('(');
        pngFilename.append(photoNum);
        pngFilename.append(").png");
        File photoFile = new File(filesDir, pngFilename.toString());
        while (photoFile.exists() ) {
            photoFile.delete();
            photoNum++;
            pngFilename.delete(0, pngFilename.length());
            pngFilename.append('(');
            pngFilename.append(photoNum);
            pngFilename.append(").png");

            photoFile = new File(filesDir, pngFilename.toString());
        }

        XML.deleteEntryFromXML(filesDir, filename);
    }

    public static String renameFiles(File filesDir, String oldFilename, String newFileName){
        StringBuilder old_txtFilename = new StringBuilder(oldFilename);
        StringBuilder old_mpegFilename = new StringBuilder(oldFilename);
        StringBuilder old_pngFilename = new StringBuilder(oldFilename);

        old_txtFilename.append(".txt");
        old_mpegFilename.append(".mpeg4");

        newFileName = findUnusedFileName(filesDir, newFileName);        //  tries to find an unused filename with the same starting sequence as the "newFileName" String

        StringBuilder new_txtFilename = new StringBuilder(newFileName);
        StringBuilder new_mpegFilename = new StringBuilder(newFileName);
        StringBuilder new_pngFilename = new StringBuilder(newFileName);

        new_txtFilename.append(".txt");
        new_mpegFilename.append(".mpeg4");

        File txtFile = new File(filesDir, old_txtFilename.toString());
        txtFile.renameTo(new File(filesDir, new_txtFilename.toString()));
        File mpegFile = new File(filesDir, old_mpegFilename.toString());
        mpegFile.renameTo(new File(filesDir, new_mpegFilename.toString()));

        int photoNum = 1;
        StringBuilder photoNumExtension = new StringBuilder("");

        photoNumExtension.append('(');
        photoNumExtension.append(photoNum);
        photoNumExtension.append(").png");

        old_pngFilename.append(photoNumExtension);
        new_pngFilename.append(photoNumExtension);

        File photoFile = new File(filesDir, old_pngFilename.toString());
        while (photoFile.exists() ) {
            photoFile.renameTo(new File(filesDir, new_pngFilename.toString()));
            photoNum++;
            photoNumExtension.delete(0, photoNumExtension.length());
            old_pngFilename.delete(0, old_pngFilename.length());
            new_pngFilename.delete(0, new_pngFilename.length());

            photoNumExtension.append('(');
            photoNumExtension.append(photoNum);
            photoNumExtension.append(").png");

            old_pngFilename.append(oldFilename);
            old_pngFilename.append(photoNumExtension);

            new_pngFilename.append(newFileName);
            new_pngFilename.append(photoNumExtension);

            photoFile = new File(filesDir, old_pngFilename.toString());
        }

        Log.i(oldFilename, "has been renamed to " + newFileName);

        return newFileName;

    }

    public static ArrayList<String> getContactSuggestions(Context context){
        ArrayList<String> tagSuggestionsArrList = new ArrayList<>();

        ContentResolver cr = context.getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

        if (cur != null && cur.getCount() > 0) {
            while (cur.moveToNext()) {
                if (!cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).equals("")) {
                    tagSuggestionsArrList.add(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
                }
            }
            cur.close();
        }

        return tagSuggestionsArrList;
    }

    public static void saveEntryText(String filename, Context context, EditText entryTextTV) throws FileNotFoundException {
        String txt = ".txt";

        DataOutputStream dos = new DataOutputStream(context.openFileOutput(filename + txt, Context.MODE_PRIVATE));

        WeakReference<DataOutputStream> dosWeak = new WeakReference<>(dos);
        try {
            dosWeak.get().writeUTF(filename.trim() + "\n");
            dosWeak.get().writeUTF(entryTextTV.getText().toString());
            dosWeak.get().flush();
            dosWeak.get().close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static String createNewEntryFile(String filename, Context context) throws  IOException{
        String txt = ".txt";
            filename.replaceAll(",", " ");
            filename.replaceAll("'", "");

            filename = findUnusedFileName(context.getFilesDir(), filename);
            File entryFile = new File(context.getFilesDir(), filename + txt);

            entryFile.createNewFile();

        return filename;
    }

    private static String findUnusedFileName(File filesDir, String desiredFilename){
        if (desiredFilename.equals(""))
            desiredFilename = "Temp".concat(MiscMethods.randomizedExtension());

        String txt = ".txt";
        File entryFile = new File(filesDir, desiredFilename + txt);
        int counter = 1;
        while (entryFile.exists()) {
            String temp =  desiredFilename + Integer.toString(counter);
            entryFile = new File(filesDir, temp + txt);
            counter++;
        }
        return desiredFilename;
    }

    public static void saveNewEntryInfoToPreferences(SharedPreferences sp, String filename, ArrayList<CharSequence> arrTags, boolean isFave){
        String txt = ".txt";
        sp.edit().putString("NEWFILENAME", filename.concat(txt)).apply();
        if (arrTags.size() >0)
            sp.edit().putString("NEWFILETAG1", arrTags.get(0).toString()).apply();

        if (arrTags.size() >1)
            sp.edit().putString("NEWFILETAG2", arrTags.get(1).toString()).apply();
        if (arrTags.size() >2)
            sp.edit().putString("NEWFILETAG3", arrTags.get(2).toString()).apply();

        sp.edit().putBoolean("NEWFILEFAVE", isFave).apply();

    }

    public static void removeNewEntryFromPreference(SharedPreferences sp){
        sp.edit().remove("NEWFILENAME").apply();
        sp.edit().remove("NEWFILETAG1").apply();
        sp.edit().remove("NEWFILETAG2").apply();
        sp.edit().remove("NEWFILETAG3").apply();
        sp.edit().remove("NEWFILEFAVE").apply();

    }

    public static ArrayList<File> getFilesWithExtension(File filesDir, final String extension){
        ArrayList<File> filesArrayList = new ArrayList<>();

        FilenameFilter filter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                return filename.endsWith(extension);
            }
        };
        File[]  entryFileArray = filesDir.listFiles(filter);

        Collections.addAll(filesArrayList, entryFileArray);
        return  filesArrayList;
    }

    public static void deleteFilesWithNoName(ArrayList<File> filesArrayList, String extension){
        for(File file: filesArrayList){
            String filename = file.getName().replace(extension, "");
            int length = filename.length();

            if ((length <= 4 && filename.charAt(0) =='(') || length == 0){
                file.delete();
            }
            else if (filename.substring(length - 3, length).equals("(0)")){
                file.delete();

        }
    }

    }

    public static boolean doesFileExist(File filesDirs, String filename, String extension){
        File file = new File(filesDirs, filename + extension);
        return file.exists();
    }

    /*
        creates a File object to see how many characters are in the file. if length is 1 then there is one character.

        Due to bad programming this App writes the filename in the file using .writeUTF() and as such there are characters that don't do anything in the beelining of the file and after the
        writing of the filename. The blocks of code that remove characters from the object summaryBuilder is there to mitigate this. Plans to change this oversight are in the way but
        to support legacy code the deletes will still have to remain.

        readLength is the length of the charBuffer. This limits over-reading characters for situations where only some of the text is necessary (ie summarizing a file)
     */

    public static String getTextFromFile(Context context, String filename, int readLength) throws IOException {
        File file = new File(context.getFilesDir(), filename);
        long fileLength = file.length();
        if (readLength> fileLength)
            readLength = (int) fileLength;

        fileLength -= filename.length();
        --fileLength;

        if (fileLength > 0) {
            char[] summaryBytes = new char[readLength];

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(context.openFileInput(filename)), readLength);
            bufferedReader.read(summaryBytes, 0, readLength);
            bufferedReader.close();
            //Log.e("buffer size", Integer.toString(summaryBytes.length));

            StringBuilder summaryBuilder = new StringBuilder();
            summaryBuilder.append(summaryBytes);

            summaryBuilder.delete(0, 2);

            // removes filename from the text of the file
            filename = filename.replaceAll(" ", "_");
            for (int iter = 0; iter < filename.length(); iter++) {
                if (summaryBuilder.charAt(0) == filename.charAt(iter))
                    summaryBuilder.deleteCharAt(0);
                else
                    break;
            }

           summaryBuilder.delete(0, 3);

            return summaryBuilder.toString().trim();
        }else{
            return "";
        }
    }

    public static ArrayList<File> getAllFilesWithExtension(final File directory, final String extension){
                ArrayList<File> filesArrayList = new ArrayList<>();

                filesArrayList.addAll(Files.getFilesWithExtension(directory,extension));

                Collections.sort(filesArrayList, new Comparator<File>() {
                    @Override
                    public int compare(File f1, File f2) {
                        return Long.valueOf(f2.lastModified()).compareTo(
                                f1.lastModified());
                    }
                });
            return filesArrayList;

    }

}


text:
package com.bsencan.openchess.view;

/**
 * An interface for all classes that needs to do rendering to a screen.
 *
 * @author Baris Sencan
 */
public interface Renderer {

	/**
	 * Should be called when rendering needs to be done.
	 *
	 * @param delta
	 *            The time in seconds since the last render.
	 */
	public void render(float delta);

	/**
	 * Should be called when device screen is resized.
	 *
	 * @param width
	 *            The new width in pixels.
	 * @param height
	 *            The new height in pixels.
	 */
	public void setSize(int width, int height);

	/**
	 * Should be called when the renderer needs to release all resources.
	 */
	public void dispose();
}


text:
The project folder is a way to quickly test this node in an local node-red
instance.

First change into the project directory and then run:

    npm install

Then start the Node-RED instance using:

    npm start

And you're up and running!


text:
require 'test_helper'

class DocsControllerTest < ActionController::TestCase
  setup do
    @doc = docs(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:docs)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create doc" do
    assert_difference('Doc.count') do
      post :create, doc: { body: @doc.body, section: @doc.section, serial: @doc.serial, source: @doc.source, sourcedb: @doc.sourcedb, sourceid: @doc.sourceid }
    end

    assert_redirected_to doc_path(assigns(:doc))
  end

  test "should show doc" do
    get :show, id: @doc
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @doc
    assert_response :success
  end

  test "should update doc" do
    put :update, id: @doc, doc: { body: @doc.body, section: @doc.section, serial: @doc.serial, source: @doc.source, sourcedb: @doc.sourcedb, sourceid: @doc.sourceid }
    assert_redirected_to doc_path(assigns(:doc))
  end

  test "should destroy doc" do
    assert_difference('Doc.count', -1) do
      delete :destroy, id: @doc
    end

    assert_redirected_to docs_path
  end
end


text:
exports.bar_entry = function f(arg) {
    console.log(arg, 'node_modules.bar.entry.js')
}


text:
Advanced topics
===============

This part of the documentation discusses topics that are more advanced, and
offer more control over the input, running, and output of the radiative
transfer.

.. toctree::
   :maxdepth: 1

   use_previous.rst
   advanced_conf.rst
   reducing_file_sizes.rst
   indepth_oct.rst
   indepth_amr.rst
   logger.rst
   peeloff.rst
   scaling_isrf.rst

Finally, the two following topics are reserved for coding ninjas! They explain
the HDF5 file format used for the dust files and the model files so that you
can write your own library, and bypass the Python library altogether.

.. toctree::
   :maxdepth: 1

   dust_file.rst
   model_file.rst


text:
#import "cbm5x0controller.h"

@implementation CBM5x0Controller

@end


text:
import { Meteor } from 'meteor/meteor';

if (Meteor.isServer) {
  Meteor.publish("users", function () {
    return Meteor.users.find({}, { fields: { username: 1, profile: 1 } });
  });
}


text:
module Crowdblog
  module ApplicationHelper
  end
end


text:
/**
 * SRWPort.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.2.1 Jun 14, 2005 (09:15:57 EDT) WSDL2Java emitter.
 */

package gov.loc.www.zing.srw.interfaces;

public interface SRWPort extends java.rmi.Remote {
    public gov.loc.www.zing.srw.SearchRetrieveResponseType searchRetrieveOperation(gov.loc.www.zing.srw.SearchRetrieveRequestType body) throws java.rmi.RemoteException;
    public gov.loc.www.zing.srw.ScanResponseType scanOperation(gov.loc.www.zing.srw.ScanRequestType body) throws java.rmi.RemoteException;
}


text:
package concrete.connections;

import abstracts.VendorConnection;
import concrete.pools.GmailConnectionPool;

public class GmailConnection extends VendorConnection {

	public GmailConnection(int connectionId) {
		super(connectionId);
	}

	@Override
	public void sendData(String data){
		System.out.println("Sending the data on Gmail connection.");
		super.sendData(data);
		GmailConnectionPool.getInstance().releaseConnection(this);
	}

	@Override
	public void receiveData(String data){
		System.out.println("Receiving the data on Gmail connection.");
		super.receiveData(data);
		GmailConnectionPool.getInstance().releaseConnection(this);
	}
}


text:
<?php

/**
 * BaseCategoryContent
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property integer $content_id
 * @property integer $category_id
 * @property Content $Content
 * @property Category $Category
 *
 * @method integer         getContentId()   Returns the current record's "content_id" value
 * @method integer         getCategoryId()  Returns the current record's "category_id" value
 * @method Content         getContent()     Returns the current record's "Content" value
 * @method Category        getCategory()    Returns the current record's "Category" value
 * @method CategoryContent setContentId()   Sets the current record's "content_id" value
 * @method CategoryContent setCategoryId()  Sets the current record's "category_id" value
 * @method CategoryContent setContent()     Sets the current record's "Content" value
 * @method CategoryContent setCategory()    Sets the current record's "Category" value
 *
 * @package    sf_sandbox
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseCategoryContent extends sfDoctrineRecord
{
    public function setTableDefinition()
    {
        $this->setTableName('category_content');
        $this->hasColumn('content_id', 'integer', 4, array(
             'type' => 'integer',
             'primary' => true,
             'length' => 4,
             ));
        $this->hasColumn('category_id', 'integer', 4, array(
             'type' => 'integer',
             'primary' => true,
             'length' => 4,
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $this->hasOne('Content', array(
             'local' => 'content_id',
             'foreign' => 'id'));

        $this->hasOne('Category', array(
             'local' => 'category_id',
             'foreign' => 'id'));
    }
}


text:
package intellij.haskell.editor

import java.util

import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandler
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.tree.IElementType
import com.intellij.psi.{PsiComment, PsiElement, PsiWhiteSpace}
import intellij.haskell.HaskellFile
import intellij.haskell.psi.HaskellPsiUtil
import intellij.haskell.psi.HaskellTypes._

import scala.collection.mutable.ListBuffer
import scala.jdk.CollectionConverters._

class HaskellExtendWordSelectionHandler extends ExtendWordSelectionHandler {

  override def canSelect(e: PsiElement): Boolean = {
    Option(e.getContainingFile).exists(_.isInstanceOf[HaskellFile]) && !e.isInstanceOf[PsiComment] && !e.isInstanceOf[PsiWhiteSpace]
  }

  override def select(e: PsiElement, editorText: CharSequence, cursorOffset: Int, editor: Editor): util.List[TextRange] = {
    val startOffset = e.getTextRange.getStartOffset
    val nextEndOffsets = getOffsets(Some(e), ListBuffer.empty[(Int, IElementType)], (e: PsiElement) => e.getNextSibling, (e: PsiElement) => (e.getTextRange.getEndOffset, e.getNode.getElementType))

    val prevStartOffsets = getOffsets(Option(e.getPrevSibling), ListBuffer.empty[(Int, IElementType)], (e: PsiElement) => e.getPrevSibling, (e: PsiElement) => (e.getTextRange.getStartOffset, e.getNode.getElementType))
    val lastEndOffset = nextEndOffsets.lastOption.getOrElse((e.getTextRange.getEndOffset, e.getNode.getElementType))

    val allSelectOptions = nextEndOffsets.map(eo => (e.getNode.getElementType, eo._2, new TextRange(startOffset, eo._1))) ++ prevStartOffsets.map(so => (so._2, lastEndOffset._2, new TextRange(so._1, lastEndOffset._1)))

    allSelectOptions.filter(x =>
      if (x._1 == HS_LEFT_PAREN) {
        x._2 == HS_RIGHT_PAREN
      } else if (x._1 == HS_LEFT_BRACE) {
        x._2 == HS_RIGHT_BRACE
      } else if (x._1 == HS_LEFT_BRACKET) {
        x._2 == HS_RIGHT_BRACKET
      } else if (x._2 == HS_RIGHT_PAREN) {
        x._1 == HS_LEFT_PAREN
      } else if (x._2 == HS_RIGHT_BRACE) {
        x._1 == HS_LEFT_BRACE
      } else if (x._2 == HS_RIGHT_BRACKET) {
        x._1 == HS_LEFT_BRACKET
      } else {
        true
      }
    ).map(_._3).asJava
  }

  private def getOffsets(element: Option[PsiElement], offsets: ListBuffer[(Int, IElementType)], getSibling: PsiElement => PsiElement, getOffset: PsiElement => (Int, IElementType)): ListBuffer[(Int, IElementType)] = {
    def recur(e: PsiElement): ListBuffer[(Int, IElementType)] = {
      getOffsets(Option(getSibling(e)), offsets, getSibling, getOffset)
    }

    element match {
      case Some(e) =>
        HaskellPsiUtil.findQualifiedName(e) match {
          case None => e match {
            case e: PsiWhiteSpace => recur(e)
            case e: PsiElement if e.getNode.getElementType == HS_COMMA => recur(e)
            case e: PsiElement if e.getNode.getElementType == HS_NEWLINE | e.getNode.getElementType == HS_EQUAL | e.getNode.getElementType == HS_LEFT_ARROW => offsets
            case _ =>
              offsets += getOffset(e)
              recur(e)
          }
          case Some(qe) =>
            offsets += getOffset(qe)
            recur(qe)
        }
      case None => offsets
    }
  }
}


text:
build:	test
	go build -o $(GOPATH)/bin/git-appraise-web git-appraise-web/git-appraise-web.go

test:	vet
	go test ./...

vet:	fmt
	go vet ./...

fmt:	assets
	gofmt -w ./

assets: deps FORCE
	rm assets/*~ 2>/dev/null || true
	$(GOPATH)/bin/go-bindata -pkg assets -o third_party/assets/assets.go assets/

deps:
	go get -u github.com/jteeuwen/go-bindata/...

FORCE:


text:
@interface PPLogger ()

- (NSString *) formatMessage:(NSString *)message severity:(PPLoggerSeverity)severity functionName:(NSString *)functionName lineNumber:(NSInteger)lineNumber underVerbosity:(PPLoggerVerbosity)verbosity;

@end

@implementation PPLogger

+ (PPLogger *)sharedInstance
{
    static PPLogger *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[PPLogger alloc] init];
    });
    return instance;
}

- (id)init
{
    if (self = [super init]) {
        self.configuration = [PPLoggerConfiguration defaultConfiguration];
    }
    return self;
}

- (NSString *)formatMessage:(NSString *)message severity:(PPLoggerSeverity)severity functionName:(NSString *)functionName lineNumber:(NSInteger)lineNumber underVerbosity:(PPLoggerVerbosity)verbosity
{
    if (verbosity == PPLoggerVerbosityUNSET) {
        return @"";
    }

    NSMutableArray *parts = [NSMutableArray array];

    NSString *severityTag = [PPLoggerConfiguration tagRepresentationOfSeverity:severity];
    [parts addObject:severityTag];

    if (verbosity == PPLoggerVerbosityDetailed) {
        [parts addObject:[NSString stringWithFormat:@"%@", functionName]];
    }

    if (verbosity == PPLoggerVerbosityDetailed) {
        [parts addObject:[NSString stringWithFormat:@"[%d]", lineNumber]];
    }

    [parts addObject:message];

    return [parts componentsJoinedByString:@"\t"];
}

- (void)log:(NSString *)message severity:(PPLoggerSeverity)severity verbosity:(PPLoggerVerbosity)verbosity functionName:(NSString *)functionName lineNumber:(NSInteger)lineNumber
{
    severity = [self.configuration normalizedSeverity:severity];
    verbosity = [self.configuration normalizedVerbosity:verbosity];

    if (![self.configuration shouldLogUnderSeverity:severity verbosity:verbosity]) {
        return;
    }

    NSString *formattedMessage = [self formatMessage:message severity:(PPLoggerSeverity)severity functionName:(NSString *)functionName lineNumber:lineNumber underVerbosity:verbosity];

    NSLogv(formattedMessage, nil);
}

@end


text:
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses,
             FunctionalDependencies, RankNTypes #-}

module Q where

class Transformer t a | t -> a where
    transform :: t -> l a -> (forall l'. l' a -> b) -> b

data EL a = forall l. EL (l a)

unEL :: EL a -> (forall l. l a -> b) -> b
unEL _ _ = error "unEL"

transform' :: (Transformer t a) => t -> EL a -> EL a
transform' = error "transform'"

data MultiToggleS ts a = MultiToggleS ts

data MultiToggle = MultiToggle

expand :: HList ts a => MultiToggleS ts a -> MultiToggle
expand (MultiToggleS ts) =
    resolve ts
        (\x mt ->
            let g = transform' x in
            mt
        )
        MultiToggle

class HList c a | c -> a where
    resolve :: c -> (forall t. (Transformer t a) => t -> b) -> b


text:
/* Tabs */
.webos-tabs {
	display: block;
}

.webos-tabs > ul.tabs {
	list-style-type: none;
	list-style-position: inside;
	padding: 0;
	margin: 0;
	position: relative;
	white-space: nowrap;
	max-width: 100%;
	overflow: auto;
}
.webos-tabs > ul.tabs li {
	display: inline-block;
}

.webos-tabs > .contents > div {
	display: none;
}
.webos-tabs > .contents > div.active {
	display: block;
}

/* Notebooks */
.webos-notebook {
	display: block;
}
.webos-notebook > ul.tabs {
	list-style-type: none;
	list-style-position: inside;
	padding: 0;
	margin: 0;
	position: relative;
	white-space: nowrap;
	overflow: hidden;
	height: 26px;
}
.webos-notebook > ul.tabs > li {
	display: inline-block;
	position: relative;
}
.webos-notebook > ul.tabs > .tab-btn {
	width: 170px;
	text-align: center;
	overflow: hidden;
	text-overflow: ellipsis;
}
.webos-notebook > ul.tabs > .tab-btn .tab-btn-close {
	float: left;
}
.webos-notebook > ul.tabs > .tab-btn-newtab {
	float: left;
}

.webos-notebook > .contents {
	height: calc(100% - 25px);
}
.webos-notebook > .contents > div {
	display: none;
	height: 100%;
}
.webos-notebook > .contents > div.active {
	display: block;
}

/* Popover */
.webos-popover {
	position: relative;
}
.webos-popover > .popover-toggle {
	position: relative;
}
.webos-popover > .popover-content {
	position: absolute;
	padding: 5px;
	z-index: 2;
	display: none;

	background-color: white;
}

/* Alert */
.webos-alert-container {
	display: block;
	padding: 3px;

	background-color: #e35d4f;
	color: #660000;
	border-bottom: 1px solid #97312e;
}
.webos-alert-container .webos-button {
	float: right;
}

/* Color picker */
.webos-color-picker {
	display: block;
	padding: 3px;
}
.webos-color-picker .picker-palette ul {
	list-style-type: none;
	display: inline-block;
	margin: 6px;
	padding: 0;
	overflow: hidden;
	border-radius: 3px;
}
.webos-color-picker .picker-palette li {
	display: block;
	position: relative;
	width: 36px;
	height: 36px;
}
.webos-color-picker .picker-palette ul.palette-variation-black {
	display: block;
	margin: 0;
}
.webos-color-picker .picker-palette ul.palette-variation-black li {
	display: inline-block;
	border-radius: 3px;
	margin: 6px;
}

/* Icons */
.webos-icon img {
	max-width: 100%;
	max-height: 100%;
}
.webos-icon.icon-dark {
	filter: url(#webos-icon-brightness-darker);
	-webkit-filter: brightness(50%);
	-moz-filter: brightness(50%);
	filter: brightness(50%);
}

/* Menus */
.webos-menuwindowheader ul { /* Liste */
	padding: 0; /* pas de marge intérieure */
	margin: 0; /* ni extérieure */
	list-style-type: none; /* on supprime le style par défaut de la liste */
	list-style-position: inside;
	line-height: 19px; /* on définit une hauteur pour chaque élément */
	text-align: center; /* on centre le texte qui se trouve dans la liste */
}
.webos-menuwindowheader ul:empty {
	display: none;
	visibility: hidden;
	opacity: 0;
}
.webos-menuwindowheader * { /* Ensemble du menu */
	position: relative;
	z-index: 1050;
}
.webos-menuwindowheader ul { /* Menu de fenetre */
	position: relative;
	background-color: white;
	min-width: 220px;
	border: 1px solid black;
}
.webos-menuwindowheader .webos-menuitem .webos-menuitem { /* Sous-listes */
	display: block;
}
.webos-menuwindowheader ul {
	position: absolute;
	display: none;
}
.webos-menuwindowheader ul.opened,
.webos-menuwindowheader .webos-menuitem.hover > ul {
	display: block;
	opacity: 1;
}
.webos-menuwindowheader .webos-menuitem ul .webos-menuitem ul { /* Sous-sous-listes */
	top: -2px;
	left: 219px;
}
.webos-menuwindowheader .webos-menuitem { /* Item de menu */
	text-align: left;
	-o-text-overflow: ellipsis; /* pour Opera 9 */
	text-overflow: ellipsis; /* pour le reste du monde */
	white-space: nowrap;
}
.webos-menuwindowheader .webos-menuitem a {
	text-decoration: none; /* on supprime le style par défaut des liens (la plupart du temps = souligné) */
	overflow: hidden;
	-o-text-overflow: ellipsis; /* pour Opera 9 */
	text-overflow: ellipsis; /* pour le reste du monde */
	white-space: nowrap;
}
.webos-menuwindowheader .webos-menuitem a:hover {
	text-decoration: none;
}
.webos-menuwindowheader .webos-menuitem, .webos-menuwindowheader .webos-menuitem a {
	color: black;
}
.webos-menuwindowheader .webos-menuitem ul .webos-menuitem { /* Item de sous-liste */
	width: 100%;
	-moz-box-sizing: border-box;
	-ms-box-sizing: border-box;
	-webkit-box-sizing: border-box;
	box-sizing: border-box;
}
.webos-menuwindowheader .webos-menuitem img.icon { /* Icone d'item */
	float: left;
	max-height: 19px;
	max-width: 19px;
	margin-right: 2px;
}
.webos-menuwindowheader > .webos-menuitem {
	/*float: left;*/
	display: inline-block;
}
.webos-menuwindowheader .separator { /* Separateur */
	border-top: solid 1px black;
}

.menu-container {
	display: inline-block;
}
.menu-container.menu-container-left {
	float:left;
}
.menu-container.menu-container-left .menu li {
	display:block;
	float:left;
}
.menu-container.menu-container-right {
	float:right;
}
.menu-container.menu-container-center {
	display:block;
	margin:auto;
}


text:
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import { Article } from "./article.model";
import { Observable } from "rxjs";
import { ExceptionService } from "../core";

@Injectable()
export class ArticleService {
    constructor(private _http: Http) { }

    public add(entity: Article) {
        return this._http
            .post(`${this._baseUrl}/api/article/add`, entity)
            .map(data => data.json())
            .catch(err => {
                return Observable.of(false);
            });
    }

    public get() {
        return this._http
            .get(`${this._baseUrl}/api/article/get`)
            .map(data => data.json())
            .catch(err => {
                return Observable.of(false);
            });
    }

    public getById(options: { id: number }) {
        return this._http
            .get(`${this._baseUrl}/api/article/getById?id=${options.id}`)
            .map(data => data.json())
            .catch(err => {
                return Observable.of(false);
            });
    }

    public remove(options: { id: number }) {
        return this._http
            .delete(`${this._baseUrl}/api/article/remove?id=${options.id}`)
            .map(data => data.json())
            .catch(err => {
                return Observable.of(false);
            });
    }

    public get _baseUrl() { return ""; }

}


text:
<?php

namespace Oneup\CssMin\Minifier\Filter;

class CssSortRulesetPropertiesMinifierFilter extends aCssMinifierFilter
{
    /**
     * Implements {@link aCssMinifierFilter::filter()}.
     *
     * @param  array   $tokens Array of objects of type aCssToken
     * @return integer Count of added, changed or removed tokens; a return value larger than 0 will rebuild the array
     */
    public function apply(array &$tokens)
    {
        $r = 0;
        for ($i = 0, $l = count($tokens); $i < $l; $i++) {
            // Only look for ruleset start rules
            if (get_class($tokens[$i]) !== "CssRulesetStartToken") { continue; }
            // Look for the corresponding ruleset end
            $endIndex = false;

            for ($ii = $i + 1; $ii < $l; $ii++) {
                if (get_class($tokens[$ii]) !== "CssRulesetEndToken") { continue; }
                $endIndex = $ii;
                break;
            }

            if (!$endIndex) { break; }

            $startIndex = $i;
            $i = $endIndex;
            // Skip if there's only one token in this ruleset
            if ($endIndex - $startIndex <= 2) { continue; }

            // Ensure that everything between the start and end is a declaration token, for safety
            for ($ii = $startIndex + 1; $ii < $endIndex; $ii++) {
                if (get_class($tokens[$ii]) !== "CssRulesetDeclarationToken") { continue(2); }
            }

            $declarations = array_slice($tokens, $startIndex + 1, $endIndex - $startIndex - 1);
            // Check whether a sort is required
            $sortRequired = $lastPropertyName = false;

            foreach ($declarations as $declaration) {
                if ($lastPropertyName) {
                    if (strcmp($lastPropertyName, $declaration->Property) > 0) {
                        $sortRequired = true;
                        break;
                    }
                }
                $lastPropertyName = $declaration->Property;
            }

            if (!$sortRequired) { continue; }

            // Arrange the declarations alphabetically by name
            usort($declarations, array(__CLASS__, "userDefinedSort1"));
            // Update "IsLast" property

            for ($ii = 0, $ll = count($declarations) - 1; $ii <= $ll; $ii++) {
                if ($ii == $ll) {
                    $declarations[$ii]->IsLast = true;
                } else {
                    $declarations[$ii]->IsLast = false;
                }
            }
            // Splice back into the array.
            array_splice($tokens, $startIndex + 1, $endIndex - $startIndex - 1, $declarations);
            $r += $endIndex - $startIndex - 1;
        }

        return $r;
    }

    /**
     * User defined sort function.
     *
     * @return integer
     */
    public static function userDefinedSort1($a, $b)
    {
        return strcmp($a->Property, $b->Property);
    }
}


text:
require 'uri'
require 'net/http'
require 'net/https'
require 'benchmark'

module ActiveMerchant
  class ConnectionError < ActiveMerchantError # :nodoc:
  end

  class RetriableConnectionError < ConnectionError # :nodoc:
  end

  class ResponseError < ActiveMerchantError # :nodoc:
    attr_reader :response

    def initialize(response, message = nil)
      @response = response
      @message  = message
    end

    def to_s
      "Failed with #{response.code} #{response.message if response.respond_to?(:message)}"
    end
  end

  class Connection
    MAX_RETRIES = 3
    OPEN_TIMEOUT = 60
    READ_TIMEOUT = 60
    VERIFY_PEER = true
    RETRY_SAFE = false
    RUBY_184_POST_HEADERS = { "Content-Type" => "application/x-www-form-urlencoded" }

    attr_accessor :endpoint
    attr_accessor :open_timeout
    attr_accessor :read_timeout
    attr_accessor :verify_peer
    attr_accessor :retry_safe
    attr_accessor :pem
    attr_accessor :pem_password
    attr_accessor :wiredump_device
    attr_accessor :logger
    attr_accessor :tag

    def initialize(endpoint)
      @endpoint     = endpoint.is_a?(URI) ? endpoint : URI.parse(endpoint)
      @open_timeout = OPEN_TIMEOUT
      @read_timeout = READ_TIMEOUT
      @retry_safe   = RETRY_SAFE
      @verify_peer  = VERIFY_PEER
    end

    def request(method, body, headers = {})
      retry_exceptions do
        begin
          info "#{method.to_s.upcase} #{endpoint}", tag

          result = nil

          realtime = Benchmark.realtime do
            result = case method
            when :get
              raise ArgumentError, "GET requests do not support a request body" if body
              http.get(endpoint.request_uri, headers)
            when :post
              debug body
              http.post(endpoint.request_uri, body, RUBY_184_POST_HEADERS.merge(headers))
            else
              raise ArgumentError, "Unsupported request method #{method.to_s.upcase}"
            end
          end

          info "--> %d %s (%d %.4fs)" % [result.code, result.message, result.body ? result.body.length : 0, realtime], tag
          response = handle_response(result)
          debug response
          response
        rescue EOFError => e
          raise ConnectionError, "The remote server dropped the connection"
        rescue Errno::ECONNRESET => e
          raise ConnectionError, "The remote server reset the connection"
        rescue Errno::ECONNREFUSED => e
          raise RetriableConnectionError, "The remote server refused the connection"
        rescue Timeout::Error, Errno::ETIMEDOUT => e
          raise ConnectionError, "The connection to the remote server timed out"
        end
      end
    end

    private
    def http
      http = Net::HTTP.new(endpoint.host, endpoint.port)
      configure_debugging(http)
      configure_timeouts(http)
      configure_ssl(http)
      configure_cert(http)
      http
    end

    def configure_debugging(http)
      http.set_debug_output(wiredump_device)
    end

    def configure_timeouts(http)
      http.open_timeout = open_timeout
      http.read_timeout = read_timeout
    end

    def configure_ssl(http)
      return unless endpoint.scheme == "https"

      http.use_ssl = true

      if verify_peer
        http.verify_mode = OpenSSL::SSL::VERIFY_PEER
        http.ca_file     = File.dirname(__FILE__) + '/../../certs/cacert.pem'
      else
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
    end

    def configure_cert(http)
      return if pem.blank?

      http.cert = OpenSSL::X509::Certificate.new(pem)

      if pem_password
        http.key = OpenSSL::PKey::RSA.new(pem, pem_password)
      else
        http.key = OpenSSL::PKey::RSA.new(pem)
      end
    end

    def retry_exceptions
      retries = 1 #MAX_RETRIES
      begin
        yield
      rescue RetriableConnectionError => e
        retries -= 1
        retry unless retries.zero?
        raise ConnectionError, e.message
      rescue ConnectionError
        retries -= 1
        retry if retry_safe && !retries.zero?
        raise
      end
    end

    def handle_response(response)
      case response.code.to_i
      when 200...300
        response.body
      else
        raise ResponseError.new(response)
      end
    end

    def debug(message, tag = nil)
      log(:debug, message, tag)
    end

    def info(message, tag = nil)
      log(:info, message, tag)
    end

    def log(level, message, tag)
      message = "[#{tag}] #{message}" if tag
      logger.send(level, message) if logger
    end
  end
end


text:
package upgrade

import (
	"bytes"
	"testing"

	kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
)

func TestPrintConfiguration(t *testing.T) {
	var tests = []struct {
		name          string
		cfg           *kubeadmapi.ClusterConfiguration
		buf           *bytes.Buffer
		expectedBytes []byte
	}{
		{
			name:          "config is nil",
			cfg:           nil,
			expectedBytes: []byte(""),
		},
		{
			name: "cluster config with local Etcd",
			cfg: &kubeadmapi.ClusterConfiguration{
				KubernetesVersion: "v1.7.1",
				Etcd: kubeadmapi.Etcd{
					Local: &kubeadmapi.LocalEtcd{
						DataDir: "/some/path",
					},
				},
				DNS: kubeadmapi.DNS{
					Type: kubeadmapi.CoreDNS,
				},
			},
			expectedBytes: []byte(`[upgrade/config] Configuration used:
	apiServer: {}
	apiVersion: kubeadm.k8s.io/v1beta1
	certificatesDir: ""
	controlPlaneEndpoint: ""
	controllerManager: {}
	dns:
	  type: CoreDNS
	etcd:
	  local:
	    dataDir: /some/path
	imageRepository: ""
	kind: ClusterConfiguration
	kubernetesVersion: v1.7.1
	networking:
	  dnsDomain: ""
	  podSubnet: ""
	  serviceSubnet: ""
	scheduler: {}
`),
		},
		{
			name: "cluster config with ServiceSubnet and external Etcd",
			cfg: &kubeadmapi.ClusterConfiguration{
				KubernetesVersion: "v1.7.1",
				Networking: kubeadmapi.Networking{
					ServiceSubnet: "10.96.0.1/12",
				},
				Etcd: kubeadmapi.Etcd{
					External: &kubeadmapi.ExternalEtcd{
						Endpoints: []string{"https://one-etcd-instance:2379"},
					},
				},
				DNS: kubeadmapi.DNS{
					Type: kubeadmapi.CoreDNS,
				},
			},
			expectedBytes: []byte(`[upgrade/config] Configuration used:
	apiServer: {}
	apiVersion: kubeadm.k8s.io/v1beta1
	certificatesDir: ""
	controlPlaneEndpoint: ""
	controllerManager: {}
	dns:
	  type: CoreDNS
	etcd:
	  external:
	    caFile: ""
	    certFile: ""
	    endpoints:
	    - https://one-etcd-instance:2379
	    keyFile: ""
	imageRepository: ""
	kind: ClusterConfiguration
	kubernetesVersion: v1.7.1
	networking:
	  dnsDomain: ""
	  podSubnet: ""
	  serviceSubnet: 10.96.0.1/12
	scheduler: {}
`),
		},
	}
	for _, rt := range tests {
		t.Run(rt.name, func(t *testing.T) {
			rt.buf = bytes.NewBufferString("")
			printConfiguration(rt.cfg, rt.buf)
			actualBytes := rt.buf.Bytes()
			if !bytes.Equal(actualBytes, rt.expectedBytes) {
				t.Errorf(
					"failed PrintConfiguration:\n\texpected: %q\n\t  actual: %q",
					string(rt.expectedBytes),
					string(actualBytes),
				)
			}
		})
	}
}


text:
const express = require('express');
const db = require('node-localdb');
const crypto = require('crypto');
const rp = require('request-promise-native');

// These come from your config file and are used for authenticating administrative calls:
const AdminKey = '{{ZkitSdk.AdminKey}}';
const AdminUId = '{{ZkitSdk.AdminUserId}}';
const ApiBase = '{{ZkitSdk.ApiBase}}/';
const TenantRoot = '{{ZkitSdk.TenantRoot.length === 0 ? "" : ZkitSdk.TenantRoot.substr(1) + "/"}}';

/*
    Called by init-user-reg, this initiates the user registration flow
    This endpoint on the server returns an object containing:
    UserId: This is the new user's id, used for operations like tresor sharing. Uniquely identifies the new user.
    RegSessionId: This is a public information that identifies this registration process.
    RegSessionVerifier: This is a server side secret, that should never touch the client device. Used during validation.
*/
function initUserRegistration(){
  return authorizedCall('api/v4/admin/user/init-user-registration', { }); // we need to make this a post
}

/*
    Called by finished-registration, in most real applications this is called later after an out-of-band validation.
    This server call will enable the user: now it can be used to log in.
    The parameters are described above: the server gets them from the initUserRegistration call, and will need to be
    stored on the application server until validation.
    The regValidationVerifier is returned by the sdk registration call, and is sent to and stored on the app server.
*/
function validateUser(id, regSessionId, regSessionVerifier, regValidationVerifier){
  return authorizedCall('api/v4/admin/user/validate-user-registration', {
    RegSessionId: regSessionId,
    RegSessionVerifier: regSessionVerifier,
    RegValidationVerifier: regValidationVerifier,
    UserId: id
  });
}

/*
    Called by new-tresor api call
    This method is used to commit the tresor creation operation, before it the tresor is unusable.
    This provides control over the flow of information in your application and serves to synchronize the application and
    the tenant database
 */
function approveTresorCreation(tresorId) {
  return authorizedCall('api/v4/admin/tresor/approve-tresor-creation', {TresorId: tresorId});
}

/*
    Called by shared-tresor
    This method is used to commit the share operation, before approval, the share has no effect on the database and on
    the tresor data downloaded by other users. After approval the tresor changes and the invited user can now decrypt
    data encrypted by this tresor.
    This provides control over the flow of information in your application and serves to synchronize the application and
    the tenant database
 */
function approveShare(inviteId) {
  return authorizedCall('api/v4/admin/tresor/approve-share?inviteId=' + inviteId, { OperationId: inviteId });
}

// Concatenates the headers into a canonical format used to sign the request
function getHeaderStringToHash(verb, url, headers, hmacHeaders) {
  return verb + '\n' + url + '\n' + hmacHeaders.map(key => key + ':' + headers[key]).join('\n');
}

// Calculates the necessary headers for authentication. The exact definitions and a detailed guide on this type of
// authentication can be found in the in Chapter 5.1 of the provided documentation.
function adminPostAuth(url, contentBuffer) {
  // Format ISO8601 with no milliseconds
  const date = new Date().toISOString().substr(0, 19) + 'Z';
  const headers = {
    'UserId': AdminUId,
    'TresoritDate': date,
    'Content-Type': 'application/json',
  };

  if (contentBuffer)
    headers['Content-SHA256'] = sha256hex(contentBuffer);

  const hmacHeaders = Object.keys(headers);
  hmacHeaders.push('HMACHeaders');
  headers['HMACHeaders'] = hmacHeaders.join(',');

  const headerStringToHash = getHeaderStringToHash(contentBuffer ? 'POST' : 'GET', url, headers, hmacHeaders);
  headers['Authorization'] = 'AdminKey ' + hmacSha256base64(headerStringToHash, AdminKey);
  return headers;
}

// Convenience function to call admin endpoints on the tenant server.
function authorizedCall(urlPart, contentObj) {
  urlPart = TenantRoot + urlPart;
  const contentBuffer = contentObj ? contentify(contentObj) : null;
  const headers = adminPostAuth(urlPart, contentBuffer);

  return rp({
    method: contentObj ? 'POST' : 'GET',
    uri: ApiBase + urlPart,
    headers: headers,
    body: contentBuffer,
  }).then(body => body.length > 0 ? JSON.parse(body) : {});
}

/*
    Below you can see the boilerplate code that calls the functions above.
    Most of the code below is database handling, parsing the data in the requests and some error handling.
 */
// Create simple local datastore to persist the users
const dbRegInfo = db('localdb/reg-info.json');

module.exports = function() {
  const api = express.Router();

  // Initiates a registration process. Returns a new unique userid, and some registration tokens to make the
  // registration transactional. For more information see the [7. Common flows] chapter in the documentation.
  api.post('/get-user-id',
    function (req, res, next) {
      dbRegInfo.findOne({alias: req.body.alias}).then(
        user => {
          if (user) {
            res.json({userId: user.userId});
          } else {
            res.status(404).json('User not found');
          }
        }, (err) => next(err || {})
      );
    }
  );

  // Initiates a registration process. Returns a new unique userid, and some registration tokens to make the
  // registration transactional. For more information see the [7. Common flows] chapter in the documentation.
  api.post('/init-user-reg',
    function (req, res, next) {
      // calls the initiation function
      initUserRegistration().then((initResponse) => {
        // saves both the server side secret and the client side data
        return dbRegInfo.insert({
          alias: req.body.alias,
          userId: initResponse.UserId,
          regSessionId: initResponse.RegSessionId,
          regSessionVerifier: initResponse.RegSessionVerifier
        }).then(() => {
          // returns the client side data
          res.json({
            userId: initResponse.UserId,
            regSessionId: initResponse.RegSessionId
          });
        });
      }).catch(err => next(err || {}));
    }
  );

  // This endpoint is called when a user finishes registration, and normally only stores the necessary information
  // to validate the user, but for the sake of the example it also calls the validation function immediately.
  // This is where you can for example commit the user to a more permanent database or start an
  // out of band validation process.
  api.post('/finished-registration',
    function (req, res, next) {
      dbRegInfo.findOne({ userId: req.body.userId })
        .then((regInfo) => {
          if (regInfo) {
            regInfo.regValidationVerifier = req.body.regValidationVerifier;
            dbRegInfo.update({ userId: regInfo.userId }, regInfo);
            return validateUser(
              regInfo.userId,
              regInfo.regSessionId,
              regInfo.regSessionVerifier,
              regInfo.regValidationVerifier,
              regInfo.alias
            ).then(() => res.status(200).json(null));
          } else {
            res.status(400).json({type: 'UserNotFound'});
          }
        })
        .catch(err => next(err || {}));
    }
  );

  // Creates a new tresor and stores the tresorid in the local database.
  api.post('/new-tresor',
    function (req, res, next) {
      approveTresorCreation(req.body.id).then(
        () => res.send(),
        err => next(err || {})
      );
    }
  );

  // This endpoint "commits" a sharing transaction initiated on the client side by the `zkit_sdk.shareTresor` call.
  // This is the right place to check application specific permissions, and to track the changes in tresor-user sharing
  // relations. This provides the application control over the information flow.
  api.post('/shared-tresor',
    function (req, res, next) {
      approveShare(req.body.id)
        .then(r => res.json(r).status(200))
        .catch(err => {
          console.log(err);
          next(err || {});
        });
    }
  );

  return api;
};

// Convenience functions to make the code above more concise
// Encode an object into a buffer to be sent.
function contentify(obj) {
  return new Buffer(JSON.stringify(obj));
}

// Simple hash functions
function sha256hex(data) {
  return crypto.createHash('sha256').update(data).digest('hex');
}
function hmacSha256base64(data, key) {
  return crypto.createHmac('sha256', new Buffer(key, 'hex')).update(data).digest('base64');
}


text:
using FlaUI.Core.AutomationElements.Infrastructure;
using FlaUI.Core.Identifiers;
using FlaUI.UIA2.Identifiers;

namespace FlaUI.UIA2
{
    public class UIA2AutomationElementProperties : IAutomationElementProperties
    {
        public PropertyId AcceleratorKey => AutomationObjectIds.AcceleratorKeyProperty;
        public PropertyId AccessKey => AutomationObjectIds.AccessKeyProperty;
        public PropertyId AriaProperties => PropertyId.NotSupportedByFramework;
        public PropertyId AriaRole => PropertyId.NotSupportedByFramework;
        public PropertyId AutomationId => AutomationObjectIds.AutomationIdProperty;
        public PropertyId BoundingRectangle => AutomationObjectIds.BoundingRectangleProperty;
        public PropertyId ClassName => AutomationObjectIds.ClassNameProperty;
        public PropertyId ClickablePoint => AutomationObjectIds.ClickablePointProperty;
        public PropertyId ControllerFor => PropertyId.NotSupportedByFramework;
        public PropertyId ControlType => AutomationObjectIds.ControlTypeProperty;
        public PropertyId Culture => AutomationObjectIds.CultureProperty;
        public PropertyId DescribedBy => PropertyId.NotSupportedByFramework;
        public PropertyId FlowsFrom => PropertyId.NotSupportedByFramework;
        public PropertyId FlowsTo => PropertyId.NotSupportedByFramework;
        public PropertyId FrameworkId => AutomationObjectIds.FrameworkIdProperty;
        public PropertyId HasKeyboardFocus => AutomationObjectIds.HasKeyboardFocusProperty;
        public PropertyId HelpText => AutomationObjectIds.HelpTextProperty;
        public PropertyId IsContentElement => AutomationObjectIds.IsContentElementProperty;
        public PropertyId IsControlElement => AutomationObjectIds.IsControlElementProperty;
        public PropertyId IsDataValidForForm => PropertyId.NotSupportedByFramework;
        public PropertyId IsEnabled => AutomationObjectIds.IsEnabledProperty;
        public PropertyId IsKeyboardFocusable => AutomationObjectIds.IsKeyboardFocusableProperty;
        public PropertyId IsOffscreen => AutomationObjectIds.IsOffscreenProperty;
        public PropertyId IsPassword => AutomationObjectIds.IsPasswordProperty;
        public PropertyId IsPeripheral => PropertyId.NotSupportedByFramework;
        public PropertyId IsRequiredForForm => AutomationObjectIds.IsRequiredForFormProperty;
        public PropertyId ItemStatus => AutomationObjectIds.ItemStatusProperty;
        public PropertyId ItemType => AutomationObjectIds.ItemTypeProperty;
        public PropertyId LabeledBy => AutomationObjectIds.AcceleratorKeyProperty;
        public PropertyId LiveSetting => PropertyId.NotSupportedByFramework;
        public PropertyId LocalizedControlType => AutomationObjectIds.LocalizedControlTypeProperty;
        public PropertyId Name => AutomationObjectIds.NameProperty;
        public PropertyId NativeWindowHandle => AutomationObjectIds.NativeWindowHandleProperty;
        public PropertyId OptimizeForVisualContent => PropertyId.NotSupportedByFramework;
        public PropertyId Orientation => AutomationObjectIds.OrientationProperty;
        public PropertyId ProcessId => AutomationObjectIds.ProcessIdProperty;
        public PropertyId ProviderDescription => PropertyId.NotSupportedByFramework;
        public PropertyId RuntimeId => AutomationObjectIds.RuntimeIdProperty;
    }
}


text:
@class IOSBooleanArray;
@class IOSByteArray;
@class IOSCharArray;
@class IOSDoubleArray;
@class IOSIntArray;
@class IOSObjectArray;

@interface LibcoreUtilEmptyArray : NSObject

@end

J2OBJC_STATIC_INIT(LibcoreUtilEmptyArray)

FOUNDATION_EXPORT IOSBooleanArray *LibcoreUtilEmptyArray_BOOLEAN_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, BOOLEAN_, IOSBooleanArray *)

FOUNDATION_EXPORT IOSByteArray *LibcoreUtilEmptyArray_BYTE_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, BYTE_, IOSByteArray *)

FOUNDATION_EXPORT IOSCharArray *LibcoreUtilEmptyArray_CHAR_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, CHAR_, IOSCharArray *)

FOUNDATION_EXPORT IOSDoubleArray *LibcoreUtilEmptyArray_DOUBLE_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, DOUBLE_, IOSDoubleArray *)

FOUNDATION_EXPORT IOSIntArray *LibcoreUtilEmptyArray_INT_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, INT_, IOSIntArray *)

FOUNDATION_EXPORT IOSObjectArray *LibcoreUtilEmptyArray_CLASS_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, CLASS_, IOSObjectArray *)

FOUNDATION_EXPORT IOSObjectArray *LibcoreUtilEmptyArray_OBJECT_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, OBJECT_, IOSObjectArray *)

FOUNDATION_EXPORT IOSObjectArray *LibcoreUtilEmptyArray_STRING_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, STRING_, IOSObjectArray *)

FOUNDATION_EXPORT IOSObjectArray *LibcoreUtilEmptyArray_THROWABLE_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, THROWABLE_, IOSObjectArray *)

FOUNDATION_EXPORT IOSObjectArray *LibcoreUtilEmptyArray_STACK_TRACE_ELEMENT_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, STACK_TRACE_ELEMENT_, IOSObjectArray *)

FOUNDATION_EXPORT IOSObjectArray *LibcoreUtilEmptyArray_TYPE_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, TYPE_, IOSObjectArray *)

FOUNDATION_EXPORT IOSObjectArray *LibcoreUtilEmptyArray_TYPE_VARIABLE_;
J2OBJC_STATIC_FIELD_GETTER(LibcoreUtilEmptyArray, TYPE_VARIABLE_, IOSObjectArray *)

J2OBJC_TYPE_LITERAL_HEADER(LibcoreUtilEmptyArray)

#endif // _LibcoreUtilEmptyArray_H_


text:
<?php

namespace LeadThread\Sms\Factories;

use Exception;
use LeadThread\Sms\Drivers\Plivo;
use LeadThread\Sms\Drivers\Twilio;
use LeadThread\Sms\Drivers\Bandwidth;

class DriverFactory
{

    /**
     * Creates a driver instance
     * @param  string $driver The driver instance to create
     * @return \LeadThread\Sms\Drivers\SendsSms
     */
    public function get($driver)
    {
        $config = config("sms.{$driver}");
        if (is_array($config)) {
            return $this->{$driver}($config);
        } else {
            throw new Exception("config must be an array! You may have chosen an unsupported SMS driver.");
        }
    }

    /**
     * Plivo
     * @param  array $config An array of config values for setting up the driver
     * @return \LeadThread\Sms\Drivers\Plivo\Request
     */
    protected function plivo(array $config)
    {
        return new Plivo($config['user'], $config['token']);
    }

    /**
     * Twilio
     * @param  array $config An array of config values for setting up the driver
     * @return \LeadThread\Sms\Drivers\Twilio
     */
    protected function twilio(array $config)
    {
        return new Twilio($config['user'], $config['token']);
    }

    /**
     * Bandwidth
     * @param  array $config An array of config values for setting up the driver
     * @return \LeadThread\Sms\Drivers\Bandwidth
     */
    protected function bandwidth(array $config)
    {
        return new Bandwidth($config['secret'], $config['token'], $config['user_id']);
    }
}


text:
using System;

namespace AccidentalFish.ApplicationSupport.Core.Repository
{
    /// <summary>
    /// Unit of work pattern for use with an ORM
    /// </summary>
    public interface IUnitOfWork : IDisposable
    {
        /// <summary>
        /// Retrieve a repository that acts within the unit of work
        /// </summary>
        /// <typeparam name="T">The type of the entities represented by the repository</typeparam>
        /// <returns>A repository</returns>
        IRepository<T> GetRepository<T>() where T : class;
        /// <summary>
        /// Save all changes made within the unit of work
        /// </summary>
        void Save();
    }
}


text:
// TODO Setup heartbeat "?heartbeat=10"
var amqplib = require('amqplib');
var util = require('../../service/util');

module.exports = function (config) {
    var url = config.url;

    return function middleware (req, res, next) {
        var app = req.app;

        if (app.amqpConnection && !app.amqpConnection.closed) {
            next();
            return;
        }

        // Clean up before creating new messes
        if (app.amqpConnection) {
            try {
                app.amqpConnection.disconnect();
            } finally {
                console.log('Cleaned up AMQP connection')
            }
        }
        app.amqpConnection = new AmqpConnection(url);
        app.amqpConnection.connect(next);
    };
};
//===========================
/**
 * @param url String URL to AMQP server
 * @param app ExpessJS Application
 */
function AmqpConnection (url) {
    this.url = url;
    this.connection = null;

    this.closed = false;
}

AmqpConnection.prototype.connect = function connect (callback) {
    console.log('[messaging:messaging] Connecting to AMQP server at', this.url);

    var self = this;
    amqplib.connect(this.url).then(function onConnected (connection) {
        self.connection = connection;

        connection.on('close', function onAmqpConnectionClose () {
            console.log('[messaging:messaging] AMQP connection closed...');

            self.closed = true;
        });

        connection.on('error', function onAmqpConnectionError (error) {
            console.log('[messaging:messaging] AMQP connection closed...');

            if (error && amqplib.isFatal(error)) {
                console.error('[messaging:messaging] Connection shutdown by server');
            }

            self.closed = true;
        });

        process.on('exit', function () {
            console.log('[messaging:messaging] Process exiting normally...');

            connection.close();
        });

        callback();
    }, callback);
};

AmqpConnection.prototype.disconnect = function disconnect () {
    console.log('[messaging:messaging] Disconnecting AMQP connection...');

    this.connection.close();
};


text:
<?php
namespace nlac;

class NLSCssMerge {

	protected $options = array(
		'downloadResources' => true,
		'downloadResourceRootPath' => null,
		'downloadResourceRootUrl' => null,
		'minify' => false,
		'closeCurl' => true,
	);

	protected $downloader = array();

	public function __construct($options = array(), $downloader = array()) {

		$this->downloader = $downloader instanceof NLSDownloader ? $downloader :
			new NLSDownloader(array_merge($this->downloader,$downloader));

		$this->options = array_merge($this->options, $options);

		if ($this->options['downloadResources'] && !file_exists($this->options['downloadResourceRootPath']))
			mkdir($this->options['downloadResourceRootPath']);
	}

	public function getDownloader() {
		return $this->downloader;
	}

	protected function replaceUrls($content, $baseUrl) {

		$content = preg_replace_callback('/(url\s*\(\s*[\'"]?\s*)([^\)\'"]+)/i', function($m) use ($baseUrl) {
			if (preg_match('@^data:@i',$m[2]))
				return $m[0];
			$absUrl = $this->downloader->toAbsUrl($m[2], $baseUrl);
			if ($this->options['downloadResources']) {
				$resource = $this->downloader->get($absUrl);
				$hash = crc32($absUrl);
				$ext = array();preg_match('/\.(\w+)[^.]*$/', $absUrl, $ext);
				$fn = $hash . '.' . $ext[1];
				file_put_contents($this->options['downloadResourceRootPath'] . '/' . $fn, $resource);
				return $m[1] . $this->options['downloadResourceRootUrl'] . '/' . $fn;
			} else {
				return $m[1] . $absUrl;
			}
		}, $content);

		return $content;
	}

	protected function replaceImports($content, $baseUrl, $level) {
		$content = preg_replace_callback('/^\s*@import[\'"\s]*([^\)\'"]+)[\'";\s]*/m', function($m) use ($baseUrl, $level) {

			return $this->process($m[1], $baseUrl, null, $level+1);

		}, $content);

		return $content;
	}

	//Simple css minifier script
	//code based on: http://www.lateralcode.com/css-minifier/
	protected static function minify($css) {
		$css = preg_replace( '#/\*.*?\*/#s', '', $css);
		$css = preg_replace('/\s+/', ' ', $css);
		return trim(
			str_replace(
				array('; ', ': ', ' {', '{ ', ', ', '} ', ';}'),
				array(';',  ':',  '{',  '{',  ',',  '}',  '}' ),
				$css
			)
		);
	}

	/**
	 * Processes a css recursively
	 */
	public function process($cssUrl, $baseUrl = null, $cssContent = null, $level = 0) {

		if (!$cssUrl && $cssContent===null)
			throw new \Exception('Either the content or the url of the css must be given');

		if (!$baseUrl)
			$baseUrl = $this->downloader->options['appBaseUrl'];

		if ($cssContent === null) {
			$cssUrl = $this->downloader->toAbsUrl($cssUrl, $baseUrl);
			$cssContent = $this->downloader->get($cssUrl);
		}

		$cssContent = $this->replaceUrls($cssContent, $cssUrl);
		$cssContent = $this->replaceImports($cssContent, $cssUrl, $level);

		if ($this->options['closeCurl'] && $level==0) {
			$this->downloader->close();
		}

		if ($this->options['minify'])
			$cssContent = self::minify($cssContent);

		return $cssContent;
	}

	public static function processUrl($cssUrl, $options = array(), $downloader = array()) {
		$merger = new self($options, $downloader);
		return $merger->process($cssUrl);
	}

	public static function processContent($content, $cssUrl = null, $options = array(), $downloader = array()) {
		$merger = new self($options, $downloader);
		return $merger->process($cssUrl, null, $content);
	}

}