text:
{% extends 'base.html' %}
{% load humanize %}
{% block content %}
{% load i18n %}

	  {{ content_user.username }} ({% trans "Owner" %}) /

            <form>
                {% csrf_token %}
                <input type="text" id="title"class="input-xxlarge present header" disabled="" rows="3" value="{{ xform.title }}" />
                {% if can_edit %}
                    {% trans "edit" %}
                    {% trans "save" %}
                {% endif %}
            </form>

        {% if can_edit %}

{% trans "Form ID:" %} {{ xform.id_string }}

        {% endif %}

{% trans "Description" %}

            <form>
                {% csrf_token %}
                <textarea id="description" class="input-xxlarge present" disabled="" rows="3" name="textarea">{% if xform.description %}{{ xform.description }}{% else %}{% trans "None" %}{% endif %}</textarea>
                {% if can_edit %}
                    {% trans "edit" %}
                    {% trans "save" %}
                {% endif %}
            </form>

            {% trans "XLSForm" %}
            {% trans "PUBLIC" %}
            {% trans "PRIVATE" %}
              {% trans "ENCRYPTED" %}

             {% trans "XLSForm" %}
            <button class="btn dropdown-toggle btn-success" data-toggle="dropdown">

            </button>

                <input class="input-xxlarge" type="text" size="16" value="{{ base_url }}{% url "download_xlsform" content_user.username xform.id_string %}"/>

             {% trans "XForm" %}
            <button class="btn dropdown-toggle" data-toggle="dropdown">

            </button>

                <input class="input-xxlarge" type="text" size="16" value="{{ base_url }}{% url "download_xform" content_user.username xform.id_string %}"/>

             {% trans "JSONForm" %}
            <button class="btn dropdown-toggle" data-toggle="dropdown">

            </button>

                <input class="input-xxlarge" type="text" size="16" value="{{ base_url }}{% url "download_jsonform" content_user.username xform.id_string %}"/>

            {% trans "License" %}:
            {% if can_edit %}
                {% for field in form_license_form %}
                    {{ field }}
                {% endfor %}
                {% trans "edit" %}
                {% trans "save" %}
            {% else %}
                {{ form_license|default:'No license' }}
            {% endif %}

{% trans "License information" %}

        {% if user.is_authenticated and content_user.username != user.username and xform.xls|length > 0 and not cloned %}

                {% trans "Clone" %}

        {% endif %}

            {% trans "Form Data" %}
            {% trans "PUBLIC" %}
            {% trans "PRIVATE" %}
              {% trans "ENCRYPTED" %}

        {% if xform.shared_data or can_view %}
        {% if not xform.encrypted and xform.submission_count > 0 %}

             {% trans "csv" %}
            <button class="btn dropdown-toggle" data-toggle="dropdown">

            </button>

                <input class="input-xxlarge" type="text" size="16" value="{{base_url}}{% url "onadata.apps.viewer.views.export_list" content_user.username xform.id_string 'csv' %}"/>

             {% trans "csv zip" %}
            <button class="btn dropdown-toggle" data-toggle="dropdown">

            </button>

                <input class="input-xxlarge" type="text" size="16" value="{{base_url}}{% url "onadata.apps.viewer.views.export_list" content_user.username xform.id_string 'csv_zip' %}"/>

             {% trans "sav zip" %}
            <button class="btn dropdown-toggle" data-toggle="dropdown">

            </button>

                <input class="input-xxlarge" type="text" size="16" value="{{base_url}}{% url "onadata.apps.viewer.views.export_list" content_user.username xform.id_string 'sav_zip' %}"/>

             {% trans "xls" %}
            <button class="btn dropdown-toggle" data-toggle="dropdown">

            </button>

                <input class="input-xxlarge" type="text" size="16" value="{{base_url}}{% url "onadata.apps.viewer.views.export_list" content_user.username xform.id_string 'xls' %}"/>

             {% trans "kml" %}
            <button class="btn dropdown-toggle" data-toggle="dropdown">

            </button>

                <input class="input-xxlarge" type="text" size="16" value="{{base_url}}{% url "onadata.apps.viewer.views.export_list" content_user.username xform.id_string 'kml' %}"/>

             {% trans "zip" %}
            <button class="btn dropdown-toggle" data-toggle="dropdown">

            </button>

                <input class="input-xxlarge" type="text" size="16" value="{{base_url}}{% url "onadata.apps.viewer.views.export_list" content_user.username xform.id_string 'zip' %}"/>

             {% trans "gdocs" %}
            <button class="btn dropdown-toggle" data-toggle="dropdown">

            </button>

                    <input class="input-xxlarge" type="text" size="16" value="{{base_url}}{% url "onadata.apps.viewer.views.export_list" content_user.username xform.id_string 'gdoc' %}"/>

{% trans "Submissions:" %} {{ xform.submission_count|intcomma }}

            {% trans "License:" %}
            {% if can_edit %}
                {% for field in data_license_form %}
                    {{ field }}
                {% endfor %}
                {% trans "edit" %}
                {% trans "save" %}
            {% else %}
                {{ data_license|default:'No license' }}
            {% endif %}

{% trans "License information" %}

				{% if xform.has_instances_with_geopoints %}

				 {% trans "Map" %}

		        {% endif %}

               {% trans "Photos" %}

                 {% trans "View Data" %}

                 {% trans "Browse Data" %}

                 {% trans "Statistics" %}

        {% else %}
            {% if can_edit %}

            {% else %}
                {% trans "NO DATA" %}
            {% endif %}
		{% endif %}
		{% endif %}

                  {% if can_edit or xform.is_crowd_form %}

                       {% trans "Enter Web Form" %}

                   {% trans "Mobile" %}
                  {% endif %}
                  {% if can_edit or xform.is_crowd_form or xform.shared %}

                       {% trans "Preview Form" %}

                  {% endif %}

              {% if can_edit or xform.is_crowd_form or xform.shared %}

                      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

{{ xform.title }} - {% trans "Preview" %}

              {% endif %}

{% trans "Source" %}

                <form action="{% url "onadata.apps.main.views.edit" content_user.username xform.id_string %}" method="post" enctype="multipart/form-data">

                {% if source.data_file %}

{{ source.data_file.name }}

                {% endif %}
                {% csrf_token %}
                <input type="text" id="source" class="input-xxlarge present" disabled="" rows="3" value="{{ source.data_value|default:"None provided" }}" />
                {% if can_edit %}
                    {% trans "edit" %}
                    {% trans "save" %}
                {% endif %}

                {% if can_edit %}
                    {% csrf_token %}

                    {{ source_form.as_table }}

                    <input type="submit" class="btn" value="{% trans 'Upload' %}" />
                {% endif %}
            </form>

{% trans "Methodology" %}

                {% for doc in supporting_docs %}

{{ doc.data_value }}
                    {% if can_edit %}
                    ||  {% trans "remove" %}
                    {% endif %}

                {% endfor %}
                {% if can_edit %}
                    <form action="{% url "onadata.apps.main.views.edit" content_user.username xform.id_string %}" method="post" enctype="multipart/form-data">
                        {% csrf_token %}

                            {{ doc_form.as_table }}

                        <input type="submit" class="btn" value="{% trans 'Upload' %}" />
                    </form>
                {% endif %}

        {% if is_owner %}

{% trans "Rest Services" %}

        {% endif %}

{% blocktrans %}Media  jpeg/png/mp3/wav/3gp allowed{% endblocktrans %}

            {% for media in media_upload %}

{{ media.data_value }}
              {% if can_edit %}
              – {% trans "remove" %}
              {% endif %}

            {% endfor %}
            {% if can_edit %}
            <form action="{% url "onadata.apps.main.views.edit" content_user.username xform.id_string %}" method="post" enctype="multipart/form-data">
                {% csrf_token %}

Media upload:	<input type="file" multiple="" name="media" id="id_media">

                <input type="submit" class="btn" value="{% trans 'Upload' %}" />
            </form>
            {% endif %}

{% trans "Mapbox Layer" %}

            {% if mapbox_layer %}

{{ mapbox_layer.map_name }} –
            {% trans "Attribution:" %} {{ mapbox_layer.attribution }}
            {% if can_edit %}
            – {% trans "remove" %}

            {% endif %}
            {% endif %}
            {% if can_edit %}
            <form action="{% url "onadata.apps.main.views.edit" content_user.username xform.id_string %}" method="post">
                {% csrf_token %}

                {{ mapbox_layer_form.as_table }}

                <input type="submit" class="btn" value="{% trans 'Upload' %}" />
            </form>
            {% endif %}

{% trans "SMS Support" %} (<acronym title="SMS Support is in beta stage now. Please use carefully as API and IDs might change.">beta</acronym>)

                <form action="{% url "onadata.apps.main.views.edit" content_user.username xform.id_string %}" method="post" enctype="multipart/form-data">

                {% if xform.allows_sms %}

{% blocktrans %}This form has enabled SMS submissions.{% endblocktrans %} {% blocktrans with id_string=xform.sms_id_string %}Submit to this form using the "{{ id_string }}" identifier.{% endblocktrans %}

                {% endif %}
                {% if can_edit %}
                    {% csrf_token %}
                    <input type="hidden" name="enable_sms_support_trigger" value="yes" />

                    {{ sms_support_form.as_table }}

                    <input type="submit" class="btn btn-primary" value="{% trans "Save Changes" %}" />
                {% endif %}
            	</form>
            	{% autoescape off %}

            	{% if xform.allows_sms %}

{% trans "Expected Format:" %}

{{ sms_support_doc.line_names }}

            	{% for helper in sms_support_doc.helpers %}

{{ forloop.counter0 }} {{ helper.0 }}: {{helper.1}}

            	{% endfor %}

{% trans "Example" %}

{{ sms_support_doc.line_values }}

            	{% else %}

{{ sms_compatible.text }}

            	{% endif %}

{% trans "Usage" %}

Note that for each case, you can select either the simplest form of the URL (containing only your username) or the one including the id_string of the form.

The latter works without specifyin the SMS Keyword in front of every message.

You would use it when your SMS Setup/Provider is used for only one form.

            	<select id="sms_support_api"><option>{% trans "Select an SMS API" %}</option>{% for provider in sms_providers_doc %}<option value="{{ provider.id }}">{{ provider.name }}</option>{% endfor %}<option value="generic">{% trans "Generic SMS API" %}</option></select>

{% trans "Use the Generic SMS API to write your own wrapper around Formhub." %}

{% trans "Single SMS Submission" %}
[GET] {{ url_root }}{% url "sms_submission" username=content_user.username %}

							[GET] {{ url_root }}{% url "sms_submission_form" username=content_user.username id_string=xform.id_string %}

            				{% trans "Params:" %} {"identity": "SENDER PHONE NUMBER", "text": "TEXT MESSAGE"}

            				{% trans "Returns:" %} {"status": "STATUS", "message": "MESSAGE", "id": "ID"}

{% trans "Multiple SMS Submissions at once" %}
[POST] {{ url_root }}{% url "sms_submissions" username=content_user.username %}

            				[POST] {{ url_root }}{% url "sms_submissions_form" username=content_user.username id_string=xform.id_string %}

            				{% trans "Params:" %} {"messages": [{"identity": "SENDER PHONE NUMBER", "text": "TEXT MESSAGE"}, ]

            				{% trans "Returns:" %} [{"status": "STATUS", "message": "MESSAGE", "id": "ID"}, ]

STATUS: {% trans "One of" %} ACCEPTED, REJECTED, PARSING_FAILED

            		   MESSAGE: {% trans "Either an error or success message. Suitable for end user." %}

            		   ID: {% trans "Only if successful. A unique ID of the submission." %}

            	{% for provider in sms_providers_doc %}
{{ provider.doc }}
{% endfor %}
            	{% endautoescape %}

        {% if is_owner %}

{% trans "Settings" %}

          {% trans "Form Shared" %}
            <input id="form-shared" type="checkbox"{% if xform.shared %} checked=""{% endif %} data-url="{% url "onadata.apps.main.views.edit" content_user.username xform.id_string %}" />

          {% trans "Data Shared" %}

            <input id="data-shared" type="checkbox"{% if xform.shared_data %} checked=""{% endif %} data-url="{% url "onadata.apps.main.views.edit" content_user.username xform.id_string %}" />

          {% trans "Crowdform" %}

            <input id="crowd-form" type="checkbox" {% if xform.is_crowd_form %}
            checked="" {% endif %} data-url="{% url "onadata.apps.main.views.edit" content_user.username xform.id_string  %}" />

          {% trans "Form Active" %}

            <input id="active-form" type="checkbox"{% if xform.downloadable %} checked=""{% endif %} data-url="{% url "onadata.apps.main.views.edit" content_user.username xform.id_string %}" />

          {% trans "Delete Form" %}

              <form action="{% url "onadata.apps.logger.views.delete_xform" username=user.username id_string=xform.id_string %}" method="post">
              {% csrf_token %}

                      ×

{% trans "Delete Confirmation" %}

{% blocktrans with title=xform.title nb_sub=xform.submission_count|intcomma %}Are you sure you want to delete the form '{{ title }}'? This form has {{ nb_sub }} submissions associated with it that will also be deleted. If you are unsure about deleting this form press 'Cancel' and consider 'Archiving' the form instead.{% endblocktrans %}

                      <button class="btn btn-primary form-submit">Delete</button>
                      {% trans "Cancel" %}

              </form>

              {% trans "Delete" %}

{% trans "bamboo" %}

            {% if xform.bamboo_dataset %}
                {% blocktrans with dataset=xform.bamboo_dataset %}bamboo dataset: {{ dataset }}{% endblocktrans %}
            {% else %}
                {% blocktrans %}bamboo link is not active{% endblocktrans %}
            {% endif %}
            {% if xform.submission_count = 0 %}

{% trans "bamboo requires at least one submission." %}
            {% else %}<form action="{% url "onadata.apps.main.views.link_to_bamboo" content_user.username xform.id_string %}" method="post">
                {% csrf_token %}
                {% if xform.bamboo_dataset %}
                    <input type="submit" class="btn" value="{% trans "Regenerate" %}" />
                {% else %}
                    <input type="submit" class="btn" value="{% trans "Activate" %}" />
                {% endif %}
                </form>
            {% endif %}

{% trans "Sharing" %}

            {% if public_link %}
            {% url "onadata.apps.main.views.show" xform.uuid as form_url %}
            {% blocktrans %}Sharing by link is on with URL {{ base_url }}{{ form_url }}{% endblocktrans %}
            {% else %}
            {% blocktrans %}Sharing by link is off{% endblocktrans %}
            {% endif %}

            <form action="{% url "onadata.apps.main.views.set_perm" content_user.username xform.id_string %}" method="post">
                {% csrf_token %}
                <input type="hidden" name="perm_type" value="link"/>
                <input type="hidden" name="for_user" value="toggle"/>
                <input type="submit" class="btn" value="{% if public_link %}{% trans "Turn off" %}{% else %}{% trans "Turn on" %}{% endif %}" />
            </form>
            {% if users_with_perms|length %}

                {% for user, perms in users_with_perms %}

{{ user }}: {{ perms }}

                {% endfor %}

            {% endif %}
            <form action="{% url "onadata.apps.main.views.set_perm" content_user.username xform.id_string %}" method="post">
                {% csrf_token %}

                {{ permission_form.as_table }}

                <input type="submit" class="btn" value="{% trans 'Submit' %}" />
            </form>

        {% endif %}

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

{%  trans "Mobile Form" %}

        {%  trans "DOWNLOAD " %}

        {%  trans " Scan - QR Reader" %}

{% endblock %}

{% block styles %}
{{ block.super }}
 <link href="{{STATIC_URL}}css/iphone-btn-style.css" rel="stylesheet"/>
{% endblock %}

{% block javascript %}
{{ block.super }}

  {% if user.is_authenticated %}

  {% endif %}

{% endblock %}


text:
module Paperclip
  class CommandLine
    class << self
      attr_accessor :path
    end

    def initialize(binary, params = "", options = {})
      @binary            = binary.dup
      @params            = params.dup
      @options           = options.dup
      @swallow_stderr    = @options.has_key?(:swallow_stderr) ? @options.delete(:swallow_stderr) : Paperclip.options[:swallow_stderr]
      @expected_outcodes = @options.delete(:expected_outcodes)
      @expected_outcodes ||= [0]
    end

    def command
      cmd = []
      cmd << full_path(@binary)
      cmd << interpolate(@params, @options)
      cmd << bit_bucket if @swallow_stderr
      cmd.join(" ")
    end

    def run
      Paperclip.log(command)
      begin
        output = self.class.send(:'`', command)
      rescue Errno::ENOENT
        raise Paperclip::CommandNotFoundError
      end
      if $?.exitstatus == 127
        raise Paperclip::CommandNotFoundError
      end
      unless @expected_outcodes.include?($?.exitstatus)
        raise Paperclip::PaperclipCommandLineError, "Command '#{command}' returned #{$?.exitstatus}. Expected #{@expected_outcodes.join(", ")}"
      end
      output
    end

    private

    def full_path(binary)
      [self.class.path, binary].compact.join("/")
    end

    def interpolate(pattern, vars)
      # interpolates :variables and :{variables}
      pattern.gsub(%r#:(?:\w+|\{\w+\})#) do |match|
        key = match[1..-1]
        key = key[1..-2] if key[0,1] == '{'
        if invalid_variables.include?(key)
          raise PaperclipCommandLineError,
            "Interpolation of #{key} isn't allowed."
        end
        shell_quote(vars[key.to_sym])
      end
    end

    def invalid_variables
      %w(expected_outcodes swallow_stderr)
    end

    def shell_quote(string)
      return "" if string.nil? or string.blank?
      if self.class.unix?
        string.split("'").map{|m| "'#{m}'" }.join("\\'")
      else
        %{"#{string}"}
      end
    end

    def bit_bucket
      self.class.unix? ? "2>/dev/null" : "2>NUL"
    end

    def self.unix?
      File.exist?("/dev/null")
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.geode.security.query;

import static org.apache.geode.cache.Region.SEPARATOR;
import static org.apache.geode.cache.RegionShortcut.PARTITION;
import static org.apache.geode.cache.RegionShortcut.REPLICATE;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.security.query.data.QueryTestObject;
import org.apache.geode.test.junit.categories.OQLQueryTest;
import org.apache.geode.test.junit.categories.SecurityTest;
import org.apache.geode.test.junit.runners.CategoryWithParameterizedRunnerFactory;

@RunWith(Parameterized.class)
@Category({SecurityTest.class, OQLQueryTest.class})
@Parameterized.UseParametersRunnerFactory(CategoryWithParameterizedRunnerFactory.class)
public class QuerySecurityForbiddenQueriesDistributedTest
    extends AbstractQuerySecurityDistributedTest {

  @Parameterized.Parameters(name = "User:{0}, RegionType:{1}")
  public static Object[] usersAndRegionTypes() {
    return new Object[][] {
        {"super-user", REPLICATE}, {"super-user", PARTITION},
        {"dataReader", REPLICATE}, {"dataReader", PARTITION},
        {"dataReaderRegion", REPLICATE}, {"dataReaderRegion", PARTITION},
        {"dataReaderRegionKey", REPLICATE}, {"dataReaderRegionKey", PARTITION},
        {"clusterManagerDataReader", REPLICATE}, {"clusterManagerDataReader", PARTITION},
        {"clusterManagerDataReaderRegion", REPLICATE}, {"clusterManagerDataReaderRegion", PARTITION}
    };
  }

  @Parameterized.Parameter
  public String user;

  @Parameterized.Parameter(1)
  public RegionShortcut regionShortcut;

  private String regexForExpectedExceptions =
      ".*Unauthorized access.*|.*dataReaderRegionKey not authorized for DATA:READ:region.*";

  @Before
  public void setUp() throws Exception {
    super.setUp(user, regionShortcut);

    keys = new Object[] {"key-0", "key-1"};
    values = new Object[] {
        new QueryTestObject(1, "John"),
        new QueryTestObject(3, "Beth")
    };

    putIntoRegion(superUserClient, keys, values, regionName);
  }

  /* ----- Implicit Getter Tests ----- */
  @Test
  public void queryWithImplicitMethodInvocationOnWhereClauseShouldThrowSecurityException() {
    String query = "SELECT * FROM " + SEPARATOR + regionName + " r WHERE r.name = 'Beth'";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query,
        regexForExpectedExceptions);
  }

  @Test
  public void queryWithImplicitMethodInvocationOnSelectClauseShouldThrowSecurityException() {
    String query = "SELECT r.name FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query,
        regexForExpectedExceptions);
  }

  @Test
  public void queriesWithImplicitMethodInvocationUsedWithinAggregateFunctionsShouldThrowSecurityException() {
    String queryCount = "SELECT COUNT(r.name) FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryCount,
        regexForExpectedExceptions);

    String queryMax = "SELECT MAX(r.name) FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryMax,
        regexForExpectedExceptions);

    String queryMin = "SELECT MIN(r.name) FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryMin,
        regexForExpectedExceptions);

    String queryAvg = "SELECT AVG(r.name) FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryAvg,
        regexForExpectedExceptions);

    String querySum = "SELECT SUM(r.name) FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, querySum,
        regexForExpectedExceptions);
  }

  @Test
  public void queryWithImplicitMethodInvocationUsedWithinDistinctClauseShouldThrowSecurityException() {
    String query = "<TRACE> SELECT DISTINCT * from " + SEPARATOR + regionName
        + " r WHERE r.name IN SET('John', 'Beth') ORDER BY r.id asc LIMIT 2";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query,
        regexForExpectedExceptions);
  }

  @Test
  public void queryWithImplicitMethodInvocationOnInnerQueriesShouldThrowSecurityException() {
    String query = "SELECT * FROM " + SEPARATOR + regionName
        + " r1 WHERE r1.name IN (SELECT r2.name FROM " + SEPARATOR
        + regionName + " r2)";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query,
        regexForExpectedExceptions);
  }

  /* ----- Direct Getter Tests ----- */
  @Test
  public void queryWithExplicitMethodInvocationOnWhereClauseShouldThrowSecurityException() {
    String query = "SELECT * FROM " + SEPARATOR + regionName + " r WHERE r.getName = 'Beth'";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query,
        regexForExpectedExceptions);
  }

  @Test
  public void queryWithExplicitMethodInvocationOnSelectClauseShouldThrowSecurityException() {
    String query = "SELECT r.getName FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query,
        regexForExpectedExceptions);
  }

  @Test
  public void queriesWithExplicitMethodInvocationUsedWithinAggregateFunctionsShouldThrowSecurityException() {
    String queryCount = "SELECT COUNT(r.getName) FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryCount,
        regexForExpectedExceptions);

    String queryMax = "SELECT MAX(r.getName) FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryMax,
        regexForExpectedExceptions);

    String queryMin = "SELECT MIN(r.getName) FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryMin,
        regexForExpectedExceptions);

    String queryAvg = "SELECT AVG(r.getName) FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryAvg,
        regexForExpectedExceptions);

    String querySum = "SELECT SUM(r.getName) FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, querySum,
        regexForExpectedExceptions);
  }

  @Test
  public void queryWithExplicitMethodInvocationUsedWithinDistinctClauseShouldThrowSecurityException() {
    String query = "<TRACE> SELECT DISTINCT * from " + SEPARATOR + regionName
        + " r WHERE r.getName IN SET('John', 'Beth') ORDER BY r.id asc LIMIT 2";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query,
        regexForExpectedExceptions);
  }

  @Test
  public void queryWithExplicitMethodInvocationOnInnerQueriesShouldThrowSecurityException() {
    String query = "SELECT * FROM " + SEPARATOR + regionName
        + " r1 WHERE r1.getName IN (SELECT r2.getName FROM " + SEPARATOR + regionName + " r2)";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query,
        regexForExpectedExceptions);
  }

  /* ----- Region Methods ----- */
  @Test
  public void queriesWithAllowedRegionMethodInvocationsShouldThrowSecurityExceptionForNonAuthorizedUsers() {
    Assume.assumeTrue(user.equals("dataReaderRegionKey"));

    String queryValues = "SELECT * FROM " + SEPARATOR + regionName + ".values";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryValues,
        regexForExpectedExceptions);

    String queryKeySet = "SELECT * FROM " + SEPARATOR + regionName + ".keySet";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryKeySet,
        regexForExpectedExceptions);

    String queryContainsKey =
        "SELECT * FROM " + SEPARATOR + regionName + ".containsKey('" + keys[0] + "')";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryContainsKey,
        regexForExpectedExceptions);

    String queryEntrySet = "SELECT * FROM " + SEPARATOR + regionName + ".get('" + keys[0] + "')";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryEntrySet,
        regexForExpectedExceptions);
  }

  @Test
  public void queriesWithRegionMutatorMethodInvocationsShouldThrowSecurityException() {
    String queryCreate = "SELECT * FROM " + SEPARATOR + regionName + ".create('key2', 15)";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryCreate,
        regexForExpectedExceptions);
    assertRegionData(superUserClient, Arrays.asList(values));

    String queryPut = "SELECT * FROM " + SEPARATOR + regionName + ".put('key-2', 'something')";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryPut,
        regexForExpectedExceptions);
    assertRegionData(superUserClient, Arrays.asList(values));

    String queryRemove = "SELECT * FROM " + SEPARATOR + regionName + ".remove('key-0')";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryRemove,
        regexForExpectedExceptions);
    assertRegionData(superUserClient, Arrays.asList(values));

    String queryDestroy = "SELECT * FROM " + SEPARATOR + regionName + ".destroyRegion()";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, queryDestroy,
        regexForExpectedExceptions);
  }

  /* ----- Other Forbidden Methods ----- */
  @Test
  public void queryWithGetClassShouldThrowSecurityException() {
    String query1 = "SELECT * FROM " + SEPARATOR + regionName + " r WHERE r.getClass != '1'";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query1,
        regexForExpectedExceptions);

    String query2 = "SELECT r.getClass FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query2,
        regexForExpectedExceptions);

    String query3 = "SELECT r.getClass() FROM " + SEPARATOR + regionName + " r";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query3,
        regexForExpectedExceptions);

    String query4 = "SELECT * FROM " + SEPARATOR + regionName + " r WHERE r.getClass != 'blah'";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query4,
        regexForExpectedExceptions);

    String query5 = "SELECT * FROM " + SEPARATOR + regionName + " r WHERE r.getClass() != '1'";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query5,
        regexForExpectedExceptions);

    String query6 = "SELECT * FROM " + SEPARATOR + regionName + " r WHERE r.Class != '1'";
    executeQueryAndAssertThatNoAuthorizedExceptionWasThrown(specificUserClient, query6,
        regexForExpectedExceptions);
  }

  @Test
  public void queryWithExplicitNonExistingMethodInvocationShouldReturnUndefined() {
    Assume.assumeFalse(user.equals("dataReaderRegionKey"));
    String query = "SELECT r.getInterestListRegex() FROM " + SEPARATOR + regionName + " r";
    List<Object> expectedResults = Arrays.asList(QueryService.UNDEFINED, QueryService.UNDEFINED);
    executeQueryAndAssertExpectedResults(specificUserClient, query, expectedResults);
  }

  @Test
  public void queryWithCloneMethodOnQRegionShouldReturnEmptyResult() {
    Assume.assumeFalse(user.equals("dataReaderRegionKey"));
    String query = "SELECT * FROM " + SEPARATOR + regionName + ".clone";
    List<Object> expectedResults = Collections.emptyList();
    executeQueryAndAssertExpectedResults(specificUserClient, query, expectedResults);
  }

  @Test
  public void queryWithExplicitNonExistingMethodInvocationOnQRegionShouldReturnEmptyResult() {
    Assume.assumeFalse(user.equals("dataReaderRegionKey"));
    String query = "SELECT * FROM " + SEPARATOR + regionName + ".getKey('" + keys[0] + "')";
    List<Object> expectedResults = Collections.emptyList();
    executeQueryAndAssertExpectedResults(specificUserClient, query, expectedResults);
  }

  @Test
  public void queryWithExplicitCreateMethodInvocationOnRegionShouldReturnUndefinedAndDoNotModifyRegion() {
    Assume.assumeFalse(user.equals("dataReaderRegionKey"));
    String query = "SELECT r.create('key2', 15) FROM " + SEPARATOR + regionName + " r";
    List<Object> expectedResults = Arrays.asList(QueryService.UNDEFINED, QueryService.UNDEFINED);
    executeQueryAndAssertExpectedResults(specificUserClient, query, expectedResults);
    assertRegionData(specificUserClient, Arrays.asList(values));
  }

  @Test
  public void queryWithExplicitMutatorMethodInvocationsOnRegionShouldReturnEmptyResultAndDoNotModifyRegion() {
    Assume.assumeFalse(user.equals("dataReaderRegionKey"));
    String queryDestroy =
        "SELECT * FROM " + SEPARATOR + regionName + ".destroyKey('" + keys[0] + "')";
    executeQueryAndAssertExpectedResults(specificUserClient, queryDestroy, Collections.emptyList());
    assertRegionData(superUserClient, Arrays.asList(values));

    String queryPutIfAbsent =
        "SELECT * FROM " + SEPARATOR + regionName + ".putIfAbsent('key-2', 'something')";
    executeQueryAndAssertExpectedResults(specificUserClient, queryPutIfAbsent,
        Collections.emptyList());
    assertRegionData(superUserClient, Arrays.asList(values));

    String queryReplace =
        "SELECT * FROM " + SEPARATOR + regionName + ".replace('key-0', 'something')";
    executeQueryAndAssertExpectedResults(specificUserClient, queryReplace, Collections.emptyList());
    assertRegionData(superUserClient, Arrays.asList(values));
  }
}


text:
//
//  BBTextStatusBar.h
//  YCStock
//
//  Created by meiosis chen on 12-8-21.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "BBStatusBarUpdating.h"
#import "BBStatusBarModel.h"

/**
 *  状态栏文字窗口
 */
NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.")
@interface BBStatusBarWindow : UIWindow
{
    UIView<BBStatusBarUpdating> *_statusBar0;
    UIView<BBStatusBarUpdating> *_statusBar1;
    BOOL _isSwaped;

    BOOL _isAnimating;
    NSMutableArray *_array;
}

@property (nonatomic, assign) BOOL isAutoHidden; // 播放到最后一个时是否自动隐藏, 默认YES

+ (BBStatusBarWindow *)sharedManager;

+ (void)showStatusBarWithModel:(id<BBStatusBarModel>)data;
+ (void)showStatusBarWithArray:(NSArray *)array; // id<BBStatusBarModel> 数组

+ (void)hiddenStatusBarAnimated:(BOOL)animated;

@end


text:
import argparse
import json

import numpy as np
import requests
from keras.preprocessing import image
from keras.applications import inception_v3

# pip install pillow
# pip install keras_applications
# pip install keras_preprocessing

# Argument parser for giving input image_path from command line
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
                help="path of the image")
args = vars(ap.parse_args())

image_path = args['image']
# Preprocessing our input image
img = image.img_to_array(image.load_img(image_path, target_size=(224, 224))) / 255.

# this line is added because of a bug in tf_serving(1.10.0-dev)
# img = img.astype('float16')

payload = {
    "instances": [{'image': img.tolist()}]
}

# sending post request to TensorFlow Serving server
r = requests.post('http://localhost:8501/v1/models/saved_models:predict', json=payload)
pred = json.loads(r.content.decode('utf-8'))
print(r.content)

# Decoding the response
# decode_predictions(preds, top=5) by default gives top 5 results
# You can pass "top=10" to get top 10 predicitons
print(json.dumps(inception_v3.decode_predictions(np.array(pred['predictions']))[0]))


text:
<?php

namespace pdepend\reflection\api;

/**
 * This class is used a container for optional property or parameter default
 * values.
 *
 * @category  PHP
 * @package   pdepend\reflection\api
 * @author    Manuel Pichler <mapi@pdepend.org>
 * @copyright 2009-2010 Manuel Pichler. All rights reserved.
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version   Release: @package_version@
 * @link      http://pdepend.org/
 */
class StaticReflectionValue
{
    /**
     * The scalar default value.
     *
     * @var mixed
     */
    private $_data = null;

    /**
     * Constructs a new default value instance.
     *
     * @param mixed $data The scalar default value.
     */
    public function __construct( $data )
    {
        $this->_data = $data;
    }

    /**
     * Returns the raw default data.
     *
     * @return mixed
     */
    public function getData()
    {
        return $this->_data;
    }

    /**
     * Returns a string representation of the encapsulated value.
     *
     * @return string
     */
    public function __toString()
    {
        if ( is_array( $this->_data ) )
        {
            return 'Array';
        }
        else if ( is_bool( $this->_data ) )
        {
            return ( $this->_data ? 'true' : 'false' );
        }
        else if ( is_null( $this->_data ) )
        {
            return 'NULL';
        }
        else if ( is_string( $this->_data ) )
        {
            return "'" . str_replace( "'", "\\'", $this->_data ) . "'";
        }
        return (string) $this->_data;
    }
}


text:
package com.singhgurjit.babycare.babycare;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class RemindersScreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reminders_screen);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

}


text:
@class Mp3PlayerButton;

#define kNCMusicEngineCacheFolderName @"com.nickcheng.NCMusicEngine"
#define kNCMusicEngineCheckMusicInterval 0.1f // Seconds
#define kNCMusicEngineSizeBuffer 100000.0f // Bytes
#define kNCMusicEnginePauseMargin 1.0f  // Seconds
#define kNCMusicEnginePlayMargin 5.0f // Seconds

@protocol NCMusicEngineDelegate;

typedef enum {
  NCMusicEnginePlayStateStopped,
  NCMusicEnginePlayStatePlaying,
  NCMusicEnginePlayStatePaused,
  NCMusicEnginePlayStateEnded,
  NCMusicEnginePlayStateError
} NCMusicEnginePlayState;

typedef enum {
  NCMusicEngineDownloadStateNotDownloaded,
  NCMusicEngineDownloadStateDownloading,
//  NCMusicEngineDownloadStatePartial,
  NCMusicEngineDownloadStateDownloaded,
  NCMusicEngineDownloadStateError
} NCMusicEngineDownloadState;

@interface NCMusicEngine : NSObject
{
    Mp3PlayerButton *button;
}

@property (nonatomic, strong) Mp3PlayerButton *button;
@property (nonatomic, assign, readonly) NCMusicEnginePlayState playState;
@property (nonatomic, assign, readonly) NCMusicEngineDownloadState downloadState;
@property (nonatomic, strong, readonly) NSError *error;
@property (weak) id<NCMusicEngineDelegate> delegate;

- (id)initWithSetBackgroundPlaying:(BOOL)setBGPlay;
- (void)playUrl:(NSURL*)url;
- (void)playUrl:(NSURL *)url withCacheKey:(NSString *)cacheKey;
- (void)pause;
- (void)resume;
- (void)stop; // Stop music and stop download.

@end

@protocol NCMusicEngineDelegate <NSObject>

//- (NSURL*)engineExpectsNextUrl:(NCMusicEngine *)engine;

@optional
- (void)engine:(NCMusicEngine *)engine didChangePlayState:(NCMusicEnginePlayState)playState;
- (void)engine:(NCMusicEngine *)engine didChangeDownloadState:(NCMusicEngineDownloadState)downloadState;
- (void)engine:(NCMusicEngine *)engine downloadProgress:(CGFloat)progress;
- (void)engine:(NCMusicEngine *)engine playProgress:(CGFloat)progress;

@end


text:
@javax.xml.bind.annotation.XmlSchema(namespace = "http://service.agent.control.geospace/")
package geospace.control.agent.service;


text:
import React, {Component} from 'react';
import TextField from 'material-ui/TextField';
import Button from 'material-ui/Button';
import {validateRevealAuctionBid} from '../../lib/ensService';
import {TimeDuration} from './TimeDuration';
import {RevealAuctionConfirmDialog} from './RevealAuctionConfirmDialog';
import {RevealAuctionJsonDialog} from './RevealAuctionJsonDialog';
import './RevealAuctionForm.css';

const EthBidTextField = (props) => (
  <TextField
    error={props.error}
    id="ethBid"
    name="ethBid"
    label="ETH"
    value={props.value}
    onChange={props.onChange}
    margin="normal"
    placeholder="0.01"
    helperText={props.error ? props.errMsg : 'Bid amount'}
  />
);

const SecretTextField = (props) => (
  <TextField
    error={props.error}
    id="secret"
    name="secret"
    label="Secret"
    value={props.value}
    onChange={props.onChange}
    margin="normal"
    placeholder="pass phrase"
    helperText={props.error ? props.errMsg :"Please protect your bid with random numbers and characters"}
  />
);

const GasTextField = (props) => (
  <TextField
    error={props.error}
    id="gas"
    name="gas"
    label="Gas Price (Gwei)"
    type="number"
    value={props.value}
    onChange={props.onChange}
    margin="normal"
    helperText={props.error ? props.errMsg : "Recommend use 21 Gwei"}
  />
);

const ConfirmFormSubmit = (props) => {
  const disabled = props.disabled;
  const classes = !disabled ? 'KeystoreUploader-button': '';

  return (

      <Button
        className={classes}
        disabled={disabled}
        raised
        label="Dialog"
        onClick={props.onClick} >
        Confirm Submit
      </Button>

  );
};

const ImportJsonButton = (props) => {
  return (

      <Button
        raised
        label="ImportJsonDialog"
        onClick={props.onClick} >
        Reveal By JSON
      </Button>

  )
}

const FormFields = (props) => (

    {/* <EmailTextField
      value={props.email}
      onChange={props.handleInputChange}
    /> */}
    <EthBidTextField
      error={props.ethBidErr}
      errMsg={props.ethBidErrMsg}
      value={props.ethBid}
      onChange={props.handleInputChange}
    />
    <SecretTextField
      error={props.secretErr}
      errMsg={props.secretErrMsg}
      value={props.secret}
      onChange={props.handleInputChange}
    />
    <GasTextField
      error={props.gasErr}
      errMsg={props.gasErrMsg}
      value={props.gas}
      onChange={props.handleInputChange}
    />

);

export class RevealAuctionForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false,
      email: '',
      ethBid: '0.01',
      ethBidErr: false,
      ethBidErrMsg: '',
      secret: '0',
      secretErr: false,
      secretErrMsg: '',
      gas: '21',
      gasErr: false,
      gasErrMsg: '',
      importDialogOpen: false,
      revealJson: '',
      revealJsonErr: false,
      revealJsonErrMsg: '',
    }
    this.handleOpen = this.handleOpen.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.checkEthBid = this.checkEthBid.bind(this);
    this.checkSecret = this.checkSecret.bind(this);
    this.checkGas = this.checkGas.bind(this);
    this.submitDisabled = this.submitDisabled.bind(this);
    this.inputResult = this.inputResult.bind(this);
    this.handleImportDialogOpen = this.handleImportDialogOpen.bind(this);
    this.handleImportDialogClose = this.handleImportDialogClose.bind(this);
    this.handleParseImportJson = this.handleParseImportJson.bind(this);
  }

  handleOpen = () => {
    if (!(this.props.address && this.props.privateKey)) {
      this.props.handleWarningMessageOpen("Should login first");
      return
    }

    const validateObj = validateRevealAuctionBid(
      this.props.searchResult.searchName,
      this.state.ethBid, this.state.secret, this.props.privateKey
    );
    if (!validateObj.validate) {
      this.props.handleMessageOpen(validateObj.err);
      return
    }

    this.setState({open: true});
  }

  handleClose = () => {
    this.setState({open: false});
  }

  handleInputChange(event) {
    const {name, value} = event.target;
    this.setState({ [name]: value });

    switch (name) {
      case 'ethBid':
        this.checkEthBid(value);
        break;
      case 'secret':
        this.checkSecret(value);
        break;
      case 'gas':
        this.checkGas(value);
        break;
      default:
    }
  }

  checkEthBid = (v) => {

    // validate input only number
    const reg = /^[+-]?\d+(\.\d+)?$/;
    if (!reg.test(v)) {
      this.setState({
        ethBidErr: true,
        ethBidErrMsg: 'Bid amount: Please input a valid number'
      })
      return;
    }

    // validate input should not be zero
    if (parseFloat(v, 10) === 0) {
      this.setState({
        ethBidErr: true,
        ethBidErrMsg: 'Bid amount: Please input a non-zero number'
      });
      return;
    }

    if (parseFloat(v, 10) < 0.01) {
      this.setState({
        ethBidErr: true,
        ethBidErrMsg: 'Bid amount: Minimum bid must at least 0.01'
      });
      return;
    }

    this.setState({
      ethBidErr: false,
      ethBidErrMsg: ''
    })
  }

  checkSecret = (v) => {
    // validate value should present
    if (v === '') {
      this.setState({
        secretErr: true,
        secretErrMsg: 'Please input random numbers and characters.'
      })
      return;
    }

    this.setState({
      secretErr: false,
      secretErrMsg: ''
    });
  }

  checkGas = (v) => {
    // validate value should present
    if (v === '') {
      this.setState({
        gasErr: true,
        gasErrMsg: 'Please input a number.'
      });
      return;
    }

    // validate should greater than one
    if (parseFloat(v, 10) <= 1) {
      this.setState({
        gasErr: true,
        gasErrMsg: 'Please input a number large than one'
      })
      return;
    }

    this.setState({
      gasErr: false,
      gasErrMsg: ''
    })
  }

  submitDisabled = () => {
    const {ethBidErr, secretErr, gasErr} = this.state;
    return ethBidErr || secretErr || gasErr;
  }

  inputResult = () => ({
    email: this.state.email,
    ethBid: this.state.ethBid,
    secret: this.state.secret,
    gas: this.state.gas
  })

  handleImportDialogOpen = () => {
    this.setState({importDialogOpen: true});
  }

  handleImportDialogClose = () => {
    this.setState({
      importDialogOpen: false,
      revealJson: '',
      revealJsonErr: false,
      revealJsonErrMsg: '',
    });
  }

  handleParseImportJson = () => {
    try {
      const revealJsonObj = JSON.parse(this.state.revealJson);
      if (revealJsonObj.name !== this.props.searchResult.searchName) {
        this.setState({revealJsonErr: true, revealJsonErrMsg: "Reveal name not match."});
        return;
      }
      if (revealJsonObj.address !== this.props.address) {
        this.setState({revealJsonErr: true, revealJsonErrMsg: "Reveal address not match."});
        return;
      }
      this.setState({
        ethBid: revealJsonObj.value,
        secret: revealJsonObj.secret,
      });
      this.handleImportDialogClose();
    } catch (e) {
      this.setState({revealJsonErr: true, revealJsonErrMsg: "Not a valid JSON format."});
    }
  }

  render() {
    const domainName =
{this.props.searchResult.searchName}.eth
;
    const timeDuration = <TimeDuration {...this.props} />;
    const revealAuctionConfirmDialog =
      (this.state.open && this.props.address && this.props.privateKey) &&
        <RevealAuctionConfirmDialog
          {...this.props}
          inputResult={this.inputResult()}
          open={this.state.open}
          handleClose={this.handleClose}
        />;

    const importJsonButton =
      <ImportJsonButton onClick={this.handleImportDialogOpen}/>;

    const revealAuctionJsonDialog = this.state.importDialogOpen &&
      <RevealAuctionJsonDialog
        {...this.state}
        handleInputChange={this.handleInputChange}
        handleParseImportJson={this.handleParseImportJson}
        handleImportDialogClose={this.handleImportDialogClose}
      />

    const confirmSubmitButton =
      <ConfirmFormSubmit
        onClick={this.handleOpen}
        disabled={this.submitDisabled()}
      />;

    return (

        {domainName}
        {timeDuration}
        <FormFields
          {...this.props}
          {...this.state}
          handleInputChange={this.handleInputChange}
        />

          {importJsonButton}
          {confirmSubmitButton}

        {revealAuctionConfirmDialog}
        {revealAuctionJsonDialog}

    );
  }
};


text:
#pragma once
#include "libmd5.h"

//! \ingroup libMD5
//! \{

class MD5 {
public:
  /**
   * initialize digest state
   */
  MD5()
  {
    MD5Init(&m_state);
  }

  /**
   * compute digest over buf of length len.
   * multiple calls may extend the digest over more data.
   */
  void update(unsigned char *buf, unsigned len)
  {
    MD5Update(&m_state, buf, len);
  }

  /**
   * flush any outstanding MD5 data, write the digest into digest.
   */
  void finalize(unsigned char digest[16])
  {
    MD5Final(digest, &m_state);
  }

private:
  context_md5_t m_state;
};

/**
 * Produce an ascii(hex) representation of the 128bit digest.
 *
 * Returns: a statically allocated null-terminated string.  DO NOT FREE.
 */
inline const char*
digestToString(unsigned char digest[16])
{
  const char* hex = "0123456789abcdef";
  static char string[33];
  for (int i = 0; i < 16; i++)
  {
    string[i*2+0] = hex[digest[i] >> 4];
    string[i*2+1] = hex[digest[i] & 0xf];
  }
  return string;
}
//! \}


text:
<?php

namespace Application\Sonata\UserBundle\Entity;

use Sonata\UserBundle\Entity\BaseUser as BaseUser;

/**
 * This file has been generated by the Sonata EasyExtends bundle.
 *
 * @link https://sonata-project.org/bundles/easy-extends
 *
 * References :
 *   working with object : http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
 *
 * @author <yourname> <youremail>
 */
class User extends BaseUser
{
    /**
     * @var int $id
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        $this->enabled = true;
    }

    /**
     * Get id
     *
     * @return int $id
     */
    public function getId()
    {
        return $this->id;
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.orange.web.parser;

import com.orange.web.annotation.RequestMapping;

/**
 *
 * @author lining
 */
public final class RequestMappingParser extends AbstractAnnotationParser<RequestMapping>{

    @Override
    public Object parse(RequestMapping requestMapping, Object... objList) {
        if(objList[0] instanceof Class<?>){
            Class<?> objClass = (Class<?>)objList[0];
            return objClass;
        }
        return null;
    }
}


text:
BASEDIR = $(CURDIR)
CLASSES = $(BASEDIR)/classes/ $(BASEDIR)/../modules/
OUTPUTDIR = $(BASEDIR)/_build
TOOLSDIR = $(BASEDIR)/tools

.ONESHELL:

clean:
	rm -rf $(OUTPUTDIR)

doxygen:
	rm -rf $(OUTPUTDIR)/doxygen
	mkdir -p $(OUTPUTDIR)/doxygen
	doxygen Doxyfile

markdown:
	rm -rf $(OUTPUTDIR)/markdown
	mkdir -p $(OUTPUTDIR)/markdown
	pushd $(OUTPUTDIR)/markdown
	python2 $(TOOLSDIR)/makemd.py $(CLASSES)
	popd

rst:
	rm -rf $(OUTPUTDIR)/rst
	mkdir -p $(OUTPUTDIR)/rst
	pushd $(OUTPUTDIR)/rst
	python3 $(TOOLSDIR)/makerst.py $(CLASSES)
	popd


text:
package com.facebook.buck.apple.xcode;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasXPath;
import static org.junit.Assert.assertThat;

import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.timing.SettableFakeClock;
import com.facebook.buck.util.ProjectFilesystem;
import com.google.common.collect.ImmutableList;

import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class WorkspaceGeneratorTest {
  private SettableFakeClock clock;
  private ProjectFilesystem projectFilesystem;
  private WorkspaceGenerator generator;

  @Before
  public void setUp() {
    clock = new SettableFakeClock(0, 0);
    projectFilesystem = new FakeProjectFilesystem(clock);
    generator = new WorkspaceGenerator(projectFilesystem, "ws", Paths.get("."));
  }

  @Test
   public void testFlatWorkspaceContainsCorrectFileRefs() throws Exception {
    generator.addFilePath(Paths.get("./Project.xcodeproj"));
    Path workspacePath = generator.writeWorkspace();
    Path contentsPath = workspacePath.resolve("contents.xcworkspacedata");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document workspace = dBuilder.parse(projectFilesystem.newFileInputStream(contentsPath));
    assertThat(workspace, hasXPath("/Workspace[@version = \"1.0\"]"));
    assertThat(workspace, hasXPath("/Workspace/FileRef/@location",
            equalTo("container:Project.xcodeproj")));
  }

  @Test
  public void testNestedWorkspaceContainsCorrectFileRefs() throws Exception {
    generator.addFilePath(Paths.get("./grandparent/parent/Project.xcodeproj"));
    Path workspacePath = generator.writeWorkspace();
    Path contentsPath = workspacePath.resolve("contents.xcworkspacedata");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document workspace = dBuilder.parse(projectFilesystem.newFileInputStream(contentsPath));
    assertThat(workspace, hasXPath("/Workspace/Group[@name=\"grandparent\"]/FileRef/@location",
            equalTo("container:grandparent/parent/Project.xcodeproj")));
  }

  @Test
  public void testWorkspaceContainsNodeInAlphabeticalOrder() throws Exception {
    generator.addFilePath(Paths.get("./2/parent/C.xcodeproj"));
    generator.addFilePath(Paths.get("./2/parent/B.xcodeproj"));
    generator.addFilePath(Paths.get("./2/parent/D.xcodeproj"));
    generator.addFilePath(Paths.get("./1/parent/E.xcodeproj"));
    generator.addFilePath(Paths.get("./3/parent/A.xcodeproj"));

    Path workspacePath = generator.writeWorkspace();
    Path contentsPath = workspacePath.resolve("contents.xcworkspacedata");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document workspace = dBuilder.parse(projectFilesystem.newFileInputStream(contentsPath));

    Node workspaceNode = workspace.getChildNodes().item(0);

    ImmutableList.Builder<String> groupsBuilder = ImmutableList.builder();
    for (int i = 0; i < workspaceNode.getChildNodes().getLength(); ++i) {
      groupsBuilder.add(
          workspaceNode
              .getChildNodes()
              .item(i)
              .getAttributes()
              .getNamedItem("name")
              .getNodeValue());
    }
    assertThat(groupsBuilder.build(), equalTo(ImmutableList.of("1", "2", "3")));

    Node secondGroup = workspaceNode.getChildNodes().item(1);

    assertThat(secondGroup.getAttributes().getNamedItem("name").getNodeValue(), equalTo("2"));

    ImmutableList.Builder<String> projectsBuilder = ImmutableList.builder();
    for (int i = 0; i < secondGroup.getChildNodes().getLength(); ++i) {
      projectsBuilder.add(
          secondGroup
              .getChildNodes()
              .item(i)
              .getAttributes()
              .getNamedItem("location")
              .getNodeValue());
    }
    assertThat(
        projectsBuilder.build(),
        equalTo(
            ImmutableList.of(
                "container:2/parent/B.xcodeproj",
                "container:2/parent/C.xcodeproj",
                "container:2/parent/D.xcodeproj")));
  }

  @Test
  public void workspaceIsRewrittenIfContentsHaveChanged() throws IOException {
    {
      generator.addFilePath(Paths.get("./Project.xcodeproj"));
      clock.setCurrentTimeMillis(49152);
      Path workspacePath = generator.writeWorkspace();
      assertThat(
          projectFilesystem.getLastModifiedTime(workspacePath.resolve("contents.xcworkspacedata")),
          equalTo(49152L));
    }

    {
      WorkspaceGenerator generator2 = new WorkspaceGenerator(
          projectFilesystem,
          "ws",
          Paths.get("."));
      generator2.addFilePath(Paths.get("./Project2.xcodeproj"));
      clock.setCurrentTimeMillis(64738);
      Path workspacePath2 = generator2.writeWorkspace();
      assertThat(
          projectFilesystem.getLastModifiedTime(workspacePath2.resolve("contents.xcworkspacedata")),
          equalTo(64738L));
    }
  }

  @Test
  public void workspaceIsNotRewrittenIfContentsHaveNotChanged() throws IOException {
    {
      generator.addFilePath(Paths.get("./Project.xcodeproj"));
      clock.setCurrentTimeMillis(49152);
      Path workspacePath = generator.writeWorkspace();
      assertThat(
          projectFilesystem.getLastModifiedTime(workspacePath.resolve("contents.xcworkspacedata")),
          equalTo(49152L));
    }

    {
      WorkspaceGenerator generator2 = new WorkspaceGenerator(
          projectFilesystem,
          "ws",
          Paths.get("."));
      generator2.addFilePath(Paths.get("./Project.xcodeproj"));
      clock.setCurrentTimeMillis(64738);
      Path workspacePath2 = generator2.writeWorkspace();
      assertThat(
          projectFilesystem.getLastModifiedTime(workspacePath2.resolve("contents.xcworkspacedata")),
          equalTo(49152L));
    }
  }
}


text:
REBAR		?= ./rebar

all: compile
	make -C deps/basho_bench all
	cp deps/basho_bench/basho_bench .

deps:
	$(REBAR) get-deps

compile: deps
	$(REBAR) compile

clean:
	$(REBAR) clean
	rm -f ./basho_bench

results:
	./deps/basho_bench/priv/summary.r -i tests/current

.PHONY: all deps compile clean results


text:
Release Process
====================

* * *

###update (commit) version in sources

	vertcoin-qt.pro
	contrib/verifysfbinaries/verify.sh
	doc/README*
	share/setup.nsi
	src/clientversion.h (change CLIENT_VERSION_IS_RELEASE to true)

###tag version in git

	git tag -s v0.8.7

###write release notes. git shortlog helps a lot, for example:

	git shortlog --no-merges v0.7.2..v0.8.0

* * *

##perform gitian builds

 From a directory containing the vertcoin source, gitian-builder and gitian.sigs

	export SIGNER=(your gitian key, ie bluematt, sipa, etc)
	export VERSION=0.8.7
	cd ./gitian-builder

 Fetch and build inputs: (first time, or when dependency versions change)

	mkdir -p inputs; cd inputs/
	wget 'http://miniupnp.free.fr/files/download.php?file=miniupnpc-1.9.20140401.tar.gz' -O miniupnpc-1.9.20140401.tar.gz'
	wget 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz'
	wget 'http://download.oracle.com/berkeley-db/db-4.8.30.NC.tar.gz'
	wget 'http://zlib.net/zlib-1.2.8.tar.gz'
	wget 'ftp://ftp.simplesystems.org/pub/libpng/png/src/history/libpng16/libpng-1.6.8.tar.gz'
	wget 'http://fukuchi.org/works/qrencode/qrencode-3.4.3.tar.bz2'
	wget 'http://downloads.sourceforge.net/project/boost/boost/1.55.0/boost_1_55_0.tar.bz2'
	wget 'http://download.qt-project.org/official_releases/qt/4.8/4.8.5/qt-everywhere-opensource-src-4.8.5.tar.gz'
	cd ..
	./bin/gbuild ../vertcoin/contrib/gitian-descriptors/boost-win32.yml
	mv build/out/boost-win32-1.50.0-gitian2.zip inputs/
	./bin/gbuild ../vertcoin/contrib/gitian-descriptors/qt-win32.yml
	mv build/out/qt-win32-4.8.3-gitian-r1.zip inputs/
	./bin/gbuild ../vertcoin/contrib/gitian-descriptors/deps-win32.yml
	mv build/out/vertcoin-deps-0.0.5.zip inputs/

 Build vertcoind and vertcoin-qt on Linux32, Linux64, and Win32:

	./bin/gbuild --commit vertcoin=v${VERSION} ../vertcoin/contrib/gitian-descriptors/gitian.yml
	./bin/gsign --signer $SIGNER --release ${VERSION} --destination ../gitian.sigs/ ../vertcoin/contrib/gitian-descriptors/gitian.yml
	pushd build/out
	zip -r vertcoin-${VERSION}-linux-gitian.zip *
	mv vertcoin-${VERSION}-linux-gitian.zip ../../
	popd
	./bin/gbuild --commit vertcoin=v${VERSION} ../vertcoin/contrib/gitian-descriptors/gitian-win32.yml
	./bin/gsign --signer $SIGNER --release ${VERSION}-win32 --destination ../gitian.sigs/ ../vertcoin/contrib/gitian-descriptors/gitian-win32.yml
	pushd build/out
	zip -r vertcoin-${VERSION}-win32-gitian.zip *
	mv vertcoin-${VERSION}-win32-gitian.zip ../../
	popd

  Build output expected:

  1. linux 32-bit and 64-bit binaries + source (vertcoin-${VERSION}-linux-gitian.zip)
  2. windows 32-bit binary, installer + source (vertcoin-${VERSION}-win32-gitian.zip)
  3. Gitian signatures (in gitian.sigs/${VERSION}[-win32]/(your gitian key)/

repackage gitian builds for release as stand-alone zip/tar/installer exe

**Linux .tar.gz:**

	unzip vertcoin-${VERSION}-linux-gitian.zip -d vertcoin-${VERSION}-linux
	tar czvf vertcoin-${VERSION}-linux.tar.gz vertcoin-${VERSION}-linux
	rm -rf vertcoin-${VERSION}-linux

**Windows .zip and setup.exe:**

	unzip vertcoin-${VERSION}-win32-gitian.zip -d vertcoin-${VERSION}-win32
	mv vertcoin-${VERSION}-win32/vertcoin-*-setup.exe .
	zip -r vertcoin-${VERSION}-win32.zip bitcoin-${VERSION}-win32
	rm -rf vertcoin-${VERSION}-win32

**Perform Mac build:**

  OSX binaries are created on a dedicated 32-bit, OSX 10.6.8 machine.
  Vertcoin 0.8.x is built with MacPorts.  0.9.x will be Homebrew only.

	qmake RELEASE=1 USE_UPNP=1 USE_QRCODE=1 vertcoin-qt.pro
	make
	export QTDIR=/opt/local/share/qt4  # needed to find translations/qt_*.qm files
	T=$(contrib/qt_translations.py $QTDIR/translations src/qt/locale)
	python2.7 share/qt/clean_mac_info_plist.py
	python2.7 contrib/macdeploy/macdeployqtplus Vertcoin-Qt.app -add-qt-tr $T -dmg -fancy contrib/macdeploy/fancy.plist

 Build output expected: Vertcoin-Qt.dmg

###Next steps:

* Code-sign Windows -setup.exe (in a Windows virtual machine) and
  OSX Bitcoin-Qt.app (Note: only Gavin has the code-signing keys currently)

* upload builds to SourceForge

* create SHA256SUMS for builds, and PGP-sign it

* update vertcoin.org version
  make sure all OS download links go to the right versions

* update forum version

* update wiki download links

Commit your signature to gitian.sigs:

	pushd gitian.sigs
	git add ${VERSION}/${SIGNER}
	git add ${VERSION}-win32/${SIGNER}
	git commit -a
	git push  # Assuming you can push to the gitian.sigs tree
	popd


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

 !-->

<serviceGroup>

    <service name="TaxonomyServices" scope="transportsession">
        <transports>
            <transport>https</transport>
        </transports>
        <parameter name="ServiceClass" locked="true">org.wso2.carbon.governance.taxonomy.services.TaxonomyServicesImpl
        </parameter>
    </service>

    <parameter name="adminService" locked="true">true</parameter>
    <parameter name="hiddenService" locked="true">true</parameter>
    <parameter name="AuthorizationAction">/permission/admin/configure/governance/taxonomy</parameter>
</serviceGroup>


text:
using System.Collections.Generic;
using AgentMulder.ReSharper.Domain.Patterns;
using AgentMulder.ReSharper.Domain.Registrations;
using JetBrains.ReSharper.Feature.Services.CSharp.StructuralSearch;
using JetBrains.ReSharper.Feature.Services.CSharp.StructuralSearch.Placeholders;
using JetBrains.ReSharper.Feature.Services.StructuralSearch;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;

namespace AgentMulder.Containers.CastleWindsor.Patterns.FromTypes.BasedOn
{
    internal sealed class BasedOnNonGeneric : BasedOnPatternBase
    {
        private readonly IBasedOnRegistrationCreator registrationCreator;

        private static readonly IStructuralSearchPattern pattern =
            new CSharpStructuralSearchPattern("$fromDescriptor$.BasedOn($argument$)",
                new ExpressionPlaceholder("fromDescriptor", "Castle.MicroKernel.Registration.FromDescriptor", false),
                new ArgumentPlaceholder("argument", 1, 1));

        public BasedOnNonGeneric(IBasedOnRegistrationCreator registrationCreator)
            : base(pattern)
        {
            this.registrationCreator = registrationCreator;
        }

        public override IEnumerable<IComponentRegistration> GetComponentRegistrations(ITreeNode registrationRootElement)
        {
            return GetBasedOnRegistrations(registrationRootElement);
        }

        public override IEnumerable<FilteredRegistrationBase> GetBasedOnRegistrations(ITreeNode registrationRootElement)
        {
            IStructuralMatchResult match = Match(registrationRootElement);

            if (match.Matched)
            {
                var argument = match.GetMatchedElement("argument") as ICSharpArgument;
                if (argument == null)
                {
                    yield break;
                }

                var typeofExpression = argument.Value as ITypeofExpression;
                if (typeofExpression != null)
                {
                    var declaredType = typeofExpression.ArgumentType as IDeclaredType;
                    if (declaredType != null)
                    {
                        ITypeElement typeElement = declaredType.GetTypeElement();
                        if (typeElement != null)
                        {
                            yield return registrationCreator.Create(registrationRootElement, typeElement);
                        }
                    }
                }
            }
        }
    }
}


text:
package org.openksavi.sponge.kotlin.test.nonscript;

import org.junit.jupiter.api.Test;

import org.openksavi.sponge.test.script.TriggersTest;
import org.openksavi.sponge.test.script.template.TriggersTestTemplate;

public class KotlinNonScriptTriggersTest extends KotlinNonScriptTest implements TriggersTest {

    @Override
    @Test
    public void testTriggers() {
        TriggersTestTemplate.testTriggers(getType());
    }

    @Override
    @Test
    public void testTriggersEventPattern() {
        TriggersTestTemplate.testTriggersEventPattern(getType());
    }

    @Override
    @Test
    public void testTriggersEventPatternIncorrect() {
        TriggersTestTemplate.testTriggersEventPatternIncorrect(getType());
    }

    @Override
    @Test
    public void testHelloWorld() {
        TriggersTestTemplate.testHelloWorld(getType());
    }

    @Override
    @Test
    public void testTriggersBuilder() {
        TriggersTestTemplate.testTriggersBuilder(getType());
    }
}


text:
#include "bsp_common.h"
#include "stm32_bluenrg_ble.h"
#include "bluenrg_sdk_api.h"
#include "bluenrg_sdk_host_api.h"
#include "dispatch.h"
#include "stm32f401_lp_mode.h"

#define BUFFER_SIZE         ((uint32_t)0x400)
#define WRITE_READ_ADDR     ((uint32_t)0x8000)
#define MANUFACTURER_CODE   ((uint16_t)0x0001)
#define DEVICE_CODE1        ((uint16_t)0x227E)
#define DEVICE_CODE2        ((uint16_t)0x2221)
#define DEVICE_CODE3        ((uint16_t)0x2201)  /*00h for PC28F128M29EWLA.*/

#define NOR_BANK_ADDR       ((uint32_t)0x60000000)
#define NOR_TIMEOUT_VALUE   ((uint32_t)0xFFFF)

NOR_HandleTypeDef hnor;
FMC_NORSRAM_TimingTypeDef NOR_Timing;
/* NOR IDs structure */
static NOR_IDTypeDef NOR_Id;

/* Read/Write Buffers */
uint16_t aTxBuffer[BUFFER_SIZE];
uint16_t aRxBuffer[BUFFER_SIZE];

/* Status variables */
__IO uint32_t uwWriteReadStatus = 0;

/* Counter index */
uint32_t uwIndex = 0;
typedef enum {FAILED = 0, PASSED = !FAILED} TestStatus;

static void Error_Handler(void);
static void Fill_Buffer(uint16_t *pBuffer, uint32_t uwBufferLength, uint16_t uwOffset);
static TestStatus Buffercmp(uint16_t *pBuffer1, uint16_t *pBuffer2, uint16_t BufferLength);

static void Error_Handler(void)
{
  while (1)
  {
  }
}

int FMC_Test(void)
{
  uint16_t *pdata = NULL;
  uint32_t index  = 0;
  uint32_t startaddress = 0;

  /*##-1- Configure the NOR device ##########################################*/
  /* NOR device configuration */

  hnor.Instance  = FMC_NORSRAM_DEVICE;
  hnor.Extended  = FMC_NORSRAM_EXTENDED_DEVICE;

  /* NOR device configuration */
  NOR_Timing.AddressSetupTime       = 8;
  NOR_Timing.AddressHoldTime        = 3;
  NOR_Timing.DataSetupTime          = 9;
  NOR_Timing.BusTurnAroundDuration  = 0;
  NOR_Timing.CLKDivision            = 2;
  NOR_Timing.DataLatency            = 1;
  NOR_Timing.AccessMode             = FMC_ACCESS_MODE_B;

  hnor.Init.NSBank                 = FMC_NORSRAM_BANK1;
  hnor.Init.DataAddressMux         = FMC_DATA_ADDRESS_MUX_ENABLE;
  hnor.Init.MemoryType             = FMC_MEMORY_TYPE_NOR;
  hnor.Init.MemoryDataWidth        = FMC_NORSRAM_MEM_BUS_WIDTH_16;
  hnor.Init.BurstAccessMode        = FMC_BURST_ACCESS_MODE_DISABLE;
  hnor.Init.WaitSignalPolarity     = FMC_WAIT_SIGNAL_POLARITY_LOW;
  hnor.Init.WrapMode               = FMC_WRAP_MODE_DISABLE;
  hnor.Init.WaitSignalActive       = FMC_WAIT_TIMING_BEFORE_WS;
  hnor.Init.WriteOperation         = FMC_WRITE_OPERATION_ENABLE;
  hnor.Init.WaitSignal             = FMC_WAIT_SIGNAL_DISABLE;
  hnor.Init.ExtendedMode           = FMC_EXTENDED_MODE_DISABLE;
  hnor.Init.AsynchronousWait       = FMC_ASYNCHRONOUS_WAIT_DISABLE;
  hnor.Init.WriteBurst             = FMC_WRITE_BURST_DISABLE;

  /* Initialize the NOR controller */
  if(HAL_NOR_Init(&hnor, &NOR_Timing, &NOR_Timing) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }

  /* Read NOR memory ID */
  if(HAL_NOR_Read_ID(&hnor, &NOR_Id) != HAL_OK)
  {
    /* NOR read ID Error */
    Error_Handler();
  }

   /* Test the NOR ID correctness */
  if((NOR_Id.Manufacturer_Code != (uint16_t)MANUFACTURER_CODE)/* ||
     (NOR_Id.Device_Code1 != (uint16_t)DEVICE_CODE1) ||
     (NOR_Id.Device_Code2 != (uint16_t)DEVICE_CODE2) ||
     (NOR_Id.Device_Code3 != (uint16_t)DEVICE_CODE3)*/)
  {
    /* NOR ID not correct */
    Error_Handler();
  }

	while (1)
		;
  /* Return to read mode */
  HAL_NOR_ReturnToReadMode(&hnor);

  /* Erase the NOR memory block to write on */
  HAL_NOR_Erase_Block(&hnor, WRITE_READ_ADDR, NOR_BANK_ADDR);

  /* Return the NOR memory status */
  if(HAL_NOR_GetStatus(&hnor, NOR_BANK_ADDR, NOR_TIMEOUT_VALUE) != HAL_NOR_STATUS_SUCCESS)
  {
    /* Erase Error */
    Error_Handler();
  }

  /*##-2- NOR memory read/write access ######################################*/
  /* Fill the buffer to write */
  Fill_Buffer(aTxBuffer, BUFFER_SIZE, 0xC20F);

  /* Write data to the NOR memory */
  pdata = aTxBuffer;
  index = BUFFER_SIZE;
  startaddress = NOR_BANK_ADDR + WRITE_READ_ADDR;
  while(index > 0)
  {
    /* Write data to NOR */
    HAL_NOR_Program(&hnor, (uint32_t *)startaddress, pdata);

    /* Read NOR device status */
    if(HAL_NOR_GetStatus(&hnor, NOR_BANK_ADDR, NOR_TIMEOUT_VALUE) != HAL_NOR_STATUS_SUCCESS)
    {
      Error_Handler();
    }

    /* Update the counters */
    index--;
    startaddress += 2;
    pdata++;
  }

  /* Read back data from the NOR memory */
  if(HAL_NOR_ReadBuffer(&hnor, NOR_BANK_ADDR + WRITE_READ_ADDR, aRxBuffer, BUFFER_SIZE) != HAL_OK)
  {
      Error_Handler();
  }

  /*##-3- Checking data integrity ############################################*/
  uwWriteReadStatus = Buffercmp(aTxBuffer, aRxBuffer, BUFFER_SIZE);

  if(uwWriteReadStatus != PASSED)
  {
  }
  else
  {
  }

  /* Infinite loop */
  while (1)
  {
  }
}

/**
  * @brief  Fills buffer with user predefined data.
  * @param  pBuffer: pointer on the buffer to fill
  * @param  uwBufferLength: size of the buffer to fill
  * @param  uwOffset: first value to fill on the buffer
  * @retval None
  */
static void Fill_Buffer(uint16_t *pBuffer, uint32_t uwBufferLength, uint16_t uwOffset)
{
  uint16_t tmpIndex = 0;

  /* Put in global buffer different values */
  for (tmpIndex = 0; tmpIndex < uwBufferLength; tmpIndex++)
  {
    pBuffer[tmpIndex] = tmpIndex + uwOffset;
  }
}

/**
  * @brief  Compares two buffers.
  * @param  pBuffer1, pBuffer2: buffers to be compared.
  * @param  BufferLength: buffer's length
  * @retval PASSED: pBuffer identical to pBuffer1
  *         FAILED: pBuffer differs from pBuffer1
  */
static TestStatus Buffercmp(uint16_t *pBuffer1, uint16_t *pBuffer2, uint16_t BufferLength)
{
  while (BufferLength--)
  {
    if (*pBuffer1 != *pBuffer2)
    {
      return FAILED;
    }

    pBuffer1++;
    pBuffer2++;
  }

  return PASSED;
}

#ifdef  USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/**
  * @brief NOR MSP Initialization
  *        This function configures the hardware resources used in this example:
  *           - Peripheral's clock enable
  *           - Peripheral's GPIO Configuration
  * @param hsram: NOR handle pointer
  * @retval None
  */
void HAL_NOR_MspInit(NOR_HandleTypeDef *hnor)
{
  GPIO_InitTypeDef GPIO_Init_Structure;

  /* Enable FMC clock */
  __HAL_RCC_FMC_CLK_ENABLE();

  /* Enable GPIOs clock */
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOE_CLK_ENABLE();
//  __HAL_RCC_GPIOF_CLK_ENABLE();
//  __HAL_RCC_GPIOG_CLK_ENABLE();

  /* Common GPIO configuration */
  GPIO_Init_Structure.Mode      = GPIO_MODE_AF_PP;
  GPIO_Init_Structure.Pull      = GPIO_PULLUP;
  GPIO_Init_Structure.Speed     = GPIO_SPEED_HIGH;
  GPIO_Init_Structure.Alternate = GPIO_AF12_FMC;

  /*## Data Bus #######*/
  /* GPIOD configuration */
  GPIO_Init_Structure.Pin   = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_8 | GPIO_PIN_9 | \
                              GPIO_PIN_10 | GPIO_PIN_14 | GPIO_PIN_15;
  HAL_GPIO_Init(GPIOD, &GPIO_Init_Structure);

  /* GPIOE configuration */
  GPIO_Init_Structure.Pin   = GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | \
                              GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13 | \
                              GPIO_PIN_14 | GPIO_PIN_15;
  HAL_GPIO_Init(GPIOE, &GPIO_Init_Structure);

  /*## Address Bus #######*/
//  /* GPIOF configuration */
//  GPIO_Init_Structure.Pin   = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | \
//                              GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_12 | GPIO_PIN_13 | \
//                              GPIO_PIN_14 | GPIO_PIN_15;
//  HAL_GPIO_Init(GPIOF, &GPIO_Init_Structure);
//
//  /* GPIOG configuration */
//  GPIO_Init_Structure.Pin   = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | \
//                              GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5;
//  HAL_GPIO_Init(GPIOG, &GPIO_Init_Structure);

  /* GPIOD configuration */
  GPIO_Init_Structure.Pin   = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13;
  HAL_GPIO_Init(GPIOD, &GPIO_Init_Structure);

  /* GPIOE configuration */
  GPIO_Init_Structure.Pin   = GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6;
  HAL_GPIO_Init(GPIOE, &GPIO_Init_Structure);

  /*## NOE and NWE configuration #######*/
  GPIO_Init_Structure.Pin = GPIO_PIN_4 |GPIO_PIN_5;
  HAL_GPIO_Init(GPIOD, &GPIO_Init_Structure);

  /*## WAIT and CLK????????? configuration #######*/
  GPIO_Init_Structure.Pin = GPIO_PIN_6 |GPIO_PIN_3;
  HAL_GPIO_Init(GPIOD, &GPIO_Init_Structure);

  /*## NL pin configuration #######*/
  GPIO_Init_Structure.Pin = GPIO_PIN_7;
  HAL_GPIO_Init(GPIOB, &GPIO_Init_Structure);

  /*## Enable Bank pin configuration #######*/
  GPIO_Init_Structure.Pin = GPIO_PIN_7;
  HAL_GPIO_Init(GPIOD, &GPIO_Init_Structure);

  /*## NBL0, NBL1 configuration #######*/
  GPIO_Init_Structure.Pin = GPIO_PIN_0 | GPIO_PIN_1;
  HAL_GPIO_Init(GPIOE, &GPIO_Init_Structure);
}

/**
  * @brief NOR MSP De-Initialization
  *        This function frees the hardware resources used in this example:
  *          - Disable the Peripheral's clock
  *          - Revert GPIO configuration to their default state
  * @param hnor: NOR handle pointer
  * @retval None
  */
void HAL_NOR_MspDeInit(NOR_HandleTypeDef *hnor)
{
//  /*## Disable peripherals and GPIO Clocks ###################################*/
//  /* Configure FMC as alternate function  */
//  HAL_GPIO_DeInit(GPIOD, GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5     | \
//                  GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 | \
//                  GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15);

//  HAL_GPIO_DeInit(GPIOE, GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_7     | \
//                  GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 | \
//                  GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15);

//  HAL_GPIO_DeInit(GPIOF, GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | \
//                  GPIO_PIN_5 | GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15);

//  HAL_GPIO_DeInit(GPIOG, GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | \
//                  GPIO_PIN_5 | GPIO_PIN_9);
}


text:
.clockpicker-popover {
	display: none;
    max-width: 228px;
}
.clockpicker-popover.clockpicker-popover-open {
	display: block;
}
.clockpicker-popover-inline {
	display: block;
	position: static;
}
.clockpicker .input-group-addon {
	cursor: pointer;
}
.clockpicker-moving {
	cursor: move;
}
.clockpicker-align-left.popover > .arrow {
	left: 25px;
}
.clockpicker-align-top.popover > .arrow {
	top: 17px;
}
.clockpicker-align-right.popover > .arrow {
	left: auto;
	right: 25px;
}
.clockpicker-align-bottom.popover > .arrow {
	top: auto;
	bottom: 6px;
}
.clockpicker-popover .popover-title {
	background-color: #fff;
	color: #999;
	font-size: 24px;
	font-weight: bold;
	line-height: 30px;
	text-align: center;
}
.clockpicker-popover .popover-title span.cursor-pointer {
	cursor: pointer;
}
.clockpicker-popover .popover-title.blank span,
.clockpicker-popover .popover-title span.clockpicker-span-blank {
	display: none;
}
.clockpicker-popover .popover-title.blank span.clockpicker-span-blank {
	display: inline;
}
.clockpicker-popover .popover-content {
	background-color: #f8f8f8;
	padding: 12px;
}
.popover-content:last-child {
	border-bottom-left-radius: 5px;
	border-bottom-right-radius: 5px;
}
.clockpicker-plate {
	background-color: #fff;
	border: 1px solid #ccc;
	border-radius: 50%;
	width: 200px;
	height: 200px;
	overflow: visible;
	position: relative;
	/* Disable text selection highlighting. Thanks to Hermanya */
	-webkit-touch-callout: none;
	-webkit-user-select: none;
	-khtml-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
}
.clockpicker-canvas,
.clockpicker-dial,
.clockpicker-dial-overlay {
	width: 200px;
	height: 200px;
	position: absolute;
	left: -1px;
	top: -1px;
}
.clockpicker-minutes {
	visibility: hidden;
}
.clockpicker-tick {
	border-radius: 50%;
	color: #666;
	line-height: 26px;
	text-align: center;
	width: 26px;
	height: 26px;
	position: absolute;
	cursor: pointer;
}
.clockpicker-tick.active,
.clockpicker-tick:hover {
	background-color: rgb(192, 229, 247);
	background-color: rgba(0, 149, 221, .25);
}
.clockpicker-button {
	background-image: none;
	background-color: #fff;
	border-width: 1px 0 0;
	border-top-left-radius: 0;
	border-top-right-radius: 0;
	margin: 0;
	padding: 10px 0;
}
.clockpicker-button+.clockpicker-button {
	margin: 0;
}
.clockpicker-button:hover {
	background-image: none;
	background-color: #ebebeb;
}
.clockpicker-button:focus {
	outline: none!important;
}
.clockpicker-dial {
	-webkit-transition: -webkit-transform 350ms, opacity 350ms;
	-moz-transition: -moz-transform 350ms, opacity 350ms;
	-ms-transition: -ms-transform 350ms, opacity 350ms;
	-o-transition: -o-transform 350ms, opacity 350ms;
	transition: transform 350ms, opacity 350ms;
}
.clockpicker-dial-out {
	opacity: 0;
}
.clockpicker-dial-overlay {
	-webkit-transition: opacity 350ms, z-index 350ms;
	-moz-transition: opacity 350ms, z-index 350ms;
	-ms-transition: opacity 350ms, z-index 350ms;
	-o-transition: opacity 350ms, z-index 350ms;
	transition: opacity 350ms, z-index 350ms;
	background-color: #f8f8f8;
	z-index: -1;
	opacity: 0;
}
.popover-content.clockpicker-am-pm-active .clockpicker-dial-overlay {
	opacity: 0.8;
	z-index: 1;
}
.clockpicker-hours.clockpicker-dial-out {
	-webkit-transform: scale(1.2, 1.2);
	-moz-transform: scale(1.2, 1.2);
	-ms-transform: scale(1.2, 1.2);
	-o-transform: scale(1.2, 1.2);
	transform: scale(1.2, 1.2);
}
.clockpicker-minutes.clockpicker-dial-out {
	-webkit-transform: scale(.8, .8);
	-moz-transform: scale(.8, .8);
	-ms-transform: scale(.8, .8);
	-o-transform: scale(.8, .8);
	transform: scale(.8, .8);
}
.clockpicker-canvas {
	-webkit-transition: opacity 175ms;
	-moz-transition: opacity 175ms;
	-ms-transition: opacity 175ms;
	-o-transition: opacity 175ms;
	transition: opacity 175ms;
}
.clockpicker-canvas-out {
	opacity: 0.25;
}
.clockpicker-canvas-bearing,
.clockpicker-canvas-fg {
	stroke: none;
	fill: rgb(0, 149, 221);
}
.clockpicker-canvas-bg {
	stroke: none;
	fill: rgb(192, 229, 247);
}
.clockpicker-canvas-bg-trans {
	fill: rgba(0, 149, 221, .25);
}
.clockpicker-canvas line {
	stroke: rgb(0, 149, 221);
	stroke-width: 1;
	stroke-linecap: round;
	/*shape-rendering: crispEdges;*/
}
.clockpicker-am-pm-block {
	height: 30px;
	position: relative;
	z-index: 1;
}
.clockpicker-am-pm-block-hidden {
	display: none;
}
.clockpicker-button.am-button,
.clockpicker-button.pm-button {
	margin: 1px;
	padding: 5px;
	border: 1px solid rgba(0, 0, 0, .2);
	border-radius: 4px;
	-webkit-transition: margin 350ms;
	-moz-transition: margin 350ms;
	-ms-transition: margin 350ms;
	-o-transition: margin 350ms;
	transition: margin 350ms;
}
.clockpicker-button.am-button {
	float: left;
}
.clockpicker-button.pm-button {
	float: right;
}
.popover-content.clockpicker-am-pm-active .clockpicker-button.am-button {
	margin-top: -115px;
	margin-left: 50px;
}
.popover-content.clockpicker-am-pm-active .clockpicker-button.pm-button {
	margin-top: -115px;
	margin-right: 50px;
}


text:
'use strict';

var mongoose = require('mongoose'),
    Modules = mongoose.model('ModulesTest');

exports.save = function (req, res) {
    var modules = new Modules(req.body);
    var owner = req.user.username;
    if (!modules.owner) {
        modules.owner = owner;
    }
    if (!modules.version) {
        modules.version = 1;
    } else {
        modules.version = modules.version + 1;
    }
    modules.save(function (err) {
        if (err) {
            switch (err.code) {
                default:
                    res.status(400).send('Please fill all the required fields');
            }
            return res.status(400);
        } else {
            res.status(200);
            return res.json({
                type: 'success',
                msg: '添加成功'
            });
        }
    });
};

exports.fetch = function(req,res){

    var projectId = req.body.projectId;
    var organizationName = req.body.organizationName;

    if (!organizationName) {
        organizationName = null;
    }
    var owner = req.user.username;

    Modules.find({projectId:projectId, author:owner}, function(err, modules){
        if (err) {
            switch (err.code) {
                default:
                    res.status(400).send('Please fill all the required fields');
            }
            return res.status(400);
        }else{
            res.status(200);
            return res.send(modules);
        }
    });
};

exports.fetchOfVersion = function(req,res){
    var projectName = req.body.projectName;
    var organizationName = req.body.organizationName;
    if(!organizationName){
        organizationName = null;
    }
    var owner = req.user.username;
    var version = req.body.version;

    Modules.findOne({projectName:projectName,organizationName:organizationName,owner:owner,version:version},function(err,module){
        if (err) {
            switch (err.code) {
                default:
                    res.status(400).send('Please fill all the required fields');
            }
            return res.status(400);
        }else{
            res.status(200);
            return res.send(module);
        }
    });
};


text:
package es.polgomez.data.repository.datasources.api.entities;

import java.io.Serializable;

/**
 * Point of Interest api entity from list
 */
public class ApiPointOfInterestListItem implements Serializable {

    private String id;
    private String title;
    private String geocoordinates;

    public ApiPointOfInterestListItem() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getGeocoordinates() {
        return geocoordinates;
    }

    public void setGeocoordinates(String geocoordinates) {
        this.geocoordinates = geocoordinates;
    }

    @Override
    public String toString() {
        return "ApiPointOfInterestListItem{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                ", geocoordinates='" + geocoordinates + '\'' +
                '}';
    }
}


text:
class PostsController < ApplicationController

	before_action :authenticate_user!, except:[:show, :list]

  def list
    @post_all = Post.order("created_at DESC")
    @post = @post_all.limit(10).offset(10*params[:id].to_i)
    @count = @post_all.count
  end

  def show
  	@post = Post.find(params[:id])
    @post.hits+=1
    @post.save
  end

  def new

    if current_user.admin==false
      redirect_to root_path
    end

  	@post = Post.new

  end

  def create

    if current_user.admin==false
      redirect_to root_path
    end

  	post = Post.new
  	post.user_id = current_user.id
  	post.title = params[:post][:title]
  	post.context = params[:post][:context]
  	post.save

  	redirect_to post_path(post.id)

  end

  def edit

    if current_user.admin==false
      redirect_to root_path
    end

  	@post = Post.find(params[:id])

  end

  def update

    if current_user.admin==false
      redirect_to root_path
    end

  	post = Post.find(params[:id])
  	post.user_id = current_user.id
  	post.title = params[:post][:title]
  	post.context = params[:post][:context]
  	post.save

  	redirect_to post_path(post.id)

  end

  def destroy

    if current_user.admin==false
      redirect_to root_path
    end

  	post = Post.find(params[:id])
  	post.destroy

  	redirect_to root_path

  end

end


text:
/*global define*/
/*global describe, it, expect*/
/*global jasmine*/
/*global beforeEach, afterEach*/
/*jslint white: true*/
define([
    'widgets/appWidgets2/input/dynamicDropdownInput',
    'base/js/namespace',
    'kbaseNarrative',
    'testUtil'
], function(
    DynamicDropdownInput,
    Jupyter,
    Narrative,
    TestUtil
) {
    'use strict';

    describe('Test dynamic dropdown input widget', function() {
        var testConfig = {
            parameterSpec: {
                data: {
                    defaultValue: '',
                    nullValue: '',
                    constraints: {
                        required: false
                    }
                }
            },
            channelName: 'foo'
        };

        beforeEach(function() {
            if (TestUtil.getAuthToken()) {
                document.cookie = 'kbase_session=' + TestUtil.getAuthToken();
                Jupyter.narrative = new Narrative();
                Jupyter.narrative.authToken = TestUtil.getAuthToken();
                Jupyter.narrative.userId = TestUtil.getUserId();
            }
        });

        it('should be real!', function() {
            expect(DynamicDropdownInput).not.toBeNull();
        });

        it('should instantiate with a test config', function() {
            TestUtil.pendingIfNoToken();
            var widget = DynamicDropdownInput.make(testConfig);
            expect(widget).toEqual(jasmine.any(Object));
        });

        it('should start up and stop correctly', function(done) {
            TestUtil.pendingIfNoToken();
            var widget = DynamicDropdownInput.make(testConfig);
            widget.start({node: document.createElement('div')})
                .then(function() {
                    return widget.stop();
                })
                .then(function() {
                    // no-op
                })
                .catch(function(error) {
                    console.error(JSON.stringify(error, null, 4));
                    console.error(error.stack);
                    fail();
                })
                .finally(function() {
                    done();
                });
        });
    });
});


text:
package engi

import "math"

// A rather basic camera
type Camera struct {
	DeadzoneSize Point
	pos, to      Point
	tracking     *Entity // The entity that is currently being followed
}

func (cam *Camera) FollowEntity(entity *Entity) {
	cam.tracking = entity
	var space *SpaceComponent
	if !cam.tracking.GetComponent(&space) {
		return
	}

	cam.to = space.Position
	cam.centerCam(Width(), Height(), 1, space)
}

func (cam *Camera) Update(dt float32) {
	if cam.tracking != nil {
		var space *SpaceComponent
		if !cam.tracking.GetComponent(&space) {
			return
		}
		cam.centerCam(Width(), Height(), 0.09, space)
	}
}

func (cam *Camera) centerCam(width, height, lerp float32, space *SpaceComponent) {
	cam.to.X += ((space.Position.X + space.Width/2) - (cam.to.X + width/2)) * lerp
	cam.to.Y += ((space.Position.Y + space.Height/2) - (cam.to.Y + height/2)) * lerp

	dWidth := cam.DeadzoneSize.X
	dHeight := cam.DeadzoneSize.Y

	if dWidth == 0 {
		dWidth = 200
	}

	if dHeight == 0 {
		dHeight = 200
	}

	min, max := Point{}, Point{}

	min.X, min.Y = cam.to.X-(dWidth/2), cam.to.Y-(dHeight/2)
	max.X, max.Y = min.X+dWidth, min.Y+dHeight

	if cam.pos.X < min.X {
		cam.pos.X = Clamp(floorFloat32(min.X), WorldBounds.Min.X, WorldBounds.Max.X-width)
	} else if cam.pos.X > max.X {
		cam.pos.X = Clamp(floorFloat32(max.X), WorldBounds.Min.X, WorldBounds.Max.X-width)
	}

	if cam.pos.Y < min.X {
		cam.pos.Y = Clamp(floorFloat32(min.Y), WorldBounds.Min.Y, WorldBounds.Max.Y-height)
	} else if cam.pos.Y > max.Y {
		cam.pos.Y = Clamp(floorFloat32(max.Y), WorldBounds.Min.Y, WorldBounds.Max.Y-height)
	}
}

func floorFloat32(i float32) float32 {
	return float32(math.Floor(float64(i)))
}


text:
<?php

namespace DAMA\DoctrineTestBundle\Behat\ServiceContainer;

use Behat\Testwork\EventDispatcher\ServiceContainer\EventDispatcherExtension;
use Behat\Testwork\ServiceContainer\Extension;
use Behat\Testwork\ServiceContainer\ExtensionManager;
use DAMA\DoctrineTestBundle\Behat\BehatListener;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class DoctrineExtension implements Extension
{
    public function getConfigKey(): string
    {
        return 'dama_doctrine';
    }

    public function initialize(ExtensionManager $extensionManager): void
    {
    }

    public function configure(ArrayNodeDefinition $builder): void
    {
    }

    public function load(ContainerBuilder $container, array $config): void
    {
        $container->register('dama_doctrine_test.listener', BehatListener::class)
            ->addTag(EventDispatcherExtension::SUBSCRIBER_TAG)
        ;
    }

    public function process(ContainerBuilder $container): void
    {
    }
}