text:
// ZAP: 2012/01/02 Separate param and attack
// ZAP: 2012/03/15 Changed the method scan to use the class StringBuilder
// instead of String.
// ZAP: 2012/04/25 Added @Override annotation to all appropriate methods.
// ZAP: 2012/12/28 Issue 447: Include the evidence in the attack field, and made into a passive scan
// rule
// ZAP: 2016/10/26 Issue 2834: Fixed the regex
// ZAP: 2016/12/15 Issue 3031: Ignore requested private IP addresses on Private IP Disclosure scan
// ZAP: 2017/06/06 Issue 3549: Exclude port when comparing hosts
// ZAP: 2019/05/08 Normalise format/indentation.
// ZAP: 2020/06/22 Normalise scan rule class naming and i18n keys.
// ZAP: 2021/08/12 Fix handling of octets with leading zeros
// ZAP: 2021/08/12 Issue 6749: Fix handling of non-octets

package org.zaproxy.zap.extension.pscanrules;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.htmlparser.jericho.Source;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.core.scanner.Plugin.AlertThreshold;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.addon.commonlib.CommonAlertTag;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;

/**
 * Checks content for private IP V4 addresses as well as Amazon EC2 private hostnames (for example,
 * ip-10-34-56-78).
 */
public class InfoPrivateAddressDisclosureScanRule extends PluginPassiveScanner {

    /** Prefix for internationalised messages used by this rule */
    private static final String MESSAGE_PREFIX = "pscanrules.infoprivateaddressdisclosure.";

    private static final Map<String, String> ALERT_TAGS =
            CommonAlertTag.toMap(
                    CommonAlertTag.OWASP_2021_A01_BROKEN_AC,
                    CommonAlertTag.OWASP_2017_A03_DATA_EXPOSED);

    private static final String REGULAR_IP_OCTET = "(25[0-5]|2[0-4]\\d|[01]?\\d{1,2})";

    private static final String NOT_FOLLOWED_BY_ANOTHER_DOTTED_NUMBER = "\\b(?!\\.\\d)";

    private static final String NOT_FOLLOWED_BY_ANOTHER_DASHED_NUMBER = "\\b(?!-\\d)";

    private static final String NOT_PRECEDED_BY_ANOTHER_DOTTED_NUMBER = "(?<!\\d\\.)\\b";

    private static final String PRECEDED_BY_IP_DASH = "\\bip-";

    /** Pattern for private IP V4 addresses as well as Amazon EC2 private hostnames */
    public static final Pattern patternPrivateIP =
            Pattern.compile(
                    "("
                            + NOT_PRECEDED_BY_ANOTHER_DOTTED_NUMBER
                            + "10\\.("
                            + REGULAR_IP_OCTET
                            + "\\.){2}"
                            + REGULAR_IP_OCTET
                            + NOT_FOLLOWED_BY_ANOTHER_DOTTED_NUMBER
                            + "|"
                            + NOT_PRECEDED_BY_ANOTHER_DOTTED_NUMBER
                            + "172\\."
                            + "(3[01]|2\\d|1[6-9])\\."
                            + REGULAR_IP_OCTET
                            + "\\."
                            + REGULAR_IP_OCTET
                            + NOT_FOLLOWED_BY_ANOTHER_DOTTED_NUMBER
                            + "|"
                            + NOT_PRECEDED_BY_ANOTHER_DOTTED_NUMBER
                            + "192\\.168\\."
                            + REGULAR_IP_OCTET
                            + "\\."
                            + REGULAR_IP_OCTET
                            + NOT_FOLLOWED_BY_ANOTHER_DOTTED_NUMBER
                            + "|"
                            // find IPs from AWS hostnames such as "ip-10-2-3-200"
                            + PRECEDED_BY_IP_DASH
                            + "10-("
                            + REGULAR_IP_OCTET
                            + "-){2}"
                            + REGULAR_IP_OCTET
                            + NOT_FOLLOWED_BY_ANOTHER_DOTTED_NUMBER
                            + "|"
                            + PRECEDED_BY_IP_DASH
                            + "172-"
                            + "(3[01]|2\\d|1[6-9])-"
                            + REGULAR_IP_OCTET
                            + "-"
                            + REGULAR_IP_OCTET
                            + NOT_FOLLOWED_BY_ANOTHER_DASHED_NUMBER
                            + "|"
                            + PRECEDED_BY_IP_DASH
                            + "192-168-"
                            + REGULAR_IP_OCTET
                            + "-"
                            + REGULAR_IP_OCTET
                            + NOT_FOLLOWED_BY_ANOTHER_DASHED_NUMBER
                            + ")"
                            // find regular ports (0-65535)
                            + "(:(0|[1-9]\\d{0,3}|[1-5]\\d{4}|6[0-4]\\d{3}|65([0-4]\\d{2}|5[0-2]\\d|53[0-5]))\\b)?",
                    Pattern.MULTILINE);

    @Override
    public int getPluginId() {
        return 00002;
    }

    @Override
    public String getName() {
        return Constant.messages.getString(MESSAGE_PREFIX + "name");
    }

    public String getDescription() {
        return Constant.messages.getString(MESSAGE_PREFIX + "desc");
    }

    public String getSolution() {
        return Constant.messages.getString(MESSAGE_PREFIX + "soln");
    }

    public String getReference() {
        return Constant.messages.getString(MESSAGE_PREFIX + "refs");
    }

    @Override
    public Map<String, String> getAlertTags() {
        return ALERT_TAGS;
    }

    public int getCweId() {
        return 200; // CWE Id 200 - Information Exposure
    }

    public int getWascId() {
        return 13; // WASC Id - Info leakage
    }

    @Override
    public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
        String host = msg.getRequestHeader().getHostName();

        String txtBody = msg.getResponseBody().toString();
        Matcher matcher = patternPrivateIP.matcher(txtBody);
        StringBuilder sbTxtFound = new StringBuilder();
        String firstOne = null;

        while (matcher.find()) {
            if (getAlertThreshold() != AlertThreshold.LOW
                    && matcher.group(1).equalsIgnoreCase(host)) {
                continue;
            }

            if (firstOne == null) {
                firstOne = matcher.group();
            }
            sbTxtFound.append(matcher.group()).append("\n");
        }

        if (sbTxtFound.length() != 0) {
            createAlert(sbTxtFound.toString(), firstOne).raise();
        }
    }

    @Override
    public List<Alert> getExampleAlerts() {
        return List.of(createAlert("192.168.36.127", "192.168.36.127").build());
    }

    private AlertBuilder createAlert(String otherInfo, String evidence) {
        return newAlert()
                .setRisk(getRisk())
                .setConfidence(Alert.CONFIDENCE_MEDIUM)
                .setDescription(getDescription())
                .setOtherInfo(otherInfo)
                .setSolution(getSolution())
                .setReference(getReference())
                .setEvidence(evidence)
                .setCweId(getCweId())
                .setWascId(getWascId());
    }

    public int getRisk() {
        return Alert.RISK_LOW;
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>org.eclipse.tm4e.samples</artifactId>
  <packaging>eclipse-plugin</packaging>
  <version>0.3.6-SNAPSHOT</version>
  <parent>
    <groupId>org.eclipse</groupId>
    <artifactId>org.eclipse.tm4e</artifactId>
    <version>0.3.2-SNAPSHOT</version>
  </parent>
</project>

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var buildWebhookFixture = require('./build-webhook-fixture');

/**
 * Webhook request information for `commit_comment`.
 * @see https://developer.github.com/v3/activity/events/types/
 * @module github-webhook-fixtures:commit_comment
 */
module.exports = buildWebhookFixture('commit_comment', {
  "action": "created",
  "comment": {
    "url": "https://api.github.com/repos/baxterthehacker/public-repo/comments/11056394",
    "html_url": "https://github.com/baxterthehacker/public-repo/commit/9049f1265b7d61be4a8904a9a27120d2064dab3b#commitcomment-11056394",
    "id": 11056394,
    "user": {
      "login": "baxterthehacker",
      "id": 6752317,
      "avatar_url": "https://avatars.githubusercontent.com/u/6752317?v=3",
      "gravatar_id": "",
      "url": "https://api.github.com/users/baxterthehacker",
      "html_url": "https://github.com/baxterthehacker",
      "followers_url": "https://api.github.com/users/baxterthehacker/followers",
      "following_url": "https://api.github.com/users/baxterthehacker/following{/other_user}",
      "gists_url": "https://api.github.com/users/baxterthehacker/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/baxterthehacker/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/baxterthehacker/subscriptions",
      "organizations_url": "https://api.github.com/users/baxterthehacker/orgs",
      "repos_url": "https://api.github.com/users/baxterthehacker/repos",
      "events_url": "https://api.github.com/users/baxterthehacker/events{/privacy}",
      "received_events_url": "https://api.github.com/users/baxterthehacker/received_events",
      "type": "User",
      "site_admin": false
    },
    "position": null,
    "line": null,
    "path": null,
    "commit_id": "9049f1265b7d61be4a8904a9a27120d2064dab3b",
    "created_at": "2015-05-05T23:40:29Z",
    "updated_at": "2015-05-05T23:40:29Z",
    "body": "This is a really good change! :+1:"
  },
  "repository": {
    "id": 35129377,
    "name": "public-repo",
    "full_name": "baxterthehacker/public-repo",
    "owner": {
      "login": "baxterthehacker",
      "id": 6752317,
      "avatar_url": "https://avatars.githubusercontent.com/u/6752317?v=3",
      "gravatar_id": "",
      "url": "https://api.github.com/users/baxterthehacker",
      "html_url": "https://github.com/baxterthehacker",
      "followers_url": "https://api.github.com/users/baxterthehacker/followers",
      "following_url": "https://api.github.com/users/baxterthehacker/following{/other_user}",
      "gists_url": "https://api.github.com/users/baxterthehacker/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/baxterthehacker/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/baxterthehacker/subscriptions",
      "organizations_url": "https://api.github.com/users/baxterthehacker/orgs",
      "repos_url": "https://api.github.com/users/baxterthehacker/repos",
      "events_url": "https://api.github.com/users/baxterthehacker/events{/privacy}",
      "received_events_url": "https://api.github.com/users/baxterthehacker/received_events",
      "type": "User",
      "site_admin": false
    },
    "private": false,
    "html_url": "https://github.com/baxterthehacker/public-repo",
    "description": "",
    "fork": false,
    "url": "https://api.github.com/repos/baxterthehacker/public-repo",
    "forks_url": "https://api.github.com/repos/baxterthehacker/public-repo/forks",
    "keys_url": "https://api.github.com/repos/baxterthehacker/public-repo/keys{/key_id}",
    "collaborators_url": "https://api.github.com/repos/baxterthehacker/public-repo/collaborators{/collaborator}",
    "teams_url": "https://api.github.com/repos/baxterthehacker/public-repo/teams",
    "hooks_url": "https://api.github.com/repos/baxterthehacker/public-repo/hooks",
    "issue_events_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues/events{/number}",
    "events_url": "https://api.github.com/repos/baxterthehacker/public-repo/events",
    "assignees_url": "https://api.github.com/repos/baxterthehacker/public-repo/assignees{/user}",
    "branches_url": "https://api.github.com/repos/baxterthehacker/public-repo/branches{/branch}",
    "tags_url": "https://api.github.com/repos/baxterthehacker/public-repo/tags",
    "blobs_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/blobs{/sha}",
    "git_tags_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/tags{/sha}",
    "git_refs_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/refs{/sha}",
    "trees_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/trees{/sha}",
    "statuses_url": "https://api.github.com/repos/baxterthehacker/public-repo/statuses/{sha}",
    "languages_url": "https://api.github.com/repos/baxterthehacker/public-repo/languages",
    "stargazers_url": "https://api.github.com/repos/baxterthehacker/public-repo/stargazers",
    "contributors_url": "https://api.github.com/repos/baxterthehacker/public-repo/contributors",
    "subscribers_url": "https://api.github.com/repos/baxterthehacker/public-repo/subscribers",
    "subscription_url": "https://api.github.com/repos/baxterthehacker/public-repo/subscription",
    "commits_url": "https://api.github.com/repos/baxterthehacker/public-repo/commits{/sha}",
    "git_commits_url": "https://api.github.com/repos/baxterthehacker/public-repo/git/commits{/sha}",
    "comments_url": "https://api.github.com/repos/baxterthehacker/public-repo/comments{/number}",
    "issue_comment_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues/comments{/number}",
    "contents_url": "https://api.github.com/repos/baxterthehacker/public-repo/contents/{+path}",
    "compare_url": "https://api.github.com/repos/baxterthehacker/public-repo/compare/{base}...{head}",
    "merges_url": "https://api.github.com/repos/baxterthehacker/public-repo/merges",
    "archive_url": "https://api.github.com/repos/baxterthehacker/public-repo/{archive_format}{/ref}",
    "downloads_url": "https://api.github.com/repos/baxterthehacker/public-repo/downloads",
    "issues_url": "https://api.github.com/repos/baxterthehacker/public-repo/issues{/number}",
    "pulls_url": "https://api.github.com/repos/baxterthehacker/public-repo/pulls{/number}",
    "milestones_url": "https://api.github.com/repos/baxterthehacker/public-repo/milestones{/number}",
    "notifications_url": "https://api.github.com/repos/baxterthehacker/public-repo/notifications{?since,all,participating}",
    "labels_url": "https://api.github.com/repos/baxterthehacker/public-repo/labels{/name}",
    "releases_url": "https://api.github.com/repos/baxterthehacker/public-repo/releases{/id}",
    "created_at": "2015-05-05T23:40:12Z",
    "updated_at": "2015-05-05T23:40:12Z",
    "pushed_at": "2015-05-05T23:40:27Z",
    "git_url": "git://github.com/baxterthehacker/public-repo.git",
    "ssh_url": "git@github.com:baxterthehacker/public-repo.git",
    "clone_url": "https://github.com/baxterthehacker/public-repo.git",
    "svn_url": "https://github.com/baxterthehacker/public-repo",
    "homepage": null,
    "size": 0,
    "stargazers_count": 0,
    "watchers_count": 0,
    "language": null,
    "has_issues": true,
    "has_downloads": true,
    "has_wiki": true,
    "has_pages": true,
    "forks_count": 0,
    "mirror_url": null,
    "open_issues_count": 2,
    "forks": 0,
    "open_issues": 2,
    "watchers": 0,
    "default_branch": "master"
  },
  "sender": {
    "login": "baxterthehacker",
    "id": 6752317,
    "avatar_url": "https://avatars.githubusercontent.com/u/6752317?v=3",
    "gravatar_id": "",
    "url": "https://api.github.com/users/baxterthehacker",
    "html_url": "https://github.com/baxterthehacker",
    "followers_url": "https://api.github.com/users/baxterthehacker/followers",
    "following_url": "https://api.github.com/users/baxterthehacker/following{/other_user}",
    "gists_url": "https://api.github.com/users/baxterthehacker/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/baxterthehacker/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/baxterthehacker/subscriptions",
    "organizations_url": "https://api.github.com/users/baxterthehacker/orgs",
    "repos_url": "https://api.github.com/users/baxterthehacker/repos",
    "events_url": "https://api.github.com/users/baxterthehacker/events{/privacy}",
    "received_events_url": "https://api.github.com/users/baxterthehacker/received_events",
    "type": "User",
    "site_admin": false
  }
});


text:
if ! [ -L /opt/chef-marketplace/embedded/cookbooks/chef-marketplace ]; then
  mv /opt/chef-marketplace/embedded/cookbooks/chef-marketplace /opt/chef-marketplace/embedded/cookbooks/chef-marketplace-pristine
  ln -s /sync/marketplace-cookbooks/chef-marketplace/ /opt/chef-marketplace/embedded/cookbooks/chef-marketplace
fi

rm -rf /var/opt/chef-marketplace/embedded/cookbooks/cache/*

echo "Workstation version of 'chef-marketplace' cookbook loaded"


text:
var express = require("express");
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var PORT = process.env.port || 3000;
var router = require('./server/router');

app.engine('.html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/server/views');

app.use('/', router);

app.listen(PORT);

console.log("server was started on "+ PORT);


text:
//using System;
//using System.Net;
//using System.Collections.Generic;
//using De.Osthus.Ambeth.Util;
//using De.Osthus.Ambeth.Log;
//using De.Osthus.Ambeth.Event;
//using De.Osthus.Ambeth.Datachange.Transfer;
//using De.Osthus.Ambeth.Datachange.Model;

//namespace De.Ostus.Ambeth.DataChange.Filter
//{
//    public class FilterRegistry : IFilterExtendable, IEventDispatcher
//    {
//        protected static ILogger logger = LoggerFactory.GetLogger(typeof(FilterRegistry));

//        protected IDictionary<String, IFilter> topicToFilterDict = new Dictionary<String, IFilter>();

//        public IEventDispatcher EventDispatcher { get; set; }

//        public void DispatchEvent(Object eventObject, DateTime dispatchTime, long sequenceId)
//        {
//            if (eventObject is IDataChange)
//            {
//                IDataChange dataChange = (IDataChange)eventObject;
//                lock (topicToFilterDict)
//                using (IEnumerator<KeyValuePair<String, IFilter>> dictIter = topicToFilterDict.GetEnumerator())
//                {
//                    foreach (IDataChangeEntry dataChangeEntry in dataChange.All)
//                    {
//                        if (!(dataChangeEntry is DataChangeEntry))
//                        {
//                            continue;
//                        }
//                        String[] topics = EvaluateMatchingTopics(dataChangeEntry, dictIter);
//                        ((DataChangeEntry)dataChangeEntry).Topics = topics;
//                    }
//                }
//            }
//            EventDispatcher.DispatchEvent(eventObject, dispatchTime, sequenceId);
//        }

//        protected String[] EvaluateMatchingTopics(IDataChangeEntry dataChangeEntry, IEnumerator<KeyValuePair<String, IFilter>> dictIter)
//        {
//            List<String> topics = new List<String>();
//            DictionaryExtension.Loop(dictIter, delegate(String topic, IFilter filter)
//            {
//                try
//                {
//                    if (filter.DoesFilterMatch(dataChangeEntry))
//                    {
//                        topics.Add(topic);
//                    }
//                }
//                catch (Exception e)
//                {
//                    if (logger.ErrorEnabled)
//                    {
//                        logger.Error("Error while handling filter '" + filter + "' on topic '" + topic + "'. Skipping this filter", e);
//                    }
//                }
//            });
//            if (topics.Count == 0)
//            {
//                return null;
//            }
//            return topics.ToArray();
//        }

//        public void RegisterFilter(IFilter filter, String topic)
//        {
//            if (filter == null)
//            {
//                throw new ArgumentException("Argument must not be null", "filter");
//            }
//            if (topic == null)
//            {
//                throw new ArgumentException("Argument must not be null", "topic");
//            }
//            topic = topic.Trim();
//            if (topic.Length == 0)
//            {
//                throw new ArgumentException("Argument must be valid", "topic");
//            }
//            lock (topicToFilterDict)
//            {
//                if (topicToFilterDict.ContainsKey(topic))
//                {
//                    throw new ArgumentException("Given topic already registered with a filter");
//                }
//                topicToFilterDict.Add(topic, filter);
//            }
//        }

//        public void UnregisterFilter(IFilter filter, String topic)
//        {
//            if (filter == null)
//            {
//                throw new ArgumentException("Argument must not be null", "filter");
//            }
//            if (topic == null)
//            {
//                throw new ArgumentException("Argument must not be null", "topic");
//            }
//            topic = topic.Trim();
//            if (topic.Length == 0)
//            {
//                throw new ArgumentException("Argument must be valid", "topic");
//            }
//            lock (topicToFilterDict)
//            {
//                IFilter registeredFilter = DictionaryExtension.ValueOrDefault(topicToFilterDict, topic);
//                if (!Object.ReferenceEquals(registeredFilter, filter))
//                {
//                    throw new ArgumentException("Given topic is registered with another filter. Unregistering illegal");
//                }
//                topicToFilterDict.Remove(topic);
//            }
//        }
//    }
//}


text:
    Return to list

      Integrations

        |

      PagerDuty

      <fieldset class="gt-fieldset"
                ng-repeat="integrationKey in config.integrationKeys">
        <legend class="gt-legend"
                style="margin-bottom: 20px;">
          Integration key
        </legend>

            This is the Integration Key displayed in PagerDuty after creating an integration of type
            Use our API directly (Events API v2).

            Can be any text. Only used when displaying the integration key on the alert configuration page.

            <button class="btn btn-danger float-right"
                    ng-click="removeIntegrationKey(integrationKey)"
                    ng-if="layout.adminEdit">
              Remove this integration key
            </button>

      </fieldset>
      <fieldset class="gt-fieldset"
                ng-if="layout.adminEdit">
        <legend class="gt-legend">
          Add {{config.integrationKeys.length ? 'another' : 'an'}} integration key
        </legend>
        <button class="btn btn-secondary"
                ng-click="addIntegrationKey()"
                style="margin-bottom: 23px; margin-left: 14px;">
          Add
        </button>
      </fieldset>


text:
var When   = require('when');
var assert = require('assert');

module.exports = function(Knex, dbName, resolver) {

  describe(dbName, function() {

    it('runs with no conditions', function(ok) {
      Knex('accounts').select().then(resolver(ok), ok);
    });

    it('throws errors on the exec if uncaught in the last block', function(ok) {

      var listeners = process.listeners('uncaughtException');

      process.removeAllListeners('uncaughtException');

      process.on('uncaughtException', function(err) {
        process.removeAllListeners('uncaughtException');
        for (var i = 0, l = listeners.length; i < l; i++) {
          process.on('uncaughtException', listeners[i]);
        }
        ok();
      });

      Knex('accounts').select().exec(function(err, resp) {
        console.log(undefinedVar);
      });
    });

    it('uses `orderBy`', function(ok) {
      Knex('accounts')
        .select()
        .orderBy('id', 'asc').then(resolver(ok), ok);
    }),

    it('does simple "where" cases', function(ok) {
      When.all([
        Knex('accounts').where('id', 1).select('first_name', 'last_name'),
        Knex('accounts').where('id', '>', 1).select(['email', 'logins']),
        Knex('accounts').where({'id': 1}).select('*'),
        Knex('accounts').where({'id': void 0}).select('*'),
        Knex('accounts').where({'id': null}).select('first_name', 'email'),
        Knex('accounts').where({'id': 0}).select()
      ]).then(resolver(ok, true), ok);
    });

    it('has a "distinct" clause', function(ok) {
      When.all([
        Knex('accounts').select().distinct('email').where('logins', 2).orderBy('email'),
        Knex('accounts').distinct('email').select().orderBy('email')
      ]).then(resolver(ok, true), ok);
    });

    it('does "orWhere" cases', function(ok) {
      When.all([
        Knex('accounts').where('id', 1).orWhere('id', '>', 2).select('first_name', 'last_name')
        // More tests can be added here.
      ]).then(resolver(ok, true), ok);
    });

    it('does "andWhere" cases', function(ok) {
      When.all([
        Knex('accounts').select('first_name', 'last_name', 'about').where('id', 1).andWhere('email', 'test@example.com')
      ]).then(resolver(ok, true), ok);
    });

    it('takes a function to wrap nested where statements', function(ok) {
      When.all([
        Knex('accounts').where(function() {
          this.where('id', 2);
          this.orWhere('id', 3);
        }).select('*')
      ]).then(resolver(ok, true), ok);
    });

    it('handles "where in" cases', function(ok) {
      When.all([
        Knex('accounts').whereIn('id', [1, 2, 3]).select()
      ]).then(resolver(ok, true), ok);
    });

    it('handles "or where in" cases', function(ok) {
      Knex('accounts')
        .where('email', 'test@example.com')
        .orWhereIn('id', [2, 3, 4])
        .select()
        .then(resolver(ok), ok);
    });

    it('handles "where exists"', function(ok) {
      Knex('accounts')
        .whereExists(function(qb) {
          this.select('id').from('test_table_two').where({id: 1});
        })
        .select()
        .then(resolver(ok), ok);
    });

    it('handles "where between"', function(ok) {
      Knex('accounts').whereBetween('id', [1, 100])
        .select()
        .then(resolver(ok), ok);
    });

    it('handles "or where between"', function(ok) {
      Knex('accounts')
        .whereBetween('id', [1, 100])
        .orWhereBetween('id', [200, 300])
        .select()
        .then(resolver(ok), ok);
    });

    it('does whereRaw', function(ok) {
      Knex('accounts')
        .whereExists(function() {
          this.select(Knex.Raw(1))
            .from('test_table_two')
            .whereRaw('test_table_two.account_id = accounts.id');
        })
        .select()
        .then(resolver(ok), ok);
    });

    it('does sub-selects', function(ok) {

      Knex('accounts').whereIn('id', function() {
        this.select('account_id').from('test_table_two').where('status', 1);
      }).select('first_name', 'last_name').then(resolver(ok), ok);

    });

    it("supports the <> operator", function(ok) {
      Knex('accounts').where('id', '<>', 2).select('email', 'logins').then(resolver(ok), ok);
    });

    it("Allows for Knex.Raw passed to the `where` clause", function(ok) {
      Knex('accounts').where(Knex.Raw('id = 2')).select('email', 'logins').then(resolver(ok), ok);
    });

  });

};


text:
package fsutil

import (
	"io"
	"os"
	"sync"

	"github.com/pkg/errors"
	"golang.org/x/net/context"
	"golang.org/x/sync/errgroup"
)

type ReceiveOpt struct {
	NotifyHashed  ChangeFunc
	ContentHasher ContentHasher
	ProgressCb    func(int, bool)
	Merge         bool
	Filter        FilterFunc
}

func Receive(ctx context.Context, conn Stream, dest string, opt ReceiveOpt) error {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	r := &receiver{
		conn:          &syncStream{Stream: conn},
		dest:          dest,
		files:         make(map[string]uint32),
		pipes:         make(map[uint32]io.WriteCloser),
		notifyHashed:  opt.NotifyHashed,
		contentHasher: opt.ContentHasher,
		progressCb:    opt.ProgressCb,
		merge:         opt.Merge,
		filter:        opt.Filter,
	}
	return r.run(ctx)
}

type receiver struct {
	dest       string
	conn       Stream
	files      map[string]uint32
	pipes      map[uint32]io.WriteCloser
	mu         sync.RWMutex
	muPipes    sync.RWMutex
	progressCb func(int, bool)
	merge      bool
	filter     FilterFunc

	notifyHashed   ChangeFunc
	contentHasher  ContentHasher
	orderValidator Validator
	hlValidator    Hardlinks
}

type dynamicWalker struct {
	walkChan chan *currentPath
	closed   bool
}

func newDynamicWalker() *dynamicWalker {
	return &dynamicWalker{
		walkChan: make(chan *currentPath, 128),
	}
}

func (w *dynamicWalker) update(p *currentPath) error {
	if w.closed {
		return errors.New("walker is closed")
	}
	if p == nil {
		close(w.walkChan)
		return nil
	}
	w.walkChan <- p
	return nil
}

func (w *dynamicWalker) fill(ctx context.Context, pathC chan<- *currentPath) error {
	for {
		select {
		case p, ok := <-w.walkChan:
			if !ok {
				return nil
			}
			pathC <- p
		case <-ctx.Done():
			return ctx.Err()
		}
	}
	return nil
}

func (r *receiver) run(ctx context.Context) error {
	g, ctx := errgroup.WithContext(ctx)

	dw, err := NewDiskWriter(ctx, r.dest, DiskWriterOpt{
		AsyncDataCb:   r.asyncDataFunc,
		NotifyCb:      r.notifyHashed,
		ContentHasher: r.contentHasher,
		Filter:        r.filter,
	})
	if err != nil {
		return err
	}

	w := newDynamicWalker()

	g.Go(func() error {
		destWalker := emptyWalker
		if !r.merge {
			destWalker = GetWalkerFn(r.dest)
		}
		err := doubleWalkDiff(ctx, dw.HandleChange, destWalker, w.fill)
		if err != nil {
			return err
		}
		if err := dw.Wait(ctx); err != nil {
			return err
		}
		r.conn.SendMsg(&Packet{Type: PACKET_FIN})
		return nil
	})

	g.Go(func() error {
		var i uint32 = 0

		size := 0
		if r.progressCb != nil {
			defer func() {
				r.progressCb(size, true)
			}()
		}
		var p Packet
		for {
			p = Packet{Data: p.Data[:0]}
			if err := r.conn.RecvMsg(&p); err != nil {
				return err
			}
			if r.progressCb != nil {
				size += p.Size()
				r.progressCb(size, false)
			}

			switch p.Type {
			case PACKET_STAT:
				if p.Stat == nil {
					if err := w.update(nil); err != nil {
						return err
					}
					break
				}
				if fileCanRequestData(os.FileMode(p.Stat.Mode)) {
					r.mu.Lock()
					r.files[p.Stat.Path] = i
					r.mu.Unlock()
				}
				i++
				cp := &currentPath{path: p.Stat.Path, f: &StatInfo{p.Stat}}
				if err := r.orderValidator.HandleChange(ChangeKindAdd, cp.path, cp.f, nil); err != nil {
					return err
				}
				if err := r.hlValidator.HandleChange(ChangeKindAdd, cp.path, cp.f, nil); err != nil {
					return err
				}
				if err := w.update(cp); err != nil {
					return err
				}
			case PACKET_DATA:
				r.muPipes.Lock()
				pw, ok := r.pipes[p.ID]
				r.muPipes.Unlock()
				if !ok {
					return errors.Errorf("invalid file request %s", p.ID)
				}
				if len(p.Data) == 0 {
					if err := pw.Close(); err != nil {
						return err
					}
				} else {
					if _, err := pw.Write(p.Data); err != nil {
						return err
					}
				}
			case PACKET_FIN:
				return nil
			}
		}
	})
	return g.Wait()
}

func (r *receiver) asyncDataFunc(ctx context.Context, p string, wc io.WriteCloser) error {
	r.mu.Lock()
	id, ok := r.files[p]
	if !ok {
		r.mu.Unlock()
		return errors.Errorf("invalid file request %s", p)
	}
	delete(r.files, p)
	r.mu.Unlock()

	wwc := newWrappedWriteCloser(wc)
	r.muPipes.Lock()
	r.pipes[id] = wwc
	r.muPipes.Unlock()
	if err := r.conn.SendMsg(&Packet{Type: PACKET_REQ, ID: id}); err != nil {
		return err
	}
	err := wwc.Wait(ctx)
	r.muPipes.Lock()
	delete(r.pipes, id)
	r.muPipes.Unlock()
	return err
}

type wrappedWriteCloser struct {
	io.WriteCloser
	err  error
	once sync.Once
	done chan struct{}
}

func newWrappedWriteCloser(wc io.WriteCloser) *wrappedWriteCloser {
	return &wrappedWriteCloser{WriteCloser: wc, done: make(chan struct{})}
}

func (w *wrappedWriteCloser) Close() error {
	w.err = w.WriteCloser.Close()
	w.once.Do(func() { close(w.done) })
	return w.err
}

func (w *wrappedWriteCloser) Wait(ctx context.Context) error {
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-w.done:
		return w.err
	}
}


text:
module.exports = {
  _: require('lodash'),
  Backbone: require('backdash')
};


text:
DTRHunspell encapsulates access to the external Hunspell library. It implements SpellingInterface to a certain degree and thus provides spell checking and correction guessing functionality as well as ignored words.

Instance Variables:
	handle			<ExternalAdress>
	classWhenAlive	<Class>

DicThesaurusRex is released under the MIT License (MIT)

Copyright (c) 2013 Daniel Neuschäfer-Rube, Suhanyaa Nitkunanantharajah, Jaqueline Pollak and Jakob Reschke

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

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

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


text:
Custom IdlingResource: IntentService
------------------------------------

Use a custom `IdlingResource` to wait for an `IntentService` to be idle.

Blog post: http://blog.sqisland.com/2015/04/espresso-custom-idling-resource.html

Video: https://caster.io/lessons/building-a-custom-espresso-idling-resource/


text:
define('crm/Models/LeadAddress/Base', ['module', 'exports', 'dojo/_base/declare', 'argos/Models/_ModelBase', '../Names', 'argos/I18n'], function (module, exports, _declare, _ModelBase2, _Names, _I18n) {
  Object.defineProperty(exports, "__esModule", {
    value: true
  });

  var _declare2 = _interopRequireDefault(_declare);

  var _ModelBase3 = _interopRequireDefault(_ModelBase2);

  var _Names2 = _interopRequireDefault(_Names);

  var _I18n2 = _interopRequireDefault(_I18n);

  function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
      default: obj
    };
  }

  var resource = (0, _I18n2.default)('leadAddressModel');

  var __class = (0, _declare2.default)('crm.Models.LeadAddress.Base', [_ModelBase3.default], {
    resourceKind: 'leadAddresses',
    entityName: 'LeadAddress',
    listViewId: 'address_related',
    entityDisplayName: resource.entityDisplayName,
    entityDisplayNamePlural: resource.entityDisplayNamePlural,
    iconClass: 'bullet-list',
    modelName: _Names2.default.LEADADDRESS

  });
  exports.default = __class;
  module.exports = exports['default'];
});


text:
package com.tngtech.jgiven.junit.lang.es;

import org.junit.Test;

import com.tngtech.jgiven.junit.lang.es.EsEscenarioTest.FaseEspannolTest;
import com.tngtech.jgiven.lang.es.Fase;
import com.tngtech.jgiven.tags.FeatureSpanish;

@FeatureSpanish
public class EsSimpleEscenarioTest extends SimpleEscenarioTest<FaseEspannolTest> {

    @Test
    public void los_escenarios_se_pueden_escribir_en_espannol() {

	dado().un_proyecto_en_espannol();

	cuando().se_usa_JGiven()
		.y().los_escenarios_se_escriben_en_espannol();

	entonces().JGiven_genera_los_informes_en_espannol();

    }

}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// System.Array
struct Il2CppArray;
// System.Object
struct Il2CppObject;

#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Array_InternalEnumerator_1_gen3676163660.h"
#include "mscorlib_System_Array1146569071.h"
#include "UnityEngine_UnityEngine_Color32598853688.h"

// System.Void System.Array/InternalEnumerator`1<UnityEngine.Color32>::.ctor(System.Array)
extern "C"  void InternalEnumerator_1__ctor_m2826013104_gshared (InternalEnumerator_1_t3676163660 * __this, Il2CppArray * ___array0, const MethodInfo* method);
#define InternalEnumerator_1__ctor_m2826013104(__this, ___array0, method) ((  void (*) (InternalEnumerator_1_t3676163660 *, Il2CppArray *, const MethodInfo*))InternalEnumerator_1__ctor_m2826013104_gshared)(__this, ___array0, method)
// System.Void System.Array/InternalEnumerator`1<UnityEngine.Color32>::System.Collections.IEnumerator.Reset()
extern "C"  void InternalEnumerator_1_System_Collections_IEnumerator_Reset_m4281953776_gshared (InternalEnumerator_1_t3676163660 * __this, const MethodInfo* method);
#define InternalEnumerator_1_System_Collections_IEnumerator_Reset_m4281953776(__this, method) ((  void (*) (InternalEnumerator_1_t3676163660 *, const MethodInfo*))InternalEnumerator_1_System_Collections_IEnumerator_Reset_m4281953776_gshared)(__this, method)
// System.Object System.Array/InternalEnumerator`1<UnityEngine.Color32>::System.Collections.IEnumerator.get_Current()
extern "C"  Il2CppObject * InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m1766787558_gshared (InternalEnumerator_1_t3676163660 * __this, const MethodInfo* method);
#define InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m1766787558(__this, method) ((  Il2CppObject * (*) (InternalEnumerator_1_t3676163660 *, const MethodInfo*))InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m1766787558_gshared)(__this, method)
// System.Void System.Array/InternalEnumerator`1<UnityEngine.Color32>::Dispose()
extern "C"  void InternalEnumerator_1_Dispose_m4247678855_gshared (InternalEnumerator_1_t3676163660 * __this, const MethodInfo* method);
#define InternalEnumerator_1_Dispose_m4247678855(__this, method) ((  void (*) (InternalEnumerator_1_t3676163660 *, const MethodInfo*))InternalEnumerator_1_Dispose_m4247678855_gshared)(__this, method)
// System.Boolean System.Array/InternalEnumerator`1<UnityEngine.Color32>::MoveNext()
extern "C"  bool InternalEnumerator_1_MoveNext_m1461072288_gshared (InternalEnumerator_1_t3676163660 * __this, const MethodInfo* method);
#define InternalEnumerator_1_MoveNext_m1461072288(__this, method) ((  bool (*) (InternalEnumerator_1_t3676163660 *, const MethodInfo*))InternalEnumerator_1_MoveNext_m1461072288_gshared)(__this, method)
// T System.Array/InternalEnumerator`1<UnityEngine.Color32>::get_Current()
extern "C"  Color32_t598853688  InternalEnumerator_1_get_Current_m3648321497_gshared (InternalEnumerator_1_t3676163660 * __this, const MethodInfo* method);
#define InternalEnumerator_1_get_Current_m3648321497(__this, method) ((  Color32_t598853688  (*) (InternalEnumerator_1_t3676163660 *, const MethodInfo*))InternalEnumerator_1_get_Current_m3648321497_gshared)(__this, method)


text:
import { Component, OnInit, ViewChild } from '@angular/core';
import { PostService, Post } from '../shared/post/index';
import { ActivatedRoute } from '@angular/router';
import { LoaderService } from '../shared/loader/loader.service';

@Component({
  moduleId: module.id,
  selector: 'wb-tag',
  templateUrl: 'tag.component.html',
  styleUrls: ['tag.component.css'],
})
export class TagComponent implements OnInit {

  loading: boolean;
  errorMessage: string;
  posts: Post[] = [];

  constructor(public postService: PostService, private route: ActivatedRoute, private loaderService: LoaderService) {
  }

  ngOnInit(): void {
    this.route.params.subscribe(params => {
      this.loadTaggedPosts(params['tag']);
    });
  }

  loadTaggedPosts(tag: string): void {
    this.loading = true;
    this.postService.getPostsByTag(tag).subscribe(posts => {
        this.posts = posts;
      },
      error => this.errorMessage = error,
      () => {
        this.loading = false;
        setTimeout(() => {
          this.loaderService.hide();
        }, 400);
      });
  }

}


text:
byte                        slip_serial_get(PORT port);
void                        slip_serial_put(PORT port, byte c);

#endif


text:
package com.baseframework.example.commons.hazelcast;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ITopic;

public class PublisherMember {

    public static void main(String[] args) {
        HazelcastInstance hz = Hazelcast.newHazelcastInstance();
        ITopic<String> topic = hz.getTopic("topic");
        topic.publish("Hello HazelCast");
    }
}


text:
import {
  Hand
} from './Hand.js';

export class BlackJackHand extends Hand {
  score() {
    let scores = this.possibleScores();
    let maxUnder = Number.MIN_VALUE;
    let minOver = Number.MAX_VALUE;
    for (let score of scores) {
      if (score > 21 && score < minOver) {
        minOver = score;
      } else if (score <= 21 && score > maxUnder) {
        maxUnder = score;
      }
    }
    return maxUnder === Number.MIN_VALUE ? minOver : maxUnder;
  }

  possibleScores() {
    let scores = [];
    if (this.cards.length === 0) {
      return scores;
    }
    for (let card of this.cards) {
      this.addCardToScoreList(card, scores);
    }
    return scores;
  }

  addCardToScoreList(card, scores) {
    if (scores.length === 0) {
      scores.push(0);
    }
    let length = scores.length;
    for (let i = 0; i < length; i++) {
      let score = scores[i];
      scores[i] = score + card.minValue();
      if (card.minValue() !== card.maxValue()) {
        scores.push(score + card.maxValue());
      }
    }
  }

  busted() {
    return this.score() > 21;
  }

  is21() {
    return this.score() === 21;
  }

  isBlackJack() {
    if (this.cards.length !== 2) {
      return false;
    }
    let first = this.cards[0];
    let second = this.cards[1];
    return (first.isAce() && second.isFaceCard()) || (second.isAce() && first.isFaceCard());
  }
}


text:
test:
	$(MAKE) QUERYSTRING="$(QUERYSTRING)" -C framework test

getallmodules:
	if [ -d subsites ]; then svn update subsites; else svn co http://svn.silverstripe.com/open/modules/subsites/trunk subsites; fi
	if [ -d genericdataadmin ]; then svn update genericdataadmin; else svn co http://svn.silverstripe.com/open/modules/genericdataadmin/trunk genericdataadmin; fi
	if [ -d forum ]; then svn update forum; else svn co http://svn.silverstripe.com/open/modules/forum/trunk forum; fi
	if [ -d cmsworkflow ]; then svn update cmsworkflow; else svn co http://svn.silverstripe.com/open/modules/cmsworkflow/trunk cmsworkflow; fi
	if [ -d multiform ]; then svn update multiform; else svn co http://svn.silverstripe.com/open/modules/multiform/trunk multiform; fi
	if [ -d events ]; then svn update events; else svn co http://svn.silverstripe.com/open/modules/events/trunk events; fi


text:
package org.apache.lucene.analysis.fi;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.fi.FinnishLightStemFilter;
import org.apache.lucene.analysis.util.TokenFilterFactory;

/**
 * Factory for {@link FinnishLightStemFilter}.
 *

 * <fieldType name="text_filgtstem" class="solr.TextField" positionIncrementGap="100">
 *   <analyzer>
 *     <tokenizer class="solr.StandardTokenizerFactory"/>
 *     <filter class="solr.LowerCaseFilterFactory"/>
 *     <filter class="solr.FinnishLightStemFilterFactory"/>
 *   </analyzer>
 * </fieldType>

 *
 */
public class FinnishLightStemFilterFactory extends TokenFilterFactory {
  @Override
  public TokenStream create(TokenStream input) {
    return new FinnishLightStemFilter(input);
  }
}


text:
html, body {
	color:#222;
	font-family:Microsoft YaHei,Helvitica,Verdana,Tohoma,Arial,san-serif;
	margin:0;
	padding: 0;
	text-decoration: none;
}
body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, textarea, p, blockquote, th, td {
	margin:0;
	padding:0;
}
img {
	border:0;
}
ol, ul {
	list-style: none outside none;
	margin:0;
	padding: 0;
}
a {
	color:#000000;
	text-decoration: none;
}
.clr {
	display:block;
	clear:both;
	height:0;
	overflow:hidden;
}
.copyright{padding:8px;text-align:center;font-size:14px;color:#0099cb;}
.copyright a{color:#0099cb;}
h2 {
	font-size:16px;
}
#cate30 {background-color:#005E92; }

#cate30 .hd{ height: auto;width:100%}
#cate30  .mainmenu:after{clear: both;
content: " ";
display: block;}
#cate30  .mainmenu li{ float:left; margin-left:1%; margin-top:1%; width:32%;   background-color:#0099cb; height:100px; border-radius:3px; }
#cate30  .mainmenu li:nth-child(2n){ background-color:#FFF}
#cate30  .mainmenu li:nth-child(2n) a{ color:#0099cb}
#cate30  .mainmenu li a{ display:block;  color:#FFF;  height:100% }
#cate30  .mainmenu li a i{ display:block; height:41%}
#cate30  .mainmenu li a img{ float:right; margin:7px 7px 0px 0px; width:30px; height:30px;}
#cate30  .mainmenu li a p{ clear:both; height:50%; padding-left:6%;}
#cate30  .mainmenu li a p b{ display:block; line-height:18px; font-size:14px; width:95%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap}
#cate30  .mainmenu li a p span{ display:block; height:32px; width:95%; font-size:12px; line-height:16px; margin-top:5px; overflow:hidden}


text:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string name="template_password_selected">Znaki od %1$d do %2$d</string>
  <string name="template_password_traversed">Znak %1$d</string>
  <string name="untitled_window">brez naslova</string>
  <string name="template_text_copied">kopirano, %1$s</string>
  <string name="template_capital_letter">velika črka %1$s</string>
  <string name="character_collapse_template"> %1$d %2$s</string>
  <string name="template_current_tts_engine">Uporaba mehanizma %1$s</string>
  <string name="keycombo_assign_dialog_instruction">Za nastavitev nove bližnjice pritisnite kombinacijo tipk. Vključevati mora vsaj tipko ALT ali Control.</string>
  <string name="keycombo_assign_dialog_default_keymap_instruction">Pritisnite kombinacijo tipk z modifikatorsko tipko %1$s, če želite nastaviti novo bližnjico.</string>
  <string name="keycombo_unassigned">Nedodeljeno</string>
  <string name="keycombo_key_modifier_shift">Shift</string>
  <string name="keycombo_key_modifier_alt">Alt</string>
  <string name="keycombo_key_modifier_ctrl">Ctrl</string>
  <string name="keycombo_key_modifier_meta">Iskanje</string>
  <string name="keycombo_key_arrow_right">Puščica desno</string>
  <string name="keycombo_key_arrow_left">Puščica levo</string>
  <string name="keycombo_key_arrow_up">Puščica gor</string>
  <string name="keycombo_key_arrow_down">Puščica dol</string>
  <string name="granularity_default">Privzeto</string>
  <string name="granularity_character">Znaki</string>
  <string name="granularity_word">Besede</string>
  <string name="granularity_line">Vrstice</string>
  <string name="granularity_paragraph">Odstavki</string>
  <string name="granularity_window">Okna</string>
  <string name="granularity_web_landmark">Posamezni sklopi</string>
  <string name="granularity_web_heading">Naslovi</string>
  <string name="granularity_web_list">Seznami</string>
  <string name="granularity_web_link">Povezave</string>
  <string name="granularity_web_control">Kontrolniki</string>
  <string name="granularity_pseudo_web_special_content">Posebna vsebina</string>
  <string name="granularity_native_heading">Naslovi</string>
  <string name="granularity_native_control">Kontrolniki</string>
  <string name="granularity_native_link">Povezave</string>
  <string name="template_overlay_window">Slika v sliki za %1$s</string>
  <string name="template_split_screen_mode_portrait">%1$s na vrhu, %2$s na dnu</string>
  <string name="template_split_screen_mode_landscape_ltr">%1$s na levi, %2$s na desni</string>
  <string name="template_split_screen_mode_landscape_rtl">%1$s na desni, %2$s na levi</string>
  <string name="template_scroll_from_to_count">Prikaz elementov %1$d−%2$d od skupno %3$d.</string>
  <string name="template_scroll_from_count">Prikaz elementa %1$d od %2$d.</string>
  <string name="template_viewpager_index_count">Stran %1$d od %2$d</string>
  <string name="template_viewpager_index_count_short">%1$d od %2$d</string>
  <string name="url_dialog_table">%1$s (%2$s)</string>
  <string name="exit_scrim">Zapri</string>
  <string name="show_keyboard_window">Tipkovnica %1$s je prikazana</string>
  <string name="hide_keyboard_window">Tipkovnica je skrita</string>
  <string name="function_on">Glasovni odziv je vklopljen</string>
  <string name="function_off">Glasovni odziv je izklopljen</string>
</resources>


text:
jQuery(document).ready(function(){
	console.log('[Regoffices] Region. Initializing...');
	});


text:
<?php
namespace FOS\UserBundle\Entity;

/* ======================================================
 * The original FOSUserBundle did some sort of majic to allow extending driectly from Model/User
 *
 * However, the simple default way requires User to live in the Entity directory
 * Probably a case of adding a mapping directory to setup file
 *
 * But this works for now and is a bit clearer to me
 */
use FOS\UserBundle\Model\User as BaseUser;

class User extends BaseUser
{

}
?>


text:
 0'>

            #
            {{ 'fullName' | i18next}}
            {{ 'rank' | i18next}}
            {{ 'role' | i18next}}
            {{ 'unit' | i18next}}

              {{$index + 1}}

{{signature.fullName}}

{{signature.rank}}

{{signature.role}}

{{signature.unit}}

              <button class="deleteSignature-button" ng-show="showButton" ng-click="delete(signature)"></button>

{{ 'noSignatures' | i18next}}

            <form ng-submit="submit()">

              <input type="text" class="form-control" ng-model="signature.fullName" placeholder="{{ 'fullName' | i18next}}" maxlength="20" required>

              <input type="text" class="form-control" ng-model="signature.rank" placeholder="{{ 'rank' | i18next}}" maxlength="20">

              <input type="text" class="form-control" ng-model="signature.role" placeholder="{{ 'role' | i18next}}" required maxlength="20">

                <input type="text" class="form-control" ng-model="signature.unit" placeholder="{{ 'unit' | i18next}}" maxlength="20">

                    <button type="submit" class="addSignature"></button>

            </form>


text:
<?php
// https://azure.microsoft.com/en-us/documentation/articles/storage-php-how-to-use-table-storage/

require_once 'vendor\autoload.php';
//ini_set('display_errors', 1);
//error_reporting(~0);

use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;

// Storage의 connection string 제공
$connectionString = "DefaultEndpointsProtocol=http;AccountName=dwazurecampstor09;AccountKey=ls5oNGYKMk2QZxGz2kb3GkZI29UAmONGkpKgFJvIgAfpY67nLplQN/FL/68EtYSYfM80eGdvkgo0WtgVjxZbpw==";

// Azure의 table storage를 위한 REST proxy 생성
$tableRestProxy = ServicesBuilder::getInstance()->createTableService($connectionString);

/////////////////////////////////////////////////////////////////
// 01 테이블 생성
/////////////////////////////////////////////////////////////////
try {
    // 테이블 생성
    $tableRestProxy->createTable("phptable");
}
catch(ServiceException $e){
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

?>


text:
namespace perlin_noise_node
{

class Nao: public PerlinNode
{
public:
  //! Intialize PerlinNode along with everything specific to this robot
  Nao(ros::NodeHandle nh);

  //! Timer callback for publishing message.
  void timerCallback(const ros::TimerEvent& event);
};
}

#endif // PERLIN_NOISE_NODE_NAO_H


text:
/**
 *  Set up namespace
 */
namespace Php {

/**
 *  List of functions that are available for use in PHP
 */
extern PHPCPP_EXPORT    bool  class_exists(const char *classname, size_t size, bool autoload = true);
inline PHPCPP_EXPORT    bool  class_exists(const char *classname, bool autoload = true) { return class_exists(classname, strlen(classname), autoload); }
inline PHPCPP_EXPORT    bool  class_exists(const std::string &classname, bool autoload = true) { return class_exists(classname.c_str(), classname.size(), autoload); }
extern PHPCPP_EXPORT    Value constant(const char *constant);
extern PHPCPP_EXPORT    Value constant(const char *constant, size_t size);
extern PHPCPP_EXPORT    Value constant(const std::string &constant);
extern PHPCPP_EXPORT    bool  define(const char *name, size_t size, const Value &value);
extern PHPCPP_EXPORT    bool  define(const char *name, const Value &value);
extern PHPCPP_EXPORT    bool  define(const std::string &name, const Value &value);
extern PHPCPP_EXPORT    bool  defined(const char *constant);
extern PHPCPP_EXPORT    bool  defined(const char *constant, size_t size);
extern PHPCPP_EXPORT    bool  defined(const std::string &constant);
extern PHPCPP_EXPORT    bool  dl(const char *filename, bool persistent = false);
inline PHPCPP_EXPORT    bool  dl(const std::string &filename, bool persistent = false) { return dl(filename.c_str(), persistent); }
inline PHPCPP_EXPORT    bool  dl(const Value &filename, bool persistent = false) { return dl(filename.rawValue(), persistent); }
extern PHPCPP_EXPORT    Value eval(const char *phpCode);
inline PHPCPP_EXPORT    Value eval(const std::string &phpCode) { return eval(phpCode.c_str()); }
extern PHPCPP_EXPORT    Value include(const char *filename);
inline PHPCPP_EXPORT    Value include(const std::string &filename) { return include(filename.c_str()); }
extern PHPCPP_EXPORT    Value include_once(const char *filename);
inline PHPCPP_EXPORT    Value include_once(const std::string &filename) { return include_once(filename.c_str()); }
inline PHPCPP_EXPORT    bool  is_a(const Value &obj, const char *classname, size_t size, bool allow_string = false) { return obj.instanceOf(classname, size, allow_string); }
inline PHPCPP_EXPORT    bool  is_a(const Value &obj, const char *classname, bool allow_string = false) { return is_a(obj, classname, strlen(classname), allow_string); }
inline PHPCPP_EXPORT    bool  is_a(const Value &obj, const std::string &classname, bool allow_string = false) { return is_a(obj, classname.c_str(), classname.size(), allow_string); }
inline PHPCPP_EXPORT    bool  is_subclass_of(const Value &obj, const char *classname, size_t size, bool allow_string = true) { return obj.derivedFrom(classname, size, allow_string); }
inline PHPCPP_EXPORT    bool  is_subclass_of(const Value &obj, const char *classname, bool allow_string = true) { return is_subclass_of(obj, classname, strlen(classname), allow_string); }
inline PHPCPP_EXPORT    bool  is_subclass_of(const Value &obj, const std::string &classname, bool allow_string = true) { return is_subclass_of(obj, classname.c_str(), classname.size(), allow_string); }
extern PHPCPP_EXPORT    Value require(const char *filename);
inline PHPCPP_EXPORT    Value require(const std::string &filename) { return require(filename.c_str()); }
extern PHPCPP_EXPORT    Value require_once(const char *filename);
inline PHPCPP_EXPORT    Value require_once(const std::string &filename) { return require_once(filename.c_str()); }
extern PHPCPP_EXPORT    Value set_exception_handler(const std::function<Value(Parameters &params)> &handler);
extern PHPCPP_EXPORT    Value set_error_handler(const std::function<Value(Parameters &params)> &handler, Message message = Message::All);
extern PHPCPP_EXPORT    Value error_reporting(Message message);
extern PHPCPP_EXPORT    const char *sapi_name();

/**
 *  Call a function in PHP
 *  @param  name        Name of the function to call
 *  @param  params      Variable number of parameters
 *  @return Value
 */
template <typename ...Params>
Value call(const char *name, Params&&... params)
{
    // the name can be turned into a Php::Value object, which implements
    // the operator () method to call it
    Value function(name);

    // invoke the operator ()
    return function(std::forward<Params>(params)...);
}

/**
 *  Long list of simply-forwarded function calls
 *
 *  Most functions in this list are forwarded to the call() method described
 *  above, which of course is slower than necessary, because they will have to
 *  pass the entire zend engine to look up the actual implementation, while a
 *  direct call the C implementation was possible too. The reason for this is
 *  that we are lazy - if you feel like looking up the actual implementation for
 *  each function in the PHP source, your support is more than welcome.
 *
 *  But since it is a stupid idea to call a PHP function from your extension
 *  anyway (that's what people write extension for: to get away from PHP and
 *  make the code run on the highway), it is not expected that these functions
 *  are going to be used very often anyway.
 */
inline PHPCPP_EXPORT    Value array_key_exists(const Value &key, const Value &array) { return array.contains(key); }
inline PHPCPP_EXPORT    Value array_key_exists(int key, const Value &array) { return array.contains(key); }
inline PHPCPP_EXPORT    Value array_key_exists(const char *key, const Value &array) { return array.contains(key); }
inline PHPCPP_EXPORT    Value array_key_exists(const std::string &key, const Value &array) { return array.contains(key); }
inline PHPCPP_EXPORT    Value array_keys(const Value &value) { return call("array_keys", value); }
inline PHPCPP_EXPORT    Value array_push(const Value &array, const Value &value) { return call("array_push", array, value); }
inline PHPCPP_EXPORT    Value array_values(const Value &value) { return call("array_values", value); }
inline PHPCPP_EXPORT    Value count(const Value &value) { return call("count", value); }
inline PHPCPP_EXPORT    Value echo(const char *input) { out << input; return nullptr; }
inline PHPCPP_EXPORT    Value echo(const std::string &input) { out << input; return nullptr; }
inline PHPCPP_EXPORT    Value empty(const Value &value) { return value.isNull() || !value.boolValue(); }
inline PHPCPP_EXPORT    Value empty(const HashMember<std::string> &member) { return !member.exists() || empty(member.value()); }
inline PHPCPP_EXPORT    Value empty(const HashMember<int> &member) { return !member.exists() || empty(member.value()); }
inline PHPCPP_EXPORT    Value is_array(const Value &value) { return value.isArray(); }
inline PHPCPP_EXPORT    Value strlen(const Value &value) { return call("strlen", value); }
inline PHPCPP_EXPORT    void  unset(const HashMember<std::string> &member) { member.unset(); }
inline PHPCPP_EXPORT    void  unset(const HashMember<int> &member) { member.unset(); }
inline PHPCPP_EXPORT    void  unset(const HashMember<Value> &member) { member.unset(); }

/**
 *  The 'ini_get' function returns an IniValue, so that it can also be used
 *  before the PHP engine is started.
 */
inline PHPCPP_EXPORT    IniValue ini_get(const char* name) { return IniValue(name, false); }
inline PHPCPP_EXPORT    IniValue ini_get_orig(const char* name) { return IniValue(name, true); }

/**
 *  The isset function conflicts with the 'isset' macro defined by the Zend engine
 */
#pragma push_macro("isset")
#undef isset

/**
 *  Define the isset function
 */
inline PHPCPP_EXPORT    Value isset(const Value &value) { return call("isset", value); }
inline PHPCPP_EXPORT    Value isset(const HashMember<std::string> &member) { return member.exists() && isset(member.value()); }
inline PHPCPP_EXPORT    Value isset(const HashMember<int> &member) { return member.exists() && isset(member.value()); }
inline PHPCPP_EXPORT    Value isset(const HashMember<Value> &member) { return member.exists() && isset(member.value()); }

/**
 *  Re-install the ISSET macro
 */
#pragma pop_macro("isset")

/**
 *  End of namespace
 */
}


text:
//
//  UIView+Tag.h
//  AJTagView
//
//  Created by AlienJunX on 16/5/12.
//  Copyright (c) 2016 AlienJunX
//
//  This source code is licensed under the MIT-style license found in the
//  LICENSE file in the root directory of this source tree.
//

#import <UIKit/UIKit.h>
#import "AJTagView.h"

@interface UIView (Tag)

/**
 *  显示单个tag
 *
 *  @param percent 百分比
 *  @param text    标签内容
 *
 *  @return 添加到当前view 的tag
 */
- (AJTagView *)aj_showTagWithPercent:(CGPoint)percent text:(NSString *)text;

/**
 *  批量显示tag
 *
 *  @param percentArray 百分比数组 [CGPoint,CGPoint,CGPoint]
 *  @param textArray    显示的标签内容
 *
 *  @return 添加到当前view 的所有tags
 */
- (NSArray *)aj_showTagsWithPercentArray:(NSArray *)percentArray textArray:(NSArray *)textArray;

@end


text:
/**
 */
package tosca.tests;

import junit.framework.TestCase;

import junit.textui.TestRunner;

import tosca.TBoundaryDefinitions;
import tosca.ToscaFactory;

/**
 *
 * A test case for the model object 'TBoundary Definitions'.
 *
 * @generated
 */
public class TBoundaryDefinitionsTest extends TestCase {

	/**
	 * The fixture for this TBoundary Definitions test case.
	 *
	 *
	 * @generated
	 */
	protected TBoundaryDefinitions fixture = null;

	/**
	 *
	 *
	 * @generated
	 */
	public static void main(String[] args) {
		TestRunner.run(TBoundaryDefinitionsTest.class);
	}

	/**
	 * Constructs a new TBoundary Definitions test case with the given name.
	 *
	 *
	 * @generated
	 */
	public TBoundaryDefinitionsTest(String name) {
		super(name);
	}

	/**
	 * Sets the fixture for this TBoundary Definitions test case.
	 *
	 *
	 * @generated
	 */
	protected void setFixture(TBoundaryDefinitions fixture) {
		this.fixture = fixture;
	}

	/**
	 * Returns the fixture for this TBoundary Definitions test case.
	 *
	 *
	 * @generated
	 */
	protected TBoundaryDefinitions getFixture() {
		return fixture;
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#setUp()
	 * @generated
	 */
	@Override
	protected void setUp() throws Exception {
		setFixture(ToscaFactory.eINSTANCE.createTBoundaryDefinitions());
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#tearDown()
	 * @generated
	 */
	@Override
	protected void tearDown() throws Exception {
		setFixture(null);
	}

} //TBoundaryDefinitionsTest


text:
<?php

namespace HiPay\Wallet\Mirakl\Vendor\Event;

//use HiPay\Wallet\Mirakl\Api\HiPay\Model\Soap\BankInfo;
use HiPay\Wallet\Mirakl\Api\HiPay\Model\Rest\BankInfo;
use Symfony\Component\EventDispatcher\Event;

class CheckBankInfos extends Event
{
    /** @var bool  */
    protected $synchronicity;

    /** @var BankInfo  */
    protected $miraklBankInfo;

    /** @var BankInfo  */
    protected $hipayBankInfo;

    /**
     * CheckBankInfos constructor.
     * @param BankInfo $miraklBankInfo
     * @param BankInfo $hipayBankInfo
     */
    public function __construct(BankInfo $miraklBankInfo, BankInfo $hipayBankInfo)
    {
        $this->miraklBankInfo = $miraklBankInfo;
        $this->hipayBankInfo = $hipayBankInfo;
        $this->synchronicity = true;
    }

    /**
     * @return BankInfo
     */
    public function getMiraklBankInfo()
    {
        return $this->miraklBankInfo;
    }

    /**
     * @return BankInfo
     */
    public function getHipayBankInfo()
    {
        return $this->hipayBankInfo;
    }

    /**
     * @return boolean
     */
    public function isSynchrony()
    {
        return $this->synchronicity;
    }

    /**
     * @param boolean $synchronicity
     */
    public function setSynchronicity($synchronicity)
    {
        $this->synchronicity = $synchronicity;
    }
}


text:
static void test_ffs()
{
    const int pre_errno = errno;

    ASSERT_EQUALS("swab: Checking, if ffs(0) returns 0", ffs(0), 0);
    ASSERT_EQUALS("swab: Checking, if ffs(1) returns 1", ffs(1), 1);
    ASSERT_EQUALS("swab: Checking, if ffs(2) returns 2", ffs(2), 2);
    ASSERT_EQUALS("swab: Checking, if ffs(4) returns 3", ffs(4), 3);
    ASSERT_EQUALS("swab: Checking, if ffs(8) returns 4", ffs(8), 4);
    ASSERT_EQUALS("swab: Checking, if ffs(16) returns 5", ffs(16), 5);
    ASSERT_EQUALS("swab: Checking, if ffs(32) returns 6", ffs(32), 6);
    ASSERT_EQUALS("swab: Checking, if ffs(64) returns 7", ffs(64), 7);
    ASSERT_EQUALS("swab: Checking, if ffs(128) returns 8", ffs(128), 8);
    ASSERT_EQUALS("swab: Checking, if ffs(256) returns 9", ffs(256), 9);
    ASSERT_EQUALS("swab: Checking, if ffs(512) returns 10", ffs(512), 10);
    ASSERT_EQUALS("swab: Checking, if ffs(1024) returns 11", ffs(1024), 11);
    ASSERT_EQUALS("swab: Checking, if ffs(2048) returns 12", ffs(2048), 12);
    ASSERT_EQUALS("swab: Checking, if ffs(4096) returns 13", ffs(4096), 13);
    ASSERT_EQUALS("swab: Checking, if ffs(8192) returns 14", ffs(8192), 14);
    ASSERT_EQUALS("swab: Checking, if ffs(16384) returns 15", ffs(16384), 15);
    ASSERT_EQUALS("swab: Checking, if ffs(32768) returns 16", ffs(32768), 16);
    ASSERT_EQUALS("swab: Checking, if ffs(65536) returns 17", ffs(65536), 17);
    ASSERT_EQUALS("swab: Checking, if ffs(131072) returns 18", ffs(131072), 18);

    ASSERT_EQUALS("ffs: Checking, if errno is unmodified", pre_errno, errno);
}

static void test_strcasecmp()
{
    const int pre_errno = errno;
    const char* src_buffer_0 = "aabb";
    const char* src_buffer_1 = "aabbA";
    const char* src_buffer_2 = "aaBB";

    const int result_0 = strcasecmp(src_buffer_0, src_buffer_0);
    const int result_1 = strcasecmp(src_buffer_0, src_buffer_1);
    const int result_2 = strcasecmp(src_buffer_0, src_buffer_2);
    const int result_3 = strcasecmp(src_buffer_1, src_buffer_0);

    ASSERT_LESS("strcasecmp: Checking, if result is less 0, if s1 contains the greater object", result_1, 0);
    ASSERT_LESS("strcasecmp: Checking, if result is greater 0, if s2 contains the greater object", 0, result_3);
    ASSERT_EQUALS("strcasecmp: Checking, if result is 0, if s1 and s2 are equal", result_0, 0);
    ASSERT_EQUALS("strcasecmp: Checking, if result is 0, if s1 and s2 are equal (case ignored)", result_2, 0);
    ASSERT_EQUALS("strcasecmp: Checking, if errno is unmodified", pre_errno, errno);
}

static void test_strncasecmp()
{
    const int pre_errno = errno;
    const char* src_buffer_0 = "aabb";
    const char* src_buffer_1 = "aabbA";
    const char* src_buffer_2 = "aaBB";

    const int result_0 = strncasecmp(src_buffer_0, src_buffer_0, 5);
    const int result_1 = strncasecmp(src_buffer_0, src_buffer_1, 5);
    const int result_2 = strncasecmp(src_buffer_0, src_buffer_2, 5);
    const int result_3 = strncasecmp(src_buffer_0, src_buffer_1, 4);
    const int result_4 = strncasecmp(src_buffer_1, src_buffer_0, 5);

    ASSERT_LESS("strncasecmp: Checking, if result is less 0, if s1 contains the greater object", result_1, 0);
    ASSERT_EQUALS("strncasecmp: Checking, if result is 0, if s1 and s2 are equal", result_0, 0);
    ASSERT_EQUALS("strncasecmp: Checking, if result is 0, if s1 and s2 are equal (case ignored)", result_2, 0);
    ASSERT_LESS("strncasecmp: Checking, if result is greater 0, if s2 contains the greater object", 0, result_4);
    ASSERT_EQUALS("strncasecmp: Checking, if maxlen was considered correctly", result_3, 0);
    ASSERT_EQUALS("strncasecmp: Checking, if errno is unmodified", pre_errno, errno);
}

// Check all functions of unistd.h
void run_strings_tests()
{
    TEST_CASE("Test POSIX strings.h functions");

    test_ffs();

    test_strcasecmp();
    test_strncasecmp();
}


text:
local onlyNTSC = false

function love.load()
	if onlyNTSC then
		effect = require('effect_ntsc')
	else
		effect = require('effect')
	end

	-- set display mode
	love.window.setMode(768, 720)
	love.window.setTitle("CRT Effect Demonstration")

	-- set default filter
	love.graphics.setDefaultFilter("nearest", "nearest")

	-- initialize canvas
	effect.init()

	-- load assets
	ntsc = love.graphics.newImage("resources/ntsc.png")
	ntsc:setWrap("repeat", "repeat")
	ntsc:setFilter("linear", "linear")
	ntscQuad = love.graphics.newQuad(0, 0, getWidth(), getHeight(), ntsc:getDimensions())

	shadowmask = love.graphics.newImage("resources/shadowmask.png")
	shadowmask:setWrap("repeat", "repeat")
	shadowmaskQuad = love.graphics.newQuad(0, 0, getDisplayWidth(), getDisplayHeight(), shadowmask:getDimensions())

	test = love.graphics.newImage("testing/contra.png")
	testQuad = love.graphics.newQuad(0, 0, getWidth(), getHeight(), test:getDimensions())
end

local time = 0

function love.draw()
	effect.preDraw()

	time = time + 1

	-- game code goes here
	love.graphics.push()
	love.graphics.scale(getScale())
	love.graphics.draw(test, testQuad, 0, 0)

	-- ntsc artifacts
	love.graphics.scale(getScale())
	love.graphics.setColor(255, 255, 255, 24)
	love.graphics.draw(ntsc, ntscQuad, 0, 0)
	love.graphics.pop()

	-- shadow mask
	if onlyNTSC then
		love.graphics.push()
		love.graphics.scale(1)
		love.graphics.setColor(255, 255, 255, 64)
		love.graphics.setBlendMode("additive")
		love.graphics.draw(shadowmask, shadowmaskQuad, 0, 0)
		love.graphics.setBlendMode("alpha")
		love.graphics.pop()
	end

	-- draw canvas w/ shader
	love.graphics.push()
	love.graphics.scale(1)
	love.graphics.setColor(255, 255, 255, 255)

	if onlyNTSC then
		effect.postDraw(0)
	else
		effect.postDraw(16)
	end

	love.graphics.pop()
end

function love.keypressed(k)
	if k == "escape" then
		love.event.quit()
	end
end

function getWidth()
	return getDisplayWidth() / getScale()
end

function getHeight()
	return getDisplayHeight() / getScale()
end

function getDisplayWidth()
	return love.graphics.getWidth()
end

function getDisplayHeight()
	return love.graphics.getHeight()
end

function getScale()
	return 3
end


text:
Shows the DBot Score and reputation of the Domain.
## Script Data
---

| **Name** | **Description** |
| --- | --- |
| Script Type | python3 |
| Tags | dynamic-section |
| Cortex XSOAR Version | 5.0.0 |

## Inputs
---
There are no inputs for this script.

## Outputs
---
There are no outputs for this script.


text:
layout: default
title: Quantitative Neurobiology
desc: Matlab notes, assignments, and code
post_title: "Week 5: Fitting models"
author: John Pearson
category: blog
---
In our last week on programming, we'll pivot toward the rest of the semester's material by talking about fitting computational models. Perhaps surprisingly, the actual mechanics behind fitting models to data is rarely discussed, and so we'll focus a little on the theory of fitting and the rest of our time on the actual mechanics of writing code that does this.

So **before our first class**:

- Read about Matlab's [`fminsearch`](https://www.mathworks.com/help/matlab/ref/fminsearch.html) function.
- Watch a video on the math behind linear regression:
    <video width="100%" align="center" controls src="{{ site.videourl }}/linear_regression.mp4" type="video/mp4">
		Your browser does not support the video tag.
	</video>

In the most generic case, finding the minimum of an arbitrary function \\(f(x)\\) is computationally intractable: there is no guarantee we can find the global minimum. However, in many cases of interest, special properties of \\(f(x)\\) allow us to make use of symmetries that allow for efficient solution of the problem. Much of the research on optimization involves either proving that some class of optimization problems can be reduced to another with nice mathematical properties (so optimization can be performed efficiently) or designing new optimization algorithms that solve some class of problems faster (in fewer steps or less time per step).

For our second class this week, we'll focus on simply using Matlab's facilities for optimization without getting into details of the algorithms involved. That is, we'll treat these as "black box" methods that take in an function \\(f\\) and spit out an answer.

So, **before our second class**:

- Read about [optimizing nonlinear functions](https://www.mathworks.com/help/matlab/math/optimizing-nonlinear-functions.html)
- Read about [curve fitting via optimization](https://www.mathworks.com/help/matlab/math/example-curve-fitting-via-optimization.html).


text:
namespace google {
namespace protobuf {
class Message;
}  // namespace protobuf
}  // namespace google

namespace rpcz {

// replier is copyable.
// Each request has its own replier, and should reply once.
// replier can be used in callback by copy.  // TODO: Need example.
// replier's copy operator is quick.
// TODO: More comments...
class RPCZ_API replier {
 public:
  replier(const connection_ptr& conn, uint64 event_id)
      : conn_(conn), event_id_(event_id) {
    GOOGLE_CHECK(conn);
  }
  ~replier() {}

 public:
  // reply(protocol::Message) is only for cpp use.
  void reply(const google::protobuf::Message& response) const {
    conn_->reply(event_id_, response);
  }
  //void reply(const std::string& response) const {
  //  conn_->reply(event_id_, response);
  //}
  void reply_error(int error_code,
      const std::string& error_message="") const {
    conn_->reply_error(event_id_, error_code, error_message);
  }

 public:
  connection_ptr get_connection_ptr() const { return conn_; }

private:
  const connection_ptr conn_;
  const uint64 event_id_;
};  // class replier

}  // namespace rpcz
#endif  // RPCZ_REPLIER_HPP


text:
<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="default_horizontal_margin">16dp</dimen>
    <dimen name="default_vertical_margin">16dp</dimen>
    <dimen name="example_horizontal_margin">20dp</dimen>

    <!-- Different font sizes for the examples -->
    <dimen name="font_large_size">22sp</dimen>
    <dimen name="font_med_size">16sp</dimen>

</resources>


text:
{% extends "base.html" %}
{% block content %}

    {% block breadcrumb %}
    {% endblock breadcrumb %}

        {% for article in articles_page.object_list %}

                        {{
                            article.title }}

 {{ article.locale_date
                        }}

 {{ article.summary }}

        {% endfor %}

    {% include 'pagination.html' %}

{% endblock content %}


text:
/**
* LibrosListController
* Controlador del listado de libros
*/
function RecipesListController($scope, $http) {
  $http.get('http://localhost/backend-api/web/app_dev.php/api/recetas').success(function(data) {
	$scope.libros = data._embedded.recetas;
  });

  //selecciona el desplegable y ordena automaticamente, variable definida en la vista con ng-model
  $scope.orderField = "nombre";
  $scope.orderReverse = "true";
}


text:
package org.springframework.security.crypto.password;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * Helper for working with the MessageDigest API.
 *
 * Performs the configured number of iterations of the hashing algorithm per digest to aid in protecting against brute force attacks.
 *
 * @author Keith Donald
 * @author Luke Taylor
 */
final class Digester {

    private final MessageDigest messageDigest;

    private final int iterations;

    /**
     * Create a new Digester.
     * @param algorithm the digest algorithm; for example, "SHA-1" or "SHA-256".
     * @param iterations the number of times to apply the digest algorithm to the input
     */
    public Digester(String algorithm, int iterations) {
        try {
            messageDigest = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("No such hashing algorithm", e);
        }

        this.iterations = iterations;
    }

    public byte[] digest(byte[] value) {
        synchronized (messageDigest) {
            for (int i = 0; i < iterations; i++) {
                value = messageDigest.digest(value);
            }
            return value;
        }
    }
}


text:
	<title>Leaflet</title>
	<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />


text:
using System;

class FormattingNumbers
{
    static void Main()
    {
        Console.Write("Enter an integer number (from 0 to 500): ");
        int a = int.Parse(Console.ReadLine());
        Console.Write("Enter first floating-point number: ");
        double b = double.Parse(Console.ReadLine());
        Console.Write("Enter second floating-point number: ");
        double c = double.Parse(Console.ReadLine());

        Console.Write("{0,-10:X}|", a);
        Console.Write("{0}|", Convert.ToString(a, 2).PadLeft(10, '0'));
        Console.Write(("{0,10:0.##}|"), b);
        Console.WriteLine(("{0,-10:F3}|"), c);
    }
}


text:
import osmapi# https://pypi.python.org/pypi/osmapi see also: https://pypi.python.org/pypi?%3Aaction=search&term=openstreetmap&submit=search

OSM_URL = "localhost"

###
def config(instanceURL="localhost:8080"):
    pass


text:
extern "C"
{
#endif

#define RTP_PAYLOAD_SIZE    1436

// RTP header definition.
typedef struct
{
    unsigned char   version_p_x_cc;
    unsigned char   m_pt;
    unsigned short  sequence_number;
    unsigned int    timestamp;
    unsigned short  ssrc;
    unsigned short  csrc;

} sRTP_HEADER;

// RTP payload definition.
typedef struct
{
    unsigned char   bytes[RTP_PAYLOAD_SIZE];

} sRTP_PAYLOAD;

// RTP packet definition.
typedef struct
{
    sRTP_HEADER     header;
    sRTP_PAYLOAD    payload;

} sRTP_PKT;

// RTP packet node definition.
typedef struct sRTP_PKT_NODE
{
    struct sRTP_PKT_NODE   *next;           ///< Next packet
    sRTP_PKT                rtp_pkt;        ///< Packet
    unsigned int            rtp_pkt_len;    ///< Packet length

} sRTP_PKT_NODE;

extern void * sx_nal_to_rtp_util_create(
    void
    );

extern void sx_nal_to_rtp_util_destroy(
    void *arg
    );

extern sRTP_PKT_NODE * sx_nal_to_rtp_util_get(
    void           *arg,
    unsigned char  *h264_frame,
    unsigned int    h264_frame_len
    );

extern void sx_nal_to_rtp_util_free(
     sRTP_PKT_NODE * head
    );

#if defined(cplusplus)
}
#endif

#endif // #if !defined(__H264_TO_RTP__)


text:
package export;

import java.util.List;

import spreadsheet.data.SpreadSheetData;
import export.exporter.ExportOptions;

/**
 * @author Daniel J. Rivers
 *         2014
 *
 * Created: Jul 12, 2014, 4:31:38 PM
 */
public interface Exportable {

	public static enum ExportType { TEXT, XLS };

	public ExportType[] getAvailableTypes();

	public StringBuffer getTextExportObject( ExportOptions opt );

	public List<SpreadSheetData> getSpreadSheetExportObject( ExportOptions opt );
}


text:
<?php

namespace Phalcon\Test\Unit5x\Mvc\Model\MetaData;

use UnitTester;
use Phalcon\Test\Models\Robots;
use Phalcon\Mvc\Model\Metadata\Memcache;

class MemcacheCest
{
    private $data;

    public function _before(UnitTester $I)
    {
        if (!class_exists('Memcache')) {
            throw new \PHPUnit_Framework_SkippedTestError(
                'Warning: Memcache class does not exist, test skipped'
            );
        }

        $I->haveServiceInDi('modelsMetadata', function () {
            return new Memcache([
                'host' => env('TEST_MC_HOST', '127.0.0.1'),
                'port' => env('TEST_MC_PORT', 11211),
            ]);
        }, true);

        $this->data = require PATH_FIXTURES . 'metadata/robots.php';
    }

    public function memcached(UnitTester $I)
    {
        $I->wantTo('fetch metadata from memcached cache');

        /** @var \Phalcon\Mvc\Model\MetaDataInterface $md */
        $md = $I->grabServiceFromDi('modelsMetadata');

        $md->reset();
        $I->assertTrue($md->isEmpty());

        Robots::findFirst();

        $I->assertEquals(
            $this->data['meta-robots-robots'],
            $md->read("meta-phalcon\\test\\models\\robots-robots")
        );
        $I->assertEquals(
            $this->data['map-robots'],
            $md->read("map-phalcon\\test\\models\\robots")
        );

        $I->assertFalse($md->isEmpty());

        $md->reset();
        $I->assertTrue($md->isEmpty());
    }
}


text:
<?php

class BaseController extends Controller {

    /**
     * Constante que le indica al paginador de datos, cuantos registros deben
     * mostrarse por página.
     *
     * @var integer
     */
    const PAGINATE_PER_PAGE = 15;

    /**
     * Setup the layout used by the controller.
     *
     * @return void
     */
    protected function setupLayout()
    {
        if (! is_null($this->layout)) {
            $this->layout = View::make($this->layout);
        }
    }

    /**
     * Create a new Validator instance.
     *
     * @access protected
     * @param  array  $data
     * @param  array  $rules
     * @param  array  $messages
     * @param  array  $customAttributes
     * @return Validator
     */
    protected function validation(array $data, array $rules, array $messages = array(), array $customAttributes = array())
    {
        return Validator::make($data, $rules, $messages, $customAttributes);
    }

    /**
     * Store items in the session only for the next request.
     *
     * @access protected
     * @param  mixed  $key
     * @param  mixed  $value
     */
    protected function flash($key, $value = null)
    {
        Session::flash($key, $value);
    }

    /**
     * Returns only the models from the collection with the specified
     * array keys.
     *
     * @access protected
     * @param  array  $keys
     * @return array
     */
    protected function onlyKeys(array $keys)
    {
        $keys = array_keys($keys);
        return $this->only($keys);
    }

    /**
     * Returns only the models from the collection with the specified
     * keys.
     *
     * @access protected
     * @param  array  $keys
     * @return array
     */
    protected function only(array $keys)
    {
        return Input::only($keys);
    }

    /**
     * Filtra los datos de la solicitúd $_GET para realizar una busqueda
     * unicamente con los datos que pasaron la validación.
     *
     * @access protected
     * @param  array  $filtro
     * @return array
     */
    protected function search(array $filtro)
    {
        $validacion = $this->validation($this->onlyKeys($filtro), $filtro);
        $validacion->passes();
        $buscar = $validacion->getData();

        // datos que no pasaron la validación, son regresados con valor null:
        foreach($validacion->failed() as $ignora => $regla) {
            $buscar[$ignora] = null;
        }

        return $buscar;
    }

    /**
     * Determine if the request is the result of an AJAX call.
     *
     * @access protected
     * @return boolean
     */
    protected function isAjax()
    {
        return Request::ajax();
    }

    /**
     * Get the request method and determine if the request is post.
     *
     * @access protected
     * @return boolean
     */
    protected function isPost()
    {
        return Request::isMethod('post');
    }

    // end BaseController.php
}


text:
from google.appengine.ext import db, ndb
from google.appengine.api import taskqueue
from google.appengine.api import memcache
from datetime import datetime
from google.appengine.ext import deferred
import time
import webapp2
from time import gmtime
import logging

class SimpleCounter(ndb.Model):

  name = ndb.StringProperty(required=True)
  count = ndb.IntegerProperty(required=True)
  added = ndb.DateTimeProperty(auto_now_add=True)
  updated = ndb.DateTimeProperty(auto_now=True)

def pingpong_incr(key_name):

  # Changing slot every 10 minutes
  slot = gmtime().tm_min / 10 % 2
  # A bug with initial value: http://code.google.com/p/googleappengine/issues/detail?id=2012
  if memcache.incr('%s_%s' % (key_name, slot), namespace='ia') is None:
	# Can set no such key existed
	memcache.set('%s_%s' % (key_name, slot), 1, namespace='ia')

def pingpong_get(key_name, from_ping=True):

  if from_ping:
	slot = gmtime().tm_min / 10 % 2
  else:
	slot = (gmtime().tm_min + 10) / 10 % 2
  return memcache.get('%s_%s' % (key_name, slot), namespace='ia')

def pingpong_delete(key_name):

  slot = (gmtime().tm_min + 10) / 10 % 2
  memcache.delete('%s_%s' % (key_name, slot), namespace='ia')


text:
package com.google.api.codegen.util;

public interface CommentReformatter {
  /** Reformats the given comment to match a language comment format */
  String reformat(String comment);
}


text:
package org.myrobotlab.service;

import java.io.IOException;

import org.myrobotlab.framework.Peers;
import org.myrobotlab.framework.Service;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.interfaces.SerialDataListener;
import org.slf4j.Logger;

public class MPU6050 extends Service implements SerialDataListener {

	private static final long serialVersionUID = 1L;

	public final static Logger log = LoggerFactory.getLogger(MPU6050.class);

	StringBuilder debugRX = new StringBuilder();

	private transient Serial serial;

	public static Peers getPeers(String name) {
		Peers peers = new Peers(name);

		// put peer definitions in
		peers.put("serial", "Serial", "Serial");
		return peers;
	}

	public static void main(String[] args) {
		LoggingFactory.getInstance().configure();

		try {

			MPU6050 mpu6050 = (MPU6050) Runtime.start("mpu6050", "MPU6050");
			mpu6050.test();

			Runtime.start("gui", "GUIService");

		} catch (Exception e) {
			Logging.logError(e);
		}
	}

	public MPU6050(String n) {
		super(n);
	}

	public boolean connect(String port) {
		return serial.connect(port, this);
	}

	public String formatMRLCommMsg(String prefix, byte[] message, int size) {
		debugRX.setLength(0);
		if (prefix != null) {
			debugRX.append(prefix);
		}
		debugRX.append(String.format("MAGIC_NUMBER|SZ %d|FN %d", size, message[0]));
		for (int i = 1; i < size; ++i) {
			debugRX.append(String.format("|P%d %d", i, message[i]));
		}
		return debugRX.toString();
	}

	@Override
	public String[] getCategories() {
		return new String[] { "microcontroller" };
	}

	@Override
	public String getDescription() {
		return "used as a general mpu6050";
	}

	@Override
	public void startService() {
		super.startService();
		serial = (Serial) startPeer("serial");
	}

	@Override
	public final Integer onByte(Integer newByte) throws IOException {
		info("%s onByte %s", getName(), newByte);
		return newByte;
	}

	@Override
	public String onConnect(String portName) {
		info("%s connected to %s", getName(), portName);
		return portName;
	}

	@Override
	public String onDisconnect(String portName) {
		info("%s disconnected from %s", getName(), portName);
		return portName;
	}

}


text:
<?PY from tenjin.helpers import _decode_params ?>
<?py for article in articles: ?>
<url><loc>#{{BLOG_HOME_FULL_URL}}#{article.quoted_url()}</loc><lastmod>#{sitemap_time_format(article.mod_time)}</lastmod></url>
<?py #endfor ?>


text:
        <button class="btn btn-primary" ng-click="editCluster()">Edit Cluster</button>

{{clusterName}} ({{clusterVersion}})

{{zone[0].zone}}

                                {{config.useFullnames ? comp.name : comp.shortname}}

                            {{node.getHostname()}}
                            (#{{node.getCardinality()}})
                            - {{node.zone}}

{{clusterName}} ({{clusterVersion}})

{{zone[0].zone}}

                            {{node.getHostname()}}
                            (#{{node.getCardinality()}})
                            - {{node.zone}}

                                {{config.useFullnames ? comp.name : comp.shortname}}{{$last ? '' : ','}}

{{clusterName}} ({{clusterVersion}})

{{zone[0].zone}}

                                {{config.useFullnames ? service.name : service.shortname}}

                            {{node.getHostname()}}
                            (#{{node.getCardinality()}})
                            - {{node.zone}}

{{clusterName}} ({{clusterVersion}})

{{zone[0].zone}}

                            {{node.getHostname()}}
                            (#{{node.getCardinality()}})
                            - {{node.zone}}

                                {{config.useFullnames ? service.name : service.shortname}}{{$last ? '' : ','}}

{{clusterName}} ({{clusterVersion}})

                                {{hostname}}

                            {{node.comps.length}} components
                            Zone: {{node.zone}}

                        {{comp.name}}
                        {{service.name}}

                        Node
                        Components
                        Services

Add Node to Component (-Alpha-)

                Oops! Component is already available on this node.

            <form class="form-horizontal" novalidate>

                    Node
                    <select ng-model="node" ng-options="node.getHostname() for node in nodes = nodes" class="form-control" required ng-change="formChange()"></select>

                    Component
                    <select ng-model="comp" ng-options="comp.name group by comp.service.name for comp in comps = comps" class="form-control" required  ng-change="formChange()"></select>

                    <button class="btn btn-primary" ng-click="addToNode()">Add</button>

            </form>