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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery;
using Microsoft.WindowsAzure.Management.SiteRecovery.Models;

namespace Microsoft.Azure.Commands.RecoveryServices
{
    /// <summary>
    /// Retrieves Azure Site Recovery Recovery Plan.
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "AzureSiteRecoveryRecoveryPlan", DefaultParameterSetName = ASRParameterSets.Default)]
    [OutputType(typeof(ASRRecoveryPlan))]

    public class GetAzureSiteRecoveryRecoveryPlan : RecoveryServicesCmdletBase
    {
        #region Parameters
        /// <summary>
        /// Gets or sets Recovery Plan ID.
        /// </summary>
        [Parameter(ParameterSetName = ASRParameterSets.ById, Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets name of the Recovery Plan.
        /// </summary>
        [Parameter(ParameterSetName = ASRParameterSets.ByName, Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public string Name { get; set; }
        #endregion Parameters

        /// <summary>
        /// ProcessRecord of the command.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            try
            {
                this.WriteWarningWithTimestamp(
                    string.Format(
                        Properties.Resources.CmdletWillBeDeprecatedSoon,
                        this.MyInvocation.MyCommand.Name));

                switch (this.ParameterSetName)
                {
                    case ASRParameterSets.ByName:
                        this.GetByName();
                        break;
                    case ASRParameterSets.ById:
                        this.GetById();
                        break;
                    case ASRParameterSets.Default:
                        this.GetByDefault();
                        break;
                }
            }
            catch (Exception exception)
            {
                this.HandleException(exception);
            }
        }

        /// <summary>
        /// Queries by name.
        /// </summary>
        private void GetByName()
        {
            RecoveryPlanListResponse recoveryPlanListResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryRecoveryPlan();

            bool found = false;
            foreach (RecoveryPlan recoveryPlan in recoveryPlanListResponse.RecoveryPlans)
            {
                if (0 == string.Compare(this.Name, recoveryPlan.Name, true))
                {
                    this.WriteRecoveryPlan(recoveryPlan);
                    found = true;
                }
            }

            if (!found)
            {
                throw new InvalidOperationException(
                    string.Format(
                    Properties.Resources.RecoveryPlanNotFound,
                    this.Name,
                    PSRecoveryServicesClient.asrVaultCreds.ResourceName));
            }
        }

        /// <summary>
        /// Queries by ID.
        /// </summary>
        private void GetById()
        {
            RecoveryPlanResponse recoveryPlanResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryRecoveryPlan(this.Id);

            this.WriteRecoveryPlan(recoveryPlanResponse.RecoveryPlan);
        }

        /// <summary>
        /// Queries all / by default.
        /// </summary>
        private void GetByDefault()
        {
            RecoveryPlanListResponse recoveryPlanListResponse =
                RecoveryServicesClient.GetAzureSiteRecoveryRecoveryPlan();

            this.WriteRecoveryPlans(recoveryPlanListResponse.RecoveryPlans);
        }

        /// <summary>
        /// Writes Recovery Plans.
        /// </summary>
        /// <param name="recoveryPlans">List of Recovery Plans</param>
        private void WriteRecoveryPlans(IList<RecoveryPlan> recoveryPlans)
        {
            this.WriteObject(recoveryPlans.Select(rp => new ASRRecoveryPlan(rp)), true);
        }

        /// <summary>
        /// Writes Recovery Plan.
        /// </summary>
        /// <param name="recoveryPlan">Recovery Plan</param>
        private void WriteRecoveryPlan(RecoveryPlan recoveryPlan)
        {
            this.WriteObject(new ASRRecoveryPlan(recoveryPlan));
        }
    }
}


text:
/*
--- Part Two ---

Santa's password expired again. What's the next one?
 */

import nextPassword from './1.js';

export default function solution(input) {
  return nextPassword(nextPassword(input));
};

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#00CCCCCC" />
            <corners android:radius="5dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#10CCCCCC" />
            <corners android:radius="5dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#20CCCCCC" />
            <corners android:radius="5dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#30CCCCCC" />
            <corners android:radius="5dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#50CCCCCC" />
            <corners android:radius="5dp" />
        </shape>
    </item>

    <!-- Background -->
    <item>
        <shape>
            <solid android:color="#FFFFFF" />
            <corners android:radius="5dp" />
        </shape>
    </item>
</layer-list>


text:
import { formatNumber } from '@superset-ui/core';

function formatCellValue(
  i: number,
  cols: string[],
  tdText: string,
  columnFormats: any,
  numberFormat: string,
  dateRegex: RegExp,
  dateFormatter: any,
) {
  const metric: string = cols[i];
  const format: string = columnFormats[metric] || numberFormat || '.3s';
  let textContent: string = tdText;
  let sortAttributeValue: any = tdText;

  if (parseFloat(tdText)) {
    const parsedValue = parseFloat(tdText);
    textContent = formatNumber(format, parsedValue);
    sortAttributeValue = parsedValue;
  } else {
    const regexMatch = dateRegex.exec(tdText);
    if (regexMatch) {
      const date = new Date(parseFloat(regexMatch[1]));
      textContent = dateFormatter(date);
      sortAttributeValue = date;
    } else if (tdText === 'null') {
      textContent = '';
      sortAttributeValue = Number.NEGATIVE_INFINITY;
    }
  }

  return { textContent, sortAttributeValue };
}

function formatDateCellValue(
  text: string,
  verboseMap: any,
  dateRegex: RegExp,
  dateFormatter: any,
) {
  const regexMatch = dateRegex.exec(text);
  let cellValue;
  if (regexMatch) {
    const date = new Date(parseFloat(regexMatch[1]));
    cellValue = dateFormatter(date);
  } else {
    cellValue = verboseMap[text] || text;
  }
  return cellValue;
}

export { formatCellValue, formatDateCellValue };


text:
// See docs in ../ops/nn_ops.cc.

#define EIGEN_USE_THREADS

#include "tensorflow/core/framework/op_kernel.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/kernels/sparse_xent_op.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"

namespace tensorflow {

typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;

template <typename Device, typename T>
class SparseSoftmaxXentWithLogitsOp : public OpKernel {
 public:
  explicit SparseSoftmaxXentWithLogitsOp(OpKernelConstruction* context)
      : OpKernel(context) {}

  void Compute(OpKernelContext* context) override {
    const Tensor& logits_in = context->input(0);
    const Tensor& labels_in = context->input(1);
    OP_REQUIRES(context, logits_in.shape().dim_size(0) == labels_in.NumElements(),
                errors::InvalidArgument(
                    "logits first dimension must match labels size.  logits shape=",
                    logits_in.shape().DebugString(), " labels shape=",
                    labels_in.shape().DebugString()));
    OP_REQUIRES(context, TensorShapeUtils::IsMatrix(logits_in.shape()),
                errors::InvalidArgument("logits must be 2-dimensional"));
    // As we already tested that both inputs have the same shape no need to
    // check that "labels" is a matrix too.

    // loss is 1-D (one per example), and size is batch_size.

    Tensor scratch;
    OP_REQUIRES_OK(
        context, context->allocate_temp(DataTypeToEnum<T>::value,
                                        TensorShape({logits_in.dim_size(0)}),
                                        &scratch));

    Tensor* loss_out = nullptr;
    OP_REQUIRES_OK(context,
                   context->allocate_output(
                       0, TensorShape({logits_in.dim_size(0)}), &loss_out));
    Tensor* back_out = nullptr;
    OP_REQUIRES_OK(context,
                   context->allocate_output(1, logits_in.shape(), &back_out));

    functor::SparseXentFunctor<Device, T> functor;
    functor(context->eigen_device<Device>(), logits_in.matrix<T>(),
            labels_in.vec<int64>(), scratch.vec<T>(), loss_out->vec<T>(),
            back_out->matrix<T>());
  }
};

// Partial specialization for a CPUDevice, that uses the Eigen implementation
// from XentEigenImpl.
namespace functor {
template <typename T>
struct SparseXentFunctor<CPUDevice, T> {
  void operator()(const CPUDevice& d, typename TTypes<T>::ConstMatrix logits,
                  typename TTypes<int64>::ConstVec labels,
                  typename TTypes<T>::Vec scratch,
                  typename TTypes<T>::Vec loss,
                  typename TTypes<T>::Matrix backprop) {
    SparseXentEigenImpl<CPUDevice, T>::Compute(d, logits, labels, scratch, loss,
                                         backprop);
  }
};
}  // namespace functor

REGISTER_KERNEL_BUILDER(Name("SparseSoftmaxCrossEntropyWithLogits")
                            .Device(DEVICE_CPU)
                            .TypeConstraint<float>("T"),
                        SparseSoftmaxXentWithLogitsOp<CPUDevice, float>);
REGISTER_KERNEL_BUILDER(Name("SparseSoftmaxCrossEntropyWithLogits")
                            .Device(DEVICE_CPU)
                            .TypeConstraint<double>("T"),
                        SparseSoftmaxXentWithLogitsOp<CPUDevice, double>);

#if GOOGLE_CUDA
REGISTER_KERNEL_BUILDER(Name("SparseSoftmaxCrossEntropyWithLogits")
                            .Device(DEVICE_GPU)
                            .TypeConstraint<float>("T"),
                        SparseSoftmaxXentWithLogitsOp<GPUDevice, float>);
#endif  // GOOGLE_CUDA

}  // namespace tensorflow


text:
<?php

/**
 * Modified: 2020-05-24T22:08:35+00:00
 */
namespace Office365\Directory\Applications;

use Office365\Runtime\ClientValue;
class ImplicitGrantSettings extends ClientValue
{
    /**
     * @var bool
     */
    public $EnableIdTokenIssuance;
    /**
     * @var bool
     */
    public $EnableAccessTokenIssuance;
}


text:
package com.kyrlach.functional.monad.maybe;

import java.util.function.Function;
import java.util.function.Supplier;

/**
 * A sum type that represents a value that may be present, or may not be.
 *
 * @param <A> the type of the optional value
 */
public abstract class Maybe<A> {

	/**
	 * A type constructor that lifts an {@code A} to a {@code Maybe<A>}.
	 *
	 * @param <A> the type of value to lift
	 * @param b the value to lift
	 * @return a {@code Maybe<A>} representing an optionally present value
	 */
	public static <A> Maybe<A> toMaybe(final A b)
	{
		if(b == null) {
			return new Nothing<A>();
		} else {
			return new Just<A>(b);
		}
	}

	/**
	 * Simulates ML style pattern matching on the union, applying the function just when this {@code Maybe<A>}
	 * is a {@code Just<A>}, or applying the function nothing when this {@code Maybe<A>} is a {@code Nothing<A>}.
	 *
	 * @param <B> the result type
	 * @param just the function to apply when this is a {@code Just<A>}
	 * @param nothing the function to apply when this is a {@code Nothing<A>}
	 * @return the result of applying the appropriate function
	 */
	public abstract <B> B match(final Function<A, B> just, final Supplier<B> nothing);

	/**
	 * Lifts a function {@code A -> B} to {@code Maybe<A> -> Maybe<B>} and applies the function to this {@code Maybe<A>}. This
	 * yields a {@code Just<B>} when this is a {@code Just<A>}, or a {@code Nothing<B>} when this is a {@code Nothing<A>}.
	 *
	 * @param <B> the domain of {@code f}
	 * @param f the function to lift
	 * @return the {@code Maybe<B>} as a result of applying the lifted function {@code f}
	 */
	public <B> Maybe<B> map(final Function<A, B> f)
	{
		return this.match(a -> toMaybe(f.apply(a)), () -> new Nothing<B>());
	}

	/**
	 * Lifts a function {@code A -> Maybe<B>} to {@code Maybe<A> -> Maybe<B>} and applies the function to this {@code Maybe<A>}.
	 * This yields a {@code Just<B>} when this is a {@code Just<A>}, or a {@code Nothing<B>} when this is a {@code Nothing<A>}.
	 *
	 * @param <B> the domain of {@code f}
	 * @param f the function to lift
	 * @return the {@code Maybe<A>} as a result of applying the lifted function {@code f}
	 */
	public <B> Maybe<B> flatMap(final Function<A, Maybe<B>> f)
	{
		return this.match(a -> f.apply(a), () -> new Nothing<B>());
	}

	/**
	 * Yields the lifted value when this is a {@code Just<A>}, or the value provided by the supplier defaultValue
	 * when this is a {@code Nothing<A>}.
	 *
	 * @param defaultValue a supplier that provides an {@code A} to use when this is a {@code Nothing<A>}
	 * @return either the lifted value or the value supplied by {@code defaultValue}
	 */
	public A getOrElse(final Supplier<A> defaultValue)
	{
		return this.match(a -> a, defaultValue);
	}
}


text: Sign in using your social accounts


text:
import fnmatch
import os
import re
import datetime
import calendar
import sqlite3
import optparse

import html2text

protocols = []

class Protocol(object):
    def __init__(self, name):
        self.name = name
        self.accounts = []

    def add_account(self, account):
        self.accounts.append(account)

    def contains_account(self, account_name):
        for account in self.accounts:
            if account.name == account_name:
                return account
        return None

class Account(object):
    def __init__(self, name):
        self.name = name
        self.contacts = []

    def add_contact(self, contact):
        self.contacts.append(contact)

    def contains_contact(self, contact_name):
        for contact in self.contacts:
            if contact.name == contact_name:
                return contact
        return None

class Contact(object):
    def __init__(self, name, group_chat=False):
        self.name = name
        self.alias = []
        self.messages = []
        self.group_chat = group_chat

    def add_message(self, message):
        self.messages.append(message)

class Message(object):
    def __init__(self, name, time, kind, show, message, subject):
        """
        :param kind: -1 if unknown
        """
        self.name = name
        self.time = time
        self.kind = kind
        self.show = show
        self.message = message
        self.subject = subject

def get_make_contact(root):
    """Integrates contact into protocol-account-contact-message-datastructure and returns it
    :param root: path to folder one level above log files
    :return: contact-object for that path
    """
    root_split = root.split('/')

    contact_name = root_split[-1]
    #groupchat's folder's end with .chat
    group_chat = False
    if contact_name.endswith(".chat"):
        contact_name = contact_name[:-5]
        group_chat = True

    account_name = root_split[-2]
    protocol_name = root_split[-3]

    protocol_contained = None
    for protocol in protocols:
        if protocol.name == protocol_name:
            protocol_contained = protocol
            break
    if not protocol_contained:
        protocol_contained = Protocol(protocol_name)
        protocols.append(protocol_contained)

    account_contained = protocol_contained.contains_account(account_name)
    if not account_contained:
        account_contained = Account(account_name)
        protocol_contained.add_account(account_contained)

    contact_contained = account_contained.contains_contact(contact_name)
    if not contact_contained:
        contact_contained = Contact(contact_name, group_chat)
        account_contained.add_contact(contact_contained)

    return contact_contained, account_contained

def add_message(name, time, message_text, root):
    """Adds message to global data-structure
    :param name: Name of person who wrote the msg
    :param time: Unix-timestamp of msg
    :param message_text:
    :param root: path to file (without filename)
    """
    (contact, account) = get_make_contact(root)

    show = None
    subject = None

    group_chat = False
    if root.endswith(".chat"):
        group_chat = True

    #actions
    if message_text and message_text.startswith("***"):
        for alias in contact.alias:
            if message_text.startswith("***" + alias) or message_text.startswith("*****" + alias + "**"):
                name = alias
                message_text = message_text.replace("*****" + alias + "**", "/me")
                message_text = message_text.replace("***" + alias, "/me")

    #not: status updates and encrypted messages
    if not name or name.startswith("The following message received from") or name == "OTR Error":
        return

    #more actions
    if name.startswith("***"):
        for alias in contact.alias:
            if name.startswith("***" + alias) or name.startswith("*****" + alias + "**"):
                message_text = name.replace("*****" + alias + "**", "/me")
                message_text = message_text.replace("***" + alias, "/me")
                name = alias

    kind = -1
    if group_chat:
        if name not in contact.alias:
            contact.alias.append(name)
        kind = 2
    else:
        if name not in contact.alias:
            contact.alias.append(name)

    message = Message(name, time, kind, show, message_text, subject)
    contact.add_message(message)

regex_date = re.compile("(\d{4})-(\d{2})-(\d{2})")

regex_html_time = re.compile(".*?>\(.*?(\d{2}):(\d{2}):(\d{2}).*?\).*")
regex_html_rest = re.compile(".*?>\(\d{2}:\d{2}:\d{2}.*?\)(.*)")
regex_html = re.compile(".*?>\(\d{2}:\d{2}:\d{2}.*?\)<.*?<b>(.*?):</b>(.*)")

def parse_html(root, filename):
    """Parses pidgin's html-formated log-files
    HTML within messages is converted to normal text, so messages about HTML-code will get lost
    :param root: Path to folder with logs by contact
    :param filename: Log-file (html) to be parsed
    """

    root_filename = os.path.join(root, filename)

    match_date = regex_date.findall(filename)
    if not match_date:
        raise Exception(root_filename, 'r')

    year = int(match_date[0][0])
    month = int(match_date[0][1])
    day = int(match_date[0][2])

    file = open(root_filename)
    lines = file.readlines()
    for line in lines[1:]:
        match_time = regex_html_time.match(line)
        if match_time:
            hour = int(match_time.group(1))
            minute = int(match_time.group(2))
            second = int(match_time.group(3))
            time = datetime.datetime(year, month, day, hour, minute, second)
            timestamp = calendar.timegm(time.utctimetuple())

            match_html = regex_html.match(line)
            if match_html:
                name = match_html.group(1)

                message_text = html2text.html2text(match_html.group(2)).replace("\\n", "\n").strip()

                add_message(name, timestamp, message_text, root)

            else:
                match_rest = regex_html_rest.match(line)
                message_text = None
                if match_rest:
                    message_text = html2text.html2text(match_rest.group(1)).replace("\\n", "\n").strip()
                add_message(None, timestamp, message_text, root)

regex_txt_time = re.compile("\(.*?(\d{2}):(\d{2}):(\d{2}).*")
regex_txt_rest = re.compile("\(\d{2}:\d{2}:\d{2}.*?\) (.*)")
regex_txt = re.compile("\(\d{2}:\d{2}:\d{2} .*\) (.*?): (.*)")

def parse_txt(root, filename):
    """Parses pidgin's txt-formated log-files
    :param root: Path to folder with logs by contact
    :param filename: Log-file (txt) to be parsed
    """

    root_filename = os.path.join(root, filename)

    match_date = regex_date.findall(filename)
    if not match_date:
        raise Exception(root_filename, 'r')

    year = int(match_date[0][0])
    month = int(match_date[0][1])
    day = int(match_date[0][2])

    file = open(root_filename)
    lines = file.readlines()

    i = 0
    while i < len(lines):
        match_time = regex_txt_time.match(lines[i])
        if match_time:
            hour = int(match_time.group(1))
            minute = int(match_time.group(2))
            second = int(match_time.group(3))
            time = datetime.datetime(year, month, day, hour, minute, second)
            timestamp = calendar.timegm(time.utctimetuple())

            match_txt = regex_txt.match(lines[i])
            if match_txt:

                name = match_txt.group(1)
                message_text = match_txt.group(2).strip()

                i += 1
                if i < len(lines):
                    match_time = regex_txt_time.match(lines[i])
                    while not match_time and i < len(lines):
                        message_text += "\n" + lines[i].strip()
                        i += 1
                        if i < len(lines):
                            match_time = regex_txt_time.match(lines[i])

                add_message(name, timestamp, message_text, root)
            else:
                match_rest = regex_txt_rest.match(lines[i])
                message_text = None
                if match_rest:
                    message_text = match_rest.group(1)
                add_message(None, timestamp, message_text, root)
                i += 1
        else:
            i += 1

def database_insert(db):
    """Insert messages (from global data-structure) into db
    :param db: Path to db to insert into
    """
    con = sqlite3.connect(db)
    cur = con.cursor()
    for protocol in protocols:
        if protocol.name == "jabber":
            for account in protocol.accounts:
                for contact in account.contacts:
                    print("Inserting", contact.name)
                    cur.execute("SELECT jid_id FROM jids WHERE jid=\"" + contact.name + "\"")
                    jid_id = cur.fetchone()

                    #contact doesn't exist in db
                    if not jid_id:
                        print("Adding", contact.name)
                        if contact.group_chat:
                            value = 1
                        else:
                            value = 0
                        cur.execute("INSERT INTO jids(jid, type) VALUES(?, ?)", (contact.name, value))
                        cur.execute("SELECT jid_id FROM jids WHERE jid=\"" + contact.name + "\"")
                        jid_id = cur.fetchone()

                    #insert msg
                    jid_id = jid_id[0]
                    for message in contact.messages:
                        if message.kind == 2:
                            sql_insert = jid_id, message.name, message.time, message.kind, message.message
                            print(sql_insert)
                            cur.execute("SELECT * FROM logs WHERE jid_id=? and contact_name=? and time=? and kind=? and message=?", sql_insert)
                            if not cur.fetchone():
                                cur.execute("INSERT INTO logs(jid_id, contact_name, time, kind, message) VALUES(?, ?, ?, ?, ?)", sql_insert)
                        elif message.kind == 4 or message.kind == 6:
                            sql_insert = jid_id, message.time, message.kind, message.message
                            cur.execute("SELECT * FROM logs WHERE jid_id=? and time=? and kind=? and message=?", sql_insert)
                            if not cur.fetchone():
                                cur.execute("INSERT INTO logs(jid_id, time, kind, message) VALUES(?, ?, ?, ?)", sql_insert)

    con.commit()
    con.close()

def parse_dir(root, filenames):
    """Parses files into global datastructure
    :param root: Path to files to parse
    :param filenames: Files to parse
    """
    for filename in fnmatch.filter(filenames, '*.html'):
        parse_html(root, filename)
    for filename in fnmatch.filter(filenames, '*.txt'):
        parse_txt(root, filename)

def names_interaction():
    """Asks user for own nicks after listing all encountered ones
    :return:List of entered nicks
    """
    already_printed = []
    for protocol in protocols:
        for account in protocol.accounts:
            for contact in account.contacts:
                for message in contact.messages:
                    if message.name not in already_printed:
                        already_printed.append(message.name)
                        print(message.name)
    nicks = input("Own nicks, comma separated: ")
    nicks = nicks.split(",")
    nicks = [nick.strip() for nick in nicks]
    return nicks

def message_update_kind(alias_me):
    """Updates global data-structure with message type (own, not own)
    :param alias_me: list of nicks of self
    """
    for protocol in protocols:
        for account in protocol.accounts:
            for contact in account.contacts:
                for message in contact.messages:
                    #if kind not jet known
                    if message.kind == -1:
                        if message.name in alias_me:
                            message.kind = 6
                        else:
                            message.kind = 4

def main():
    parser = optparse.OptionParser()
    parser.add_option("-i", "--indir", action="store", type="string", dest="in_dir")
    parser.add_option("-o", "--outfile", action="store", type="string", dest="out_file")
    parser.parse_args()

    own_checked = []

    for root, dirnames, filenames in os.walk(parser.values.in_dir):
        print("Parsing", root)

        parse_dir(root, filenames)

    alias_me = names_interaction()
    message_update_kind(alias_me)
    database_insert(parser.values.out_file)

if __name__ == '__main__':
    main()


text:
class SnapshotArray(list):
	"""Guarantees that array entries provided by begin()"""
	def __init__(self):
		list.__init__(self)
		self.recycled = None
		self.snapshot = None
		self.snapshots = 0

	def begin(self):
		"""Returns the backing array, which is guaranteed to  not be modified
		before end()"""
		self.modified()
		self.snapshot = self[:]
		self.snapshots += 1
		return self.snapshot

	def end(self):
		"""Releases the guarantee tha tth earray returned by begin()
		won't be modified"""
		self.snapshots = max(0, self.snapshots-1)
		if self.snapshot is None:
			return

		if self.snapshot != self and self.snapshots == 0:
			#the backing array was copied, keep around the old array
			self.recycled = self.snapshot[:]
			for i in range(len(self.recycled)):
				self.recycled[i] = None

			self.snapshot = None

	def modified(self):
		if ((self.snapshot is None) or (self.snapshot != self)):
			return
		#snapshot is in use, copy backing array to recycled array
		#or create a new backing array
		if (self.recycled is not None):
			self[:] = self.recycled[:]
			self.recycled = None

	def __setitem__(self, key, item):
		self.modified()
		list.__setitem__(self, key, item)

	def append(self, item):
		self.modified()
		list.append(self, item)

	def remove(self, item):
		self.modified()
		list.remove(self, item)

	def reverse(self):
		self.modified()
		list.reverse(self)

	def pop(self):
		self.modified()
		return list.pop(self)

	def sort(self, key=None):
		self.modified()
		list.sort(self, key)

	def __setslice__(self, i, j, seq):
		self.__setitem__(slice(i, j), seq)


text:
package com.streamreduce.rest.dto.response;

import com.streamreduce.core.model.SobaObject;
import com.streamreduce.core.model.dto.ObjectIdSerializer;

import java.util.Set;
import java.util.TreeSet;

import org.bson.types.ObjectId;
import org.codehaus.jackson.map.annotate.JsonSerialize;

public class SobaObjectResponseDTO extends ObjectWithIdResponseDTO {

    private String alias;
    private String description;
    private ObjectId accountId;
    private ObjectId userId;
    private Set<String> hashtags = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
    private SobaObject.Visibility visibility;

    public SobaObject.Visibility getVisibility() {
        return visibility;
    }

    public void setVisibility(SobaObject.Visibility visibility) {
        this.visibility = visibility;
    }

    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @JsonSerialize(using = ObjectIdSerializer.class)
    public ObjectId getAccountId() {
        return accountId;
    }

    public void setAccountId(ObjectId accountId) {
        this.accountId = accountId;
    }

    @JsonSerialize(using=ObjectIdSerializer.class)
    public ObjectId getUserId() {
        return userId;
    }

    public void setUserId(ObjectId userId) {
        this.userId = userId;
    }

    public Set<String> getHashtags() {
        return hashtags;
    }

    public void setHashtags(Set<String> hashtags) {
        this.hashtags = hashtags;
    }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zergatul.Cryptography;

namespace Zergatul.Network.Asn1
{
    public class ObjectIdentifier : Asn1Element
    {
        public OID OID { get; private set; }

        public ObjectIdentifier()
            : base(new Asn1Tag
            {
                Class = Asn1TagClass.Universal,
                ValueType = Asn1ValueType.Primitive,
                Number = Asn1TagNumber.OBJECT_IDENTIFIER
            })
        {

        }

        public ObjectIdentifier(OID oid)
            : this()
        {
            this.OID = oid;
        }

        protected override byte[] BodyToBytes()
        {
            var array = this.OID.DotNotation.Split('.').Select(p => int.Parse(p)).ToArray();
            if (array.Length < 2)
                throw new NotImplementedException();

            int first;
            switch (array[0])
            {
                case 0: first = array[1]; break;
                case 1: first = 40 + array[1]; break;
                case 2: first = 80 + array[1]; break;
                default: throw new InvalidOperationException();
            }

            using (var ms = new MemoryStream())
            {
                if (array.Length == 2)
                    first |= 0x80;
                ms.WriteByte((byte)first);
                for (int i = 2; i < array.Length; i++)
                {
                    int value = array[i];
                    byte[] parts = Enumerable.Range(0, 4).Reverse().Select(p => (byte)((value >> (7 * p)) & 0x7F)).SkipWhile(p => p == 0).ToArray();
                    for (int p = 0; p < parts.Length - 1; p++)
                        parts[p] |= 0x80;
                    ms.Write(parts, 0, parts.Length);
                }
                return ms.ToArray();
            }
        }

        protected override void ReadBody(Stream stream)
        {
            long totalRead = 0;
            ulong number = 0;
            bool first = true;
            var sb = new StringBuilder();

            while (totalRead < Length)
            {
                int readResult = stream.ReadByte();
                if (readResult == -1)
                    throw new EndOfStreamException();
                _raw.Add((byte)readResult);
                totalRead++;

                byte b = (byte)readResult;
                number += (byte)(b & 0x7F);
                if ((b & 0x80) == 0)
                {
                    if (first)
                    {
                        if (number < 40)
                            sb.Append('0');
                        else if (number < 80)
                        {
                            sb.Append('1');
                            number -= 40;
                        }
                        else
                        {
                            sb.Append('2');
                            number -= 80;
                        }
                        first = false;
                    }
                    sb.Append('.');
                    sb.Append(number);
                    number = 0;
                }
                else
                    checked
                    {
                        number *= 128;
                    }
            }

            string oidString = sb.ToString();
            var oid = OID.Find(oidString);
            if (oid != null)
                this.OID = oid;
            else
                this.OID = new OID(oidString);
        }
    }
}


text:
<?php

namespace Bolt\Events;

/**
 * Definitions for all possible StorageEvents.
 *
 *  * @codeCoverageIgnore
 */
final class StorageEvents
{
    private function __construct()
    {
    }

    // we make no distinction between insert/update
    const PRE_SAVE      = 'preSave';
    const POST_SAVE     = 'postSave';

    const PRE_INSERT    = 'preInsert';
    const POST_INSERT   = 'postInsert';

    const PRE_DELETE    = 'preDelete';
    const POST_DELETE   = 'postDelete';

    const PRE_HYDRATE   = 'preHydrate';
    const POST_HYDRATE  = 'postHydrate';
}


text:
package org.intellij.images.options;

import com.intellij.openapi.application.ApplicationManager;

/**
 * Options manager.
 *
 * @author Alexey Efimov
 */
public abstract class OptionsManager {
    /**
     * Return current options.
     *
     * @return Options
     */
    public abstract Options getOptions();

    public static OptionsManager getInstance() {
      return ApplicationManager.getApplication().getService(OptionsManager.class);
    }
}


text:
<TimeML
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../../dtd/timeml_1.2.1.xsd">

<DOCNO> WSJ891101-0048 </DOCNO>
<DD> = 891101 </DD>
<AN> 891101-0048. </AN>
<HL> Business Brief -- First Security Corp.:
@  Tentative Accord Formed
@  To Buy Deseret Bancorp. </HL>
<DD> 11/01/89 </DD>
<SO> WALL STREET JOURNAL (J) </SO>
<CO> FSCO </CO>
<IN> TENDER OFFERS, MERGERS, ACQUISITIONS (TNM) </IN>
<TEXT>
   First Security Corp. said it tentatively agreed  to acquire Deseret Bancorp. for stock valued at about $18 million.

   Terms call for First Security  to issue about 0.55 share of its stock for each Deseret share held, or a total of about 550,000 First Security shares.
It has about 12.3 million shares outstanding.

   Deseret, with about $100 million in assets, is the parent of the Deseret Bank, which has six offices and headquarters at Pleasant Grove, Utah.
The purchase price is equal to about 1.65 times Deseret's roughly $10.7 million book value, or assets less liabilities.

   Salt Lake City-based First Security, with $5.4 billion in assets, said the agreement is subject to shareholder and regulatory approval, and that it hopes  to complete the transaction early next year.
</TEXT>

</TimeML>


text:
题目描述

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
 Can you solve it without using extra space?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast){
                ListNode* slow2 = head;
                while(slow2 != slow){
                    slow = slow->next;
                    slow2 = slow2->next;
                }
                return slow2;
            }
        }
        return NULL;
    }
};


text:
<?php

/*
 * This file is part of the RollerworksDatagrid package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Datagrid\Tests;

use Rollerworks\Component\Datagrid\Column\ColumnInterface;
use Rollerworks\Component\Datagrid\Column\HeaderView;
use Rollerworks\Component\Datagrid\Column\ResolvedColumnTypeInterface;
use Rollerworks\Component\Datagrid\DatagridInterface;
use Rollerworks\Component\Datagrid\DatagridView;
use Rollerworks\Component\Datagrid\DataRowset;
use Rollerworks\Component\Datagrid\Tests\Fixtures\Entity;

class DatagridViewTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $rowset;

    /**
     * @var DatagridView
     */
    private $gridView;

    protected function setUp()
    {
        $type = $this->getMock(ResolvedColumnTypeInterface::class);
        $type->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('text'));

        $datagrid = $this->getMock(DatagridInterface::class);
        $column = $this->getMock(ColumnInterface::class);

        $column->expects($this->any())
            ->method('getType')
            ->will($this->returnValue($type));

        $this->rowset = new DataRowset([
            'e1' => new Entity('entity1'),
            'e2' => new Entity('entity2'),
        ]);

        $this->gridView = new DatagridView($datagrid, [$column], $this->rowset);

        $column = $this->getMock('Rollerworks\Component\Datagrid\Column\ColumnInterface');
        $column->expects($this->any())
            ->method('getType')
            ->will($this->returnValue($type));

        $columnHeader = new HeaderView($column, $this->gridView, 'foo');

        $column->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo'));

        $column->expects($this->any())
            ->method('getType')
            ->will($this->returnValue($type));

        $this->gridView->setColumns([$columnHeader]);
    }

    public function testHasColumn()
    {
        $this->assertTrue($this->gridView->hasColumn('foo'));
        $this->assertFalse($this->gridView->hasColumn('bar'));

        $this->assertInstanceOf('Rollerworks\Component\Datagrid\Column\HeaderView', $this->gridView->getColumn('foo'));
    }

    public function testGetColumn()
    {
        $this->assertInstanceOf('Rollerworks\Component\Datagrid\Column\HeaderView', $this->gridView->getColumn('foo'));

        $this->setExpectedException('Rollerworks\Component\Datagrid\Exception\InvalidArgumentException');
        $this->gridView->getColumn('bar');
    }

    public function testAddColumn()
    {
        $type = $this->getMock('Rollerworks\Component\Datagrid\Column\ResolvedColumnTypeInterface');
        $type->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('text'));

        $column = $this->getMock('Rollerworks\Component\Datagrid\Column\ColumnInterface');
        $column->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('bar'));

        $column->expects($this->any())
            ->method('getType')
            ->will($this->returnValue($type));

        $columnHeader = new HeaderView($column, $this->gridView, 'bar');
        $this->gridView->addColumn($columnHeader);

        $this->assertTrue($this->gridView->hasColumn('foo'));
        $this->assertTrue($this->gridView->hasColumn('bar'));
        $this->assertFalse($this->gridView->hasColumn('bla'));
    }

    public function testRemoveColumn()
    {
        $type = $this->getMock('Rollerworks\Component\Datagrid\Column\ResolvedColumnTypeInterface');
        $type->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('text'));

        $column = $this->getMock('Rollerworks\Component\Datagrid\Column\ColumnInterface');
        $column->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('bar'));

        $column->expects($this->any())
            ->method('getType')
            ->will($this->returnValue($type));

        $columnHeader = new HeaderView($column, $this->gridView, 'bar');
        $this->gridView->addColumn($columnHeader);

        $this->gridView->removeColumn('foo');

        $this->assertFalse($this->gridView->hasColumn('foo'));
        $this->assertTrue($this->gridView->hasColumn('bar'));
    }

    public function testClearColumns()
    {
        $type = $this->getMock('Rollerworks\Component\Datagrid\Column\ResolvedColumnTypeInterface');
        $type->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('text'));

        $column = $this->getMock('Rollerworks\Component\Datagrid\Column\ColumnInterface');
        $column->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('bar'));

        $column->expects($this->any())
            ->method('getType')
            ->will($this->returnValue($type));

        $columnHeader = new HeaderView($column, $this->gridView, 'bar');
        $this->gridView->addColumn($columnHeader);

        $this->gridView->clearColumns();

        $this->assertFalse($this->gridView->hasColumn('foo'));
        $this->assertFalse($this->gridView->hasColumn('bar'));
    }

    public function testGetCanGetVariablesWhenNoneWereSet()
    {
        $this->assertEquals([], $this->gridView->getVars());
        $this->assertNull($this->gridView->getVar('foo'));
        $this->assertEquals('bar', $this->gridView->getVar('foo', 'bar'));
    }

    public function testGetGetVariablesWhenSet()
    {
        $this->gridView->setVar('foo', 'bar');
        $this->gridView->setVar('name', 'test');
        $this->gridView->setVar('empty', null);

        $this->assertEquals(['foo' => 'bar', 'name' => 'test', 'empty' => null], $this->gridView->getVars());
        $this->assertEquals('bar', $this->gridView->getVar('foo'));
        $this->assertEquals('test', $this->gridView->getVar('name'));
        $this->assertEquals('test', $this->gridView->getVar('name'));
        $this->assertNull($this->gridView->getVar('bar'));

        // This ensures null values are checked properly.
        $this->assertNull($this->gridView->getVar('empty', 'overwrite'));
    }

    public function testCount()
    {
        $this->assertCount(2, $this->gridView);
    }
}


text:
<?php

App::uses('CarsAppModel', 'Cars.MakeModel');

/**
 * Cars
 *
 * @category FeatureType
 */
class FeatureType extends AppModel {

/**
 * FeatureType name
 *
 * @var string
 * @access public
 */
	public $name = 'FeatureType';
	public $useTable = 'car_feature_types';
	public $actsAs = array(
			'Search.Searchable'
	);
	public $filterArgs = array(
			'name' => array('type' => 'like', 'field' => array('FeatureType.name')),

	);

/**
 * Validation
 *
 * @var array
 * @access public
 */
	public $validate = array(
		'name' => array(
			'rule' => array('minLength', 2),
			'message' => 'Make name cannot be empty.',
		),

	);

	protected $_displayFields = array(
			'id',
			'name',
			'created',
			'status',
	);

public function typelist($id){
$conditions =array('status'=>1,'feature_type_id'=>$id);
return	$list = $this->find('list',array('conditions'=>$conditions));
}
}


text:
require "factory_bot_rails/generators/rspec_generator"
require "factory_bot_rails/generators/non_rspec_generator"
require "factory_bot_rails/generators/null_generator"

module FactoryBotRails
  class Generator
    def initialize(config)
      @generators = config.app_generators
    end

    def run
      generator.new(@generators).run
    end

    def generator
      return Generators::NullGenerator if factory_bot_disabled?

      if test_framework == :rspec
        Generators::RSpecGenerator
      else
        Generators::NonRSpecGenerator
      end
    end

    def test_framework
      rails_options[:test_framework]
    end

    def factory_bot_disabled?
      rails_options[:factory_bot] == false
    end

    def rails_options
      @generators.options[:rails]
    end
  end
end


text:
<?php

namespace Symfony\Component\EventDispatcher;

/**
 * EventInterface.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
interface EventInterface
{
    /**
     * Returns the subject.
     *
     * @return mixed The subject
     */
    function getSubject();

    /**
     * Returns the event name.
     *
     * @return string The event name
     */
    function getName();

    /**
     * Sets the processed flag to true.
     *
     * This method must be called by listeners when
     * it has processed the event (it is only meaningful
     * when the event has been notified with the notifyUntil()
     * dispatcher method.
     */
    function setProcessed();

    /**
     * Returns whether the event has been processed by a listener or not.
     *
     * This method is only meaningful for events notified
     * with notifyUntil().
     *
     * @return Boolean true if the event has been processed, false otherwise
     */
    function isProcessed();

    /**
     * Returns the event parameters.
     *
     * @return array The event parameters
     */
    function all();

    /**
     * Returns true if the parameter exists.
     *
     * @param  string  $name  The parameter name
     *
     * @return Boolean true if the parameter exists, false otherwise
     */
    function has($name);

    /**
     * Returns a parameter value.
     *
     * @param  string  $name  The parameter name
     *
     * @return mixed  The parameter value
     *
     * @throws \InvalidArgumentException When parameter doesn't exists for this event
     */
    function get($name);

    /**
     * Sets a parameter.
     *
     * @param string  $name   The parameter name
     * @param mixed   $value  The parameter value
     */
    function set($name, $value);
}


text:
<!DOCTYPE html>

<title>Server-Sent Events</title>
<meta charset="utf-8">
<meta http-equiv="Cache-Control" content="no-store" />
<link rel="stylesheet" href="styles/layout.css" type="text/css">

HTML5 Demonstration

Multimedia Technology Course 2014-2015

Home

About

HTML5 Server-Sent Events

A server-sent event is when a web page automatically gets updates from a server.

This was also possible before, but the web page would have to ask if any updates were
available. With server-sent events, the updates come automatically.

Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.

The EventSource object is used to receive server-sent event notifications:

var source = new EventSource("serverpage.php");
source.onmessage = function(event) {
    document.getElementById("result").innerHTML += event.data + "<br>";
};

Example explained:

Create a new EventSource object, and specify the URL of the page sending the updates

Each time an update is received, the onmessage event occurs

When an onmessage event occurs, put the received data into the element with id="result"

W3C Example

Base template by OS Templates, edited by M. Bogdanos


text:
选择支付方式

  {volist name="list" id="payment"}

      <input type="radio" name="payment_method" {if condition="$payment['code'] eq 'alipay' "} checked="checked"{/if} value="{$payment.code}" />

    {$payment.name}

 {/volist}

    <input type="button" value="继续" id="button-payment-method" class="btn btn-primary btn-continue" />


text:
package main

import "testing"

func TestNotYetImplementedMessageIsCorrect(t *testing.T) {
	expected := "Not yet implemented, sorry!"
	if NotYetImplementedMessage != expected {
		t.Fatalf("NotYetImplementedMessage has wrong text. Expected \"%s\" but was \"%s\".", expected, NotYetImplementedMessage)
	}
}


text:
package org.pageseeder.furi;

import java.util.Hashtable;
import java.util.Map;

/**
 * A variable resolver backed by a values mapped to objects.
 *
 * @author Christophe Lauret
 * @version 30 December 2008
 */
public class VariableResolverMap<V> implements VariableResolver {

  /**
   * The list of values.
   */
  private Map<String, ? extends V> _map;

  /**
   * Creates a new variable resolver.
   */
  public VariableResolverMap() {
    this._map = new Hashtable<String,V>();
  }

  /**
   * Creates a new variable resolver from the given map.
   *
   * @param map Variable values mapped to objects.
   */
  public VariableResolverMap(Map<String,? extends V> map) {
    this._map = map;
  }

  /**
   * {@inheritDoc}
   */
  public boolean exists(String value) {
    if (value == null)
      return false;
    return this._map.containsKey(value);
  }

  /**
   * {@inheritDoc}
   */
  public V resolve(String value) {
    return this._map.get(value);
  }

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE469_Use_of_Pointer_Subtraction_to_Determine_Size__char_07.c
Label Definition File: CWE469_Use_of_Pointer_Subtraction_to_Determine_Size.label.xml
Template File: point-flaw-07.tmpl.c
*/
/*
 * @description
 * CWE: 469 Use of Pointer Subtraction to Determine Size
 * Sinks:
 *    GoodSink: Subtract pointers within the same string
 *    BadSink : Subtract pointers to two different strings
 * Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5)
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#define SOURCE_STRING "abc/opqrstu"

/* The variable below is not declared "const", but is never assigned
   any other value so a tool should be able to identify that reads of
   this will always give its initialized value. */
static int staticFive = 5;

#ifndef OMITBAD

void CWE469_Use_of_Pointer_Subtraction_to_Determine_Size__char_07_bad()
{
    if(staticFive==5)
    {
        {
            char string1[] = SOURCE_STRING;
            char string2[] = SOURCE_STRING;
            char * slashInString1;
            size_t indexOfSlashInString1;
            slashInString1 = strchr(string1, '/');
            if (slashInString1 == NULL)
            {
                exit(1);
            }
            /* FLAW: subtracting the slash pointer from a completely different string, should be slashInString1 - string1 */
            indexOfSlashInString1 = (size_t)(slashInString1 - string2);
            /* print the index of where the slash was found */
            printUnsignedLine(indexOfSlashInString1);
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() uses if(staticFive!=5) instead of if(staticFive==5) */
static void good1()
{
    if(staticFive!=5)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        {
            char string1[] = SOURCE_STRING;
            char * slashInString1;
            size_t indexOfSlashInString1;
            slashInString1 = strchr(string1, '/');
            if (slashInString1 == NULL)
            {
                exit(1);
            }
            /* FIX: subtract the ending pointer from the actual string it originated from (string1) */
            indexOfSlashInString1 = (size_t)(slashInString1 - string1);
            /* print the index of where the slash was found */
            printUnsignedLine(indexOfSlashInString1);
        }
    }
}

/* good2() reverses the bodies in the if statement */
static void good2()
{
    if(staticFive==5)
    {
        {
            char string1[] = SOURCE_STRING;
            char * slashInString1;
            size_t indexOfSlashInString1;
            slashInString1 = strchr(string1, '/');
            if (slashInString1 == NULL)
            {
                exit(1);
            }
            /* FIX: subtract the ending pointer from the actual string it originated from (string1) */
            indexOfSlashInString1 = (size_t)(slashInString1 - string1);
            /* print the index of where the slash was found */
            printUnsignedLine(indexOfSlashInString1);
        }
    }
}

void CWE469_Use_of_Pointer_Subtraction_to_Determine_Size__char_07_good()
{
    good1();
    good2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE469_Use_of_Pointer_Subtraction_to_Determine_Size__char_07_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE469_Use_of_Pointer_Subtraction_to_Determine_Size__char_07_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
import json
import collections

Edge = collections.namedtuple("Edge",["source","dest","type"])

class GraphHelper( object ):
    def __init__(self):
        self.counters = collections.defaultdict(lambda: 0)
        self.nodes = set()
        self.edges = set()

    def dumps(self):
        return json.dumps({
            "nodes": sorted(self.nodes),
            "edges": [{"from":e.source,"to":e.dest,"type":e.type} for e in self.edges]
        })

    def make(self, node_type):
        full_name = node_type + "#" + str(self.counters[node_type])
        self.counters[node_type] += 1
        self.nodes.add(full_name)
        return Node(full_name, self)

    def make_unique(self, node_name):
        if not node_name in self.nodes:
            self.nodes.add(node_name)
        return Node(node_name, self)

class BadEdgeError( Exception ):
    pass

class Node( object ):
    def __init__(self, identifier, parent):
        object.__setattr__(self, 'identifier', identifier)
        object.__setattr__(self, 'parent', parent)

    def __getattr__(self, edgename):
        matching = set(e.dest for e in self.parent.edges
                        if e.source == self.identifier
                           and e.type == edgename)
        if len(matching) == 0:
            return None
        elif len(matching) > 1:
            raise BadEdgeError("Expected one result for {}.{}, got {}".format(self.identifier, edgename, matching))
        return Node(matching.pop(), self.parent)

    def __getitem__(self, edgename):
        return self.__getattr__(edgename)

    def __setattr__(self, edgename, value):
        if edgename in ["identifier","parent"]:
            self.__setattribute__(edgename, value)
            return
        matching = set(e for e in self.parent.edges
                        if e.source == self.identifier
                           and e.type == edgename)
        if len(matching) > 1:
            print("WARNING: Setting attr {} on {} clears old values, but has multiple edges {}".format(edgename,self.identifier,matching))
        self.parent.edges -= matching
        if value is not None:
            self.parent.edges.add(Edge(self.identifier, value.identifier, edgename))

    def __setitem__(self, edgename, value):
        return self.__setattr__(edgename, value)

    def getall(self, edgename):
        matching = frozenset(e.dest for e in self.parent.edges
                        if e.source == self.identifier
                           and e.type == edgename)
        return matching

    def add(self, edgename, dest):
        self.parent.edges.add(Edge(self.identifier, dest.identifier, edgename))

    def remove(self, edgename=None, dest=None):
        matching = set(e for e in self.parent.edges
                        if e.source == self.identifier
                           and (e.dest == dest.identifier or dest is None)
                           and (e.type == edgename or edgename is None))
        self.parent.edges -= matching

    @property
    def type(self):
        return self.identifier.split("#")[0]

class Story( object ):
    def __init__(self):
        self.graph = GraphHelper()
        self.counter = 1
        self.lines = []

    def add_line(self, line_str):
        assert not "=" in line_str
        assert not "\t" in line_str
        self.lines.append("{} {}={}".format(self.counter, line_str, self.graph.dumps()))
        self.counter += 1

    def no_query(self):
        self.add_query("","")

    def add_query(self, query, answer):
        assert not "=" in query + answer
        assert not "\t" in query + answer
        self.lines.append("{} {}\t{}".format(self.counter, query, answer))
        self.counter += 1


text:
package com.siyeh.ig.threading;

import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.testFramework.IdeaTestUtil;
import com.siyeh.ig.IGInspectionTestCase;

public class SynchronizationOnLocalVariableOrMethodParameterInspectionTest extends IGInspectionTestCase {

  @Override
  protected Sdk getTestProjectSdk() {
    LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_8);
    return IdeaTestUtil.getMockJdk17();
  }

  public void test() throws Exception {
    doTest("com/siyeh/igtest/threading/synchronization_on_local_variable_or_method_parameter",
           new SynchronizationOnLocalVariableOrMethodParameterInspection());
  }
}


text:
import time
import lib.stm32
import lib.stlinkex

# Stm32 L0 and L1 programming
class Flash():
    PECR_OFFSET       =    4
    PEKEYR_OFFSET     = 0x0c
    PRGKEYR_OFFSET    = 0x10
    OPTKEYR_OFFSET    = 0x14
    SR_OFFSET         = 0x18
    STM32L0_NVM_PHY   = 0x40022000
    STM32L1_NVM_PHY   = 0x40023c00
    STM32_NVM_PEKEY1  = 0x89abcdef
    STM32_NVM_PEKEY2  = 0x02030405
    STM32_NVM_PRGKEY1 = 0x8c9daebf
    STM32_NVM_PRGKEY2 = 0x13141516

    PECR_PELOCK      = 1 <<  0
    PECR_PRGLOCK     = 1 <<  1
    PECR_PRG         = 1 <<  3
    PECR_ERASE       = 1 <<  9
    PECR_FPRG        = 1 << 10

    SR_BSY           = 1 <<  0
    SR_EOP           = 1 <<  1
    SR_WRPERR        = 1 <<  8
    SR_PGAERR        = 1 <<  9
    SR_SIZERR        = 1 << 10

    SR_ERROR_MASK = SR_WRPERR | SR_PGAERR | SR_SIZERR

    def __init__(self, driver, stlink, dbg):
        self._driver = driver
        self._stlink = stlink
        self._dbg = dbg
        self._page_size = 2048
        #use core id to find out if L0 or L1
        if  stlink._coreid == 0xbc11477:
            self._nvm = Flash.STM32L0_NVM_PHY
            self._page_size = 128
        else:
            self._nvm = Flash.STM32L1_NVM_PHY
            self._page_size = 256
        self.unlock()

    def clear_sr(self):
        # clear errors
        sr = self._stlink.get_debugreg32(self._nvm + Flash.SR_OFFSET)
        self._stlink.set_debugreg32(self._nvm + Flash.SR_OFFSET, sr)

    def unlock(self):
        self._dbg.debug('unlock')
        self._driver.core_reset_halt()
        self.wait_busy(0.01)
        self.clear_sr()
        # Lock first. Double unlock results in error!
        self._stlink.set_debugreg32(self._nvm + Flash.PECR_OFFSET,
                                    Flash.PECR_PELOCK)
        pecr = self._stlink.get_debugreg32(self._nvm + Flash.PECR_OFFSET)
        if pecr & Flash.PECR_PELOCK:
            # unlock keys
            self._stlink.set_debugreg32(self._nvm + Flash.PEKEYR_OFFSET,
                                        Flash.STM32_NVM_PEKEY1)
            self._stlink.set_debugreg32(self._nvm + Flash.PEKEYR_OFFSET,
                                        Flash.STM32_NVM_PEKEY2)
            pecr = self._stlink.get_debugreg32(self._nvm + Flash.PECR_OFFSET)
        else :
            raise lib.stlinkex.StlinkException(
                'Unexpected unlock behaviour! FLASH_CR 0x%08x' % pecr)
        # check if programing was unlocked
        if pecr & Flash.PECR_PELOCK:
            raise lib.stlinkex.StlinkException(
                'Error unlocking FLASH_CR: 0x%08x. Reset!' % prcr)

    def lock(self):
        self._stlink.set_debugreg32(self._nvm + Flash.PECR_OFFSET,
                                    Flash.PECR_PELOCK)
        self._driver.core_reset_halt()

    def prg_unlock(self):
        pecr = self._stlink.get_debugreg32(self._nvm + Flash.PECR_OFFSET)
        if not pecr & Flash.PECR_PRGLOCK:
            return
        if pecr & Flash.PECR_PELOCK:
            raise lib.stlinkex.StlinkException('PELOCK still set: %08x' % pecr)
        # unlock keys
        self._stlink.set_debugreg32(self._nvm + Flash.PRGKEYR_OFFSET,
                                    Flash.STM32_NVM_PRGKEY1)
        self._stlink.set_debugreg32(self._nvm + Flash.PRGKEYR_OFFSET,
                                    Flash.STM32_NVM_PRGKEY2)
        pecr = self._stlink.get_debugreg32(self._nvm + Flash.PECR_OFFSET)
        if pecr & Flash.PECR_PRGLOCK:
            raise lib.stlinkex.StlinkException('PRGLOCK still set: %08x' % pecr)

    def erase_pages(self, addr, size):
        self._dbg.verbose('erase_pages from addr 0x%08x for %d byte' %
                          (addr, size))
        erase_addr =   addr         & ~(self._page_size - 1)
        last_addr  =  (addr + size + self._page_size - 1) &\
                      ~(self._page_size - 1)
        self._dbg.bargraph_start('Erasing FLASH', value_min=erase_addr,
                                 value_max=last_addr)
        self.prg_unlock()
        pecr = Flash.PECR_PRG | Flash.PECR_ERASE
        self._stlink.set_debugreg32(self._nvm + Flash.PECR_OFFSET, pecr)
        while erase_addr < last_addr:
            self._stlink.set_debugreg32(erase_addr, 0)
            self.wait_busy(0.01)
            erase_addr += self._page_size
            self._dbg.bargraph_update(value=erase_addr)
        self._dbg.bargraph_done()
        self._stlink.set_debugreg32(self._nvm + Flash.PECR_OFFSET, 0)

    def wait_busy(self, wait_time, bargraph_msg=None, check_eop=False):
        end_time = time.time() + wait_time * 1.5
        if bargraph_msg:
            self._dbg.bargraph_start(bargraph_msg, value_min=time.time(),
                                     value_max=time.time() + wait_time)
        while time.time() < end_time:
            if bargraph_msg:
                self._dbg.bargraph_update(value=time.time())
            status = self._stlink.get_debugreg32(self._nvm + Flash.SR_OFFSET)
            if not status & (Flash.SR_BSY | (check_eop & Flash.SR_EOP)) :
                self.end_of_operation(status)
                if bargraph_msg:
                    self._dbg.bargraph_done()
                if check_eop:
                    self._stlink.set_debugreg32(self._nvm + Flash.SR_OFFSET,
                                                 Flash.SR_EOP)
                return
            time.sleep(wait_time / 20)
        raise lib.stlinkex.StlinkException('Operation timeout')

    def end_of_operation(self, status):
        if status & Flash.SR_ERROR_MASK:
            raise lib.stlinkex.StlinkException(
                'Error writing FLASH with status (FLASH_SR) %08x' % status)

class Stm32L0(lib.stm32.Stm32):
    def flash_erase_all(self, flash_size):
        # Mass erase is only possible by setting and removing flash
        # write protection. This will also erase EEPROM!
        # Use page erase instead

        self._dbg.debug('Stm32L0.flash_erase_all')
        flash = Flash(self, self._stlink, self._dbg)
        flash.erase_pages(lib.stm32.Stm32.FLASH_START, flash_size);
        flash.lock()

    def flash_write(self, addr, data, erase=False, erase_sizes=None):
        if addr is None:
            addr = self.FLASH_START
        self._dbg.debug(
            'Stm32l4.flash_write '
            '(%s, [data:%dBytes], erase=%s, erase_sizes=%s)'
            % (addr, len(data), erase, erase_sizes))
        if addr % 4:
            raise lib.stlinkex.StlinkException
        ('Start address is not aligned to word')
        flash = Flash(self, self._stlink, self._dbg)
        if erase:
            if erase_sizes:
                flash.erase_pages(addr, len(data))
            else:
                flash.erase_all()
        self._dbg.bargraph_start('Writing FLASH', value_min=addr,
                                 value_max=addr + len(data))
        flash.unlock()
        flash.prg_unlock()
        datablock = data
        data_addr = addr
        block = datablock
        while len(datablock):
            size = 0
            if data_addr & ((flash._page_size >> 1) -1):
                # not half page aligned
                size = data_addr & ((flash._page_size >> 1) -1)
                size = (flash._page_size >> 1) - size
            if len(datablock) < (flash._page_size >> 1):
                # remainder not full half page
                size = len(datablock)
            while size:
                block = datablock[:4]
                datablock = datablock[4:]
                if max(block) != 0:
                    self._stlink.set_mem32(data_addr, block)
                data_addr += 4
                size -= 4
                self._dbg.bargraph_update(value=data_addr)
                flash.wait_busy(0.005, check_eop=True)
            pecr = Flash.PECR_FPRG | Flash.PECR_PRG
            self._stlink.set_debugreg32(flash._nvm + Flash.PECR_OFFSET, pecr)
            while len(datablock) >= (flash._page_size >> 1):
                block = datablock[:(flash._page_size >> 1)]
                datablock = datablock[(flash._page_size >> 1):]
                if max(block) != 0:
                    self._stlink.set_mem32(data_addr, block)
                data_addr += len(block)
                self._dbg.bargraph_update(value=data_addr)
                flash.wait_busy(0.005, check_eop=True)
            self._stlink.set_debugreg32(flash._nvm + Flash.PECR_OFFSET, 0)
        flash.lock()
        self._dbg.bargraph_done()


text:
For production apps we use sw-precache

https://github.com/GoogleChrome/sw-precache/blob/3.1.0/GettingStarted.md

Give these commands in sequence:

npm install

gulp

npm start


text:
export default () => "standard";
export let foo = () => "standard";


text:
<?php

namespace Umc\Base\Downloader;

class Module implements DownloaderInterface
{
    /**
     * get relative path to the file
     *
     * @param string $file
     * @return string
     */
    public function getRelativePath($file)
    {
        return $file. '.tar.gz';
    }

    /**
     * @return \Magento\Framework\Phrase
     */
    public function getLabel()
    {
        return __('Download Module Archive');
    }

    /**
     * @return \Magento\Framework\Phrase
     */
    public function getErrorLabel()
    {
        return __('Module archive is not available');
    }
}


text:
const path = require('path');
const merge = require('webpack-merge');
const defaultWebpackConfig = require('terra-dev-site/config/webpack/webpack.config');

const coreConfig = () => {
  const processPath = process.cwd();
  const rootPath = processPath.includes('packages') ? processPath.split('packages')[0] : processPath;

  const i18nAlias = path.resolve(path.join(rootPath, 'packages', 'terra-i18n'));
  return {
    resolve: {
      alias: {
        'terra-i18n': i18nAlias,
      },
    },
  };
};

const mergedConfig = (env, argv) => (
  merge(defaultWebpackConfig(env, argv), coreConfig())
);

module.exports = mergedConfig;


text:
#ifndef SOFT_FLAC_ENC_H_

#define SOFT_FLAC_ENC_H_

#include <media/stagefright/omx/SimpleSoftOMXComponent.h>

#include "FLAC/stream_encoder.h"

namespace android {

struct SoftFlacEncoder : public SimpleSoftOMXComponent {
    SoftFlacEncoder(const char *name,
            const OMX_CALLBACKTYPE *callbacks,
            OMX_PTR appData,
            OMX_COMPONENTTYPE **component);

    virtual OMX_ERRORTYPE initCheck() const;

protected:
    virtual ~SoftFlacEncoder();

    virtual OMX_ERRORTYPE internalGetParameter(
            OMX_INDEXTYPE index, OMX_PTR params);

    virtual OMX_ERRORTYPE internalSetParameter(
            OMX_INDEXTYPE index, const OMX_PTR params);

    virtual void onQueueFilled(OMX_U32 portIndex);

private:
    const unsigned int kNumBuffers = 2;
    const unsigned int kMaxNumSamplesPerFrame = 1152;
    const unsigned int kMaxInputBufferSize = kMaxNumSamplesPerFrame * sizeof(int16_t) * 2;
    const unsigned int kMaxOutputBufferSize = 65536;    //TODO check if this can be reduced

    bool mSignalledError;

    OMX_U32 mNumChannels;
    OMX_U32 mSampleRate;
    OMX_U32 mCompressionLevel;

    // should the data received by the callback be written to the output port
    bool        mEncoderWriteData;
    bool        mEncoderReturnedEncodedData;
    bool        mSawInputEOS;
    bool        mSentOutputEOS;
    size_t      mEncoderReturnedNbBytes;
    OMX_TICKS  mCurrentInputTimeStamp;

    FLAC__StreamEncoder* mFlacStreamEncoder;

    void initPorts();

    OMX_ERRORTYPE configureEncoder();

    // FLAC encoder callbacks
    // maps to encoderEncodeFlac()
    static FLAC__StreamEncoderWriteStatus flacEncoderWriteCallback(
            const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[],
            size_t bytes, unsigned samples, unsigned current_frame, void *client_data);

    FLAC__StreamEncoderWriteStatus onEncodedFlacAvailable(
                const FLAC__byte buffer[],
                size_t bytes, unsigned samples, unsigned current_frame);

    // FLAC takes samples aligned on 32bit boundaries, use this buffer for the conversion
    // before passing the input data to the encoder
    FLAC__int32* mInputBufferPcm32;

    unsigned mHeaderOffset;
    bool mHeaderComplete;
    bool mWroteHeader;
    char mHeader[128];

    DISALLOW_EVIL_CONSTRUCTORS(SoftFlacEncoder);
};

}  // namespace android

#endif  // SOFT_FLAC_ENC_H_


text:
class NumArray {
    int N;
    vector<int> seg_tree;

    // node is the node index in the tree
    // lo/hi are bounds of the subarray
    // index, val corresponds to the array element to update
    int updateInternal(int node, int lo, int hi, int index, int val) {
        if (lo == hi) {
            int prev_val = seg_tree[node];
            seg_tree[node] = val;
            return val-prev_val;  // returns delta, so upstream can modify it
        }

        int mid = (lo+hi)/2;
        int delta=0;
        if (index <= mid) {
            delta = updateInternal(2*node+1, lo,    mid, index, val);
        } else {
            delta = updateInternal(2*node+2, mid+1, hi,  index, val);
        }
        seg_tree[node] += delta;
        return delta;
    }

    // lo/hi is what the current node covers
    // query_lo/query_hi is the query range
    int sumInternal(int node, int lo, int hi, int query_lo, int query_hi) {
        if (lo > query_hi) return 0;
        if (hi < query_lo) return 0;
        if (query_lo <= lo && query_hi >= hi) {
            // query range encompasses me entirely
            return seg_tree[node];
        }
        int mid=(lo+hi)/2;
        int lhs = sumInternal(2*node+1, lo, mid, query_lo, query_hi);
        int rhs = sumInternal(2*node+2, mid+1, hi, query_lo, query_hi);
        return lhs+rhs;
    }

public:
    NumArray(vector<int>& nums) {
        N = nums.size();
        seg_tree = vector<int>(4*N, 0);

        for (int i=0; i<nums.size(); i++) {
            update(i, nums[i]);
        }
    }

    // O(log n) time, O(n) space.
    void update(int index, int val) {
        if (index >= N) return;
        updateInternal(0, 0, N-1, index, val);
    }

    // O(log n) time, O(n) space.
    int sumRange(int left, int right) {
        return sumInternal(0, 0, N-1, left, right);
    }
};

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray* obj = new NumArray(nums);
 * obj->update(index,val);
 * int param_2 = obj->sumRange(left,right);
 */


text:
'use strict'

module.exports = function (grunt) {
  require('load-grunt-config')(grunt)
}


text:
# Provision an Apache Spark 2.0 Cluster on Suse Linux Enterprise Server R12 SP1

In Memory Cluster Computing to solve query optimization, slow Machine Learning and many other BI problems

To master this template and Spark 2.0 on SLES you can leverage hands on workshop from [Value Amplify](http://www.valueamplify.com)

### To deploy this sample using a script in the root of this repo

```PowerShell
.\Deploy-AzureResourceGroup.ps1 -ResourceGroupLocation 'eastus' -ArtifactsStagingDirectory 'spark-2.0-on-suse' -UploadArtifacts
```
```bash
azure-group-deploy.sh -a 'spark-2.0-on-suse' -l eastus -u
```
This template deploys a **spark-2.0-on-suse** infrastructure. The **spark-2.0-on-suse** template is a Spark 2.0 environment based on Spark Standalone Cluster Manager; the template setup one master node and N worker nodes installing and configuring Spark 2.0.
Details about installation are available on all the nodes under /tmp/ director

## Solution overview and deployed resources

This template deploys a **spark-2.0-on-suse** infrastructure. The **spark-2.0-on-suse** is a Spark 2.0 environment based on Spark Standalone Cluster Manager; the template setup 1 master node and N worker nodes installing and configuring spark.
Spark Master is accessible using a dedicated public IP (resource **sparkMasterPublicIP**): from here you can connect via **spark-shell** or **spark-submit**
Details about installation are available on all the nodes under /tmp/ directory.

The following resources are deployed as part of the solution

#### Virtual network

The internal network that delimits the cluster environment

#### Storage Account

The storage account associated to the cluster for, automatically referenced on Spark using **wasb://** address

#### Virtual Machine

VMs will be used as spark master or N-th worker on the cluster

+ **sparkmaster**: The master node from the cluster
+ **sparkslave[i]**: the i-th worker node of the cluster

#### Network Interface Card

+ **ni_master/nislave[i]**: master and worker network interfaces

#### Public IP

+ **sparkMasterPublicIP**: the public IP of the master node

#### Custom Script Example

+ **configuresparkonmaster/slave[i]**: The bash script that will install and configure the Spark 2.0 cluster

#### Network Security group

+ **ns_spark**: The network security group for the Spark Cluster

## Usage

#### Connect

Connect with ssh to your master node using username and password provided at deploy time
```bash
ssh yourusername@YOUR_MASTER_PUBLIC_IP
```

#### Management

You can see how application are executed consulting Spark Web UI at **http://YOUR_MASTER_PUBLIC_IP:8080**

If running application on sparkmaster you can reach Spark Application UI at **http://YOUR_MASTER_PUBLIC_IP:4040**

## Notes

Spark 2.0 logs are provided under **/srv/spark/logs** directory


text:
using System;
using System.Collections.Generic;

namespace Pliant.Collections
{
    public class AvlTree<T>
        where T : IComparable<T>
    {
        private class AvlNode
        {
            public T Key { get; private set; }

            public int Height { get; set; }

            public AvlNode Left { get; set; }

            public AvlNode Right { get; set; }

            public AvlNode(T key)
            {
                Key = key;
                Height = 1;
            }
        }

        private AvlNode _root;

        public void Insert(T key)
        {
            _root = Insert(_root, key);
        }

        private AvlNode Insert(AvlNode node, T key)
        {
            var isLeaf = node == null;
            if (isLeaf)
                return new AvlNode(key);

            // do a binary search tree insertion recursively
            if (key.CompareTo(node.Key) < 0)
                node.Left = Insert(node.Left, key);
            else
                node.Right = Insert(node.Right, key);

            // update height
            node.Height = Math.Max(
                Height(node.Left),
                Height(node.Right)) + 1;

            // at each level of recursion, check if the tree is unbalanced
            var balanceFactor = GetBalanceFactor(node);

            if (-1 <= balanceFactor && balanceFactor <= 1)
                return node;

            // Left Left
            if (balanceFactor > 1 && key.CompareTo(node.Left.Key) < 0)
                return RotateRight(node);

            // Right Right
            if (balanceFactor < -1 && key.CompareTo(node.Right.Key) > 0)
                return RotateLeft(node);

            // Left Right
            if (balanceFactor > 1 && key.CompareTo(node.Left.Key) > 0)
            {
                node.Left = RotateLeft(node.Left);
                return RotateRight(node);
            }

            // Right Left
            if (balanceFactor < -1 && key.CompareTo(node.Right.Key) < 0)
            {
                node.Right = RotateRight(node.Right);
                return RotateLeft(node);
            }

            return node;
        }

        private static AvlNode RotateLeft(AvlNode x)
        {
            var y = x.Right;
            var temp = y.Left;

            // rotation
            y.Left = x;
            x.Right = temp;

            // update height
            x.Height = Math.Max(Height(x.Left), Height(x.Right)) + 1;
            y.Height = Math.Max(Height(y.Left), Height(y.Right)) + 1;

            // new root
            return y;
        }

        private static AvlNode RotateRight(AvlNode y)
        {
            var x = y.Left;
            var temp = x.Right;

            // rotation
            x.Right = y;
            y.Left = temp;

            // update height
            y.Height = Math.Max(Height(y.Left), Height(y.Right)) + 1;
            x.Height = Math.Max(Height(x.Left), Height(x.Right)) + 1;

            // new root
            return x;
        }

        private static int Height(AvlNode node)
        {
            if (node == null)
                return 0;
            return node.Height;
        }

        private static int GetBalanceFactor(AvlNode node)
        {
            if (node == null)
                return 0;
            return Height(node.Left) - Height(node.Right);
        }

        public IEnumerator<T> GetEnumerator()
        {
            return GetEnumerator(_root);
        }

        private IEnumerator<T> GetEnumerator(AvlNode node)
        {
            if (node == null)
                yield break;

            var leftTree = GetEnumerator(node.Left);
            while (leftTree.MoveNext())
                yield return leftTree.Current;

            yield return node.Key;

            var rightTree = GetEnumerator(node.Right);
            while (rightTree.MoveNext())
                yield return rightTree.Current;
        }
    }
}


text:
"""Utils for dataset creation.

Creative Applications of Deep Learning w/ Tensorflow.
Kadenze, Inc.
Copyright Parag K. Mital, June 2016.
"""

import os
import pickle
import numpy as np
import tensorflow as tf
from . import dft

def create_input_pipeline(files, batch_size, n_epochs, shape, crop_shape=None,
                          crop_factor=1.0, n_threads=4):
    """Creates a pipefile from a list of image files.
    Includes batch generator/central crop/resizing options.
    The resulting generator will dequeue the images batch_size at a time until
    it throws tf.errors.OutOfRangeError when there are no more images left in
    the queue.

    Parameters
    ----------
    files : list
        List of paths to image files.
    batch_size : int
        Number of image files to load at a time.
    n_epochs : int
        Number of epochs to run before raising tf.errors.OutOfRangeError
    shape : list
        [height, width, channels]
    crop_shape : list
        [height, width] to crop image to.
    crop_factor : float
        Percentage of image to take starting from center.
    n_threads : int, optional
        Number of threads to use for batch shuffling
    """

    # We first create a "producer" queue.  It creates a production line which
    # will queue up the file names and allow another queue to deque the file
    # names all using a tf queue runner.
    # Put simply, this is the entry point of the computational graph.
    # It will generate the list of file names.
    # We also specify it's capacity beforehand.
    producer = tf.train.string_input_producer(
        files, capacity=len(files))

    # We need something which can open the files and read its contents.
    reader = tf.WholeFileReader()

    # We pass the filenames to this object which can read the file's contents.
    # This will create another queue running which dequeues the previous queue.
    keys, vals = reader.read(producer)

    # And then have to decode its contents as we know it is a jpeg image
    imgs = tf.image.decode_jpeg(
        vals,
        channels=3 if len(shape) > 2 and shape[2] == 3 else 0)

    # We have to explicitly define the shape of the tensor.
    # This is because the decode_jpeg operation is still a node in the graph
    # and doesn't yet know the shape of the image.  Future operations however
    # need explicit knowledge of the image's shape in order to be created.
    imgs.set_shape(shape)

    # Next we'll centrally crop the image to the size of 100x100.
    # This operation required explicit knowledge of the image's shape.
    if shape[0] > shape[1]:
        rsz_shape = [int(shape[0] / shape[1] * crop_shape[0] / crop_factor),
                     int(crop_shape[1] / crop_factor)]
    else:
        rsz_shape = [int(crop_shape[0] / crop_factor),
                     int(shape[1] / shape[0] * crop_shape[1] / crop_factor)]
    rszs = tf.image.resize_images(imgs, rsz_shape[0], rsz_shape[1])
    crops = (tf.image.resize_image_with_crop_or_pad(
        rszs, crop_shape[0], crop_shape[1])
        if crop_shape is not None
        else imgs)

    # Now we'll create a batch generator that will also shuffle our examples.
    # We tell it how many it should have in its buffer when it randomly
    # permutes the order.
    min_after_dequeue = len(files) // 10

    # The capacity should be larger than min_after_dequeue, and determines how
    # many examples are prefetched.  TF docs recommend setting this value to:
    # min_after_dequeue + (num_threads + a small safety margin) * batch_size
    capacity = min_after_dequeue + (n_threads + 1) * batch_size

    # Randomize the order and output batches of batch_size.
    batch = tf.train.shuffle_batch([crops],
                                   enqueue_many=False,
                                   batch_size=batch_size,
                                   capacity=capacity,
                                   min_after_dequeue=min_after_dequeue,
                                   num_threads=n_threads)

    # alternatively, we could use shuffle_batch_join to use multiple reader
    # instances, or set shuffle_batch's n_threads to higher than 1.

    return batch

def download_and_extract_tar(path, dst):
    """Download and extract a tar file.

    Parameters
    ----------
    path : str
        Url to tar file to download.
    dst : str
        Location to save tar file contents.
    """
    import tarfile
    filepath = download(path)
    if not os.path.exists(dst):
        os.makedirs(dst)
    tarfile.open(filepath, 'r:gz').extractall(dst)

def download(path):
    """Use urllib to download a file.

    Parameters
    ----------
    path : str
        Url to download

    Returns
    -------
    path : str
        Location of downloaded file.
    """
    from six.moves import urllib
    from IPython.core.display import clear_output

    print('Downloading ' + path)

    def progress(count, block_size, total_size):
        print('Downloaded %02.02f/%02.02f MB' % (
            count * block_size / 1024.0 / 1024.0,
            total_size / 1024.0 / 1024.0))
        clear_output(wait=True)

    filepath, _ = urllib.request.urlretrieve(path, reporthook=progress)
    return filepath

def gtzan_music_speech_download(dst='gtzan_music_speech'):
    """Download the GTZAN music and speech dataset.

    Parameters
    ----------
    dst : str, optional
        Location to put the GTZAN music and speech datset.
    """
    path = 'http://opihi.cs.uvic.ca/sound/music_speech.tar.gz'
    download_and_extract_tar(path, dst)

def gtzan_music_speech_load(dst='gtzan_music_speech'):
    """Load the GTZAN Music and Speech dataset.

    Downloads the dataset if it does not exist into the dst directory.

    Parameters
    ----------
    dst : str, optional
        Location of GTZAN Music and Speech dataset.

    Returns
    -------
    Xs, ys : np.ndarray, np.ndarray
        Array of data, Array of labels
    """
    from scipy.io import wavfile

    if not os.path.exists(dst):
        gtzan_music_speech_download(dst)
    music_dir = os.path.join(os.path.join(dst, 'music_speech'), 'music_wav')
    music = [os.path.join(music_dir, file_i)
             for file_i in os.listdir(music_dir)
             if file_i.endswith('.wav')]
    speech_dir = os.path.join(os.path.join(dst, 'music_speech'), 'speech_wav')
    speech = [os.path.join(speech_dir, file_i)
              for file_i in os.listdir(speech_dir)
              if file_i.endswith('.wav')]
    Xs = []
    ys = []
    for i in music:
        sr, s = wavfile.read(i)
        s = s / 16384.0 - 1.0
        re, im = dft.dft_np(s)
        mag, phs = dft.ztoc(re, im)
        Xs.append((mag, phs))
        ys.append(0)
    for i in speech:
        sr, s = wavfile.read(i)
        s = s / 16384.0 - 1.0
        re, im = dft.dft_np(s)
        mag, phs = dft.ztoc(re, im)
        Xs.append((mag, phs))
        ys.append(1)
    Xs = np.array(Xs)
    Xs = np.transpose(Xs, [0, 2, 3, 1])
    ys = np.array(ys)
    return Xs, ys

def cifar10_download(dst='cifar10'):
    """Download the CIFAR10 dataset.

    Parameters
    ----------
    dst : str, optional
        Directory to download into.
    """
    path = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
    download_and_extract_tar(path, dst)

def cifar10_load(dst='cifar10'):
    """Load the CIFAR10 dataset.

    Downloads the dataset if it does not exist into the dst directory.

    Parameters
    ----------
    dst : str, optional
        Location of CIFAR10 dataset.

    Returns
    -------
    Xs, ys : np.ndarray, np.ndarray
        Array of data, Array of labels
    """
    if not os.path.exists(dst):
        cifar10_download(dst)
    Xs = None
    ys = None
    for f in range(1, 6):
        cf = pickle.load(open(
            '%s/cifar-10-batches-py/data_batch_%d' % (dst, f), 'rb'),
            encoding='LATIN')
        if Xs is not None:
            Xs = np.r_[Xs, cf['data']]
            ys = np.r_[ys, np.array(cf['labels'])]
        else:
            Xs = cf['data']
            ys = cf['labels']
    Xs = np.swapaxes(np.swapaxes(Xs.reshape(-1, 3, 32, 32), 1, 3), 1, 2)
    return Xs, ys

def dense_to_one_hot(labels, n_classes=2):
    """Convert class labels from scalars to one-hot vectors.

    Parameters
    ----------
    labels : array
        Input labels to convert to one-hot representation.
    n_classes : int, optional
        Number of possible one-hot.

    Returns
    -------
    one_hot : array
        One hot representation of input.
    """
    return np.eye(n_classes).astype(np.float32)[labels]

class DatasetSplit(object):
    """Utility class for batching data and handling multiple splits.

    Attributes
    ----------
    current_batch_idx : int
        Description
    images : np.ndarray
        Xs of the dataset.  Not necessarily images.
    labels : np.ndarray
        ys of the dataset.
    n_labels : int
        Number of possible labels
    num_examples : int
        Number of total observations
    """

    def __init__(self, images, labels):
        """Initialize a DatasetSplit object.

        Parameters
        ----------
        images : np.ndarray
            Xs/inputs
        labels : np.ndarray
            ys/outputs
        """
        self.images = np.array(images).astype(np.float32)
        if labels is not None:
            self.labels = np.array(labels).astype(np.int32)
            self.n_labels = len(np.unique(labels))
        else:
            self.labels = None
        self.num_examples = len(self.images)

    def next_batch(self, batch_size=100):
        """Batch generator with randomization.

        Parameters
        ----------
        batch_size : int, optional
            Size of each minibatch.

        Returns
        -------
        Xs, ys : np.ndarray, np.ndarray
            Next batch of inputs and labels (if no labels, then None).
        """
        # Shuffle each epoch
        current_permutation = np.random.permutation(range(len(self.images)))
        epoch_images = self.images[current_permutation, ...]
        if self.labels is not None:
            epoch_labels = self.labels[current_permutation, ...]

        # Then iterate over the epoch
        self.current_batch_idx = 0
        while self.current_batch_idx < len(self.images):
            end_idx = min(
                self.current_batch_idx + batch_size, len(self.images))
            this_batch = {
                'images': epoch_images[self.current_batch_idx:end_idx],
                'labels': epoch_labels[self.current_batch_idx:end_idx]
                if self.labels is not None else None
            }
            self.current_batch_idx += batch_size
            yield this_batch['images'], this_batch['labels']

class Dataset(object):
    """Create a dataset from data and their labels.

    Allows easy use of train/valid/test splits; Batch generator.

    Attributes
    ----------
    all_idxs : list
        All indexes across all splits.
    all_inputs : list
        All inputs across all splits.
    all_labels : list
        All labels across all splits.
    n_labels : int
        Number of labels.
    split : list
        Percentage split of train, valid, test sets.
    test_idxs : list
        Indexes of the test split.
    train_idxs : list
        Indexes of the train split.
    valid_idxs : list
        Indexes of the valid split.
    """

    def __init__(self, Xs, ys=None, split=[1.0, 0.0, 0.0], one_hot=False):
        """Initialize a Dataset object.

        Parameters
        ----------
        Xs : np.ndarray
            Images/inputs to a network
        ys : np.ndarray
            Labels/outputs to a network
        split : list, optional
            Percentage of train, valid, and test sets.
        one_hot : bool, optional
            Whether or not to use one-hot encoding of labels (ys).
        """
        self.all_idxs = []
        self.all_labels = []
        self.all_inputs = []
        self.train_idxs = []
        self.valid_idxs = []
        self.test_idxs = []
        self.n_labels = 0
        self.split = split

        # Now mix all the labels that are currently stored as blocks
        self.all_inputs = Xs
        n_idxs = len(self.all_inputs)
        idxs = range(n_idxs)
        rand_idxs = np.random.permutation(idxs)
        self.all_inputs = self.all_inputs[rand_idxs, ...]
        if ys is not None:
            self.all_labels = ys if not one_hot else dense_to_one_hot(ys)
            self.all_labels = self.all_labels[rand_idxs, ...]
        else:
            self.all_labels = None

        # Get splits
        self.train_idxs = idxs[:round(split[0] * n_idxs)]
        self.valid_idxs = idxs[len(self.train_idxs):
                               len(self.train_idxs) + round(split[1] * n_idxs)]
        self.test_idxs = idxs[len(self.valid_idxs):
                              len(self.valid_idxs) + round(split[2] * n_idxs)]

    @property
    def X(self):
        """Inputs/Xs/Images.

        Returns
        -------
        all_inputs : np.ndarray
            Original Inputs/Xs.
        """
        return self.all_inputs

    @property
    def Y(self):
        """Outputs/ys/Labels.

        Returns
        -------
        all_labels : np.ndarray
            Original Outputs/ys.
        """
        return self.all_labels

    @property
    def train(self):
        """Train split.

        Returns
        -------
        split : DatasetSplit
            Split of the train dataset.
        """
        inputs = self.all_inputs[self.train_idxs, ...]
        if self.all_labels is not None:
            labels = self.all_labels[self.train_idxs, ...]
        else:
            labels = None
        return DatasetSplit(inputs, labels)

    @property
    def valid(self):
        """Validation split.

        Returns
        -------
        split : DatasetSplit
            Split of the validation dataset.
        """
        inputs = self.all_inputs[self.valid_idxs, ...]
        if self.all_labels is not None:
            labels = self.all_labels[self.valid_idxs, ...]
        else:
            labels = None
        return DatasetSplit(inputs, labels)

    @property
    def test(self):
        """Test split.

        Returns
        -------
        split : DatasetSplit
            Split of the test dataset.
        """
        inputs = self.all_inputs[self.test_idxs, ...]
        if self.all_labels is not None:
            labels = self.all_labels[self.test_idxs, ...]
        else:
            labels = None
        return DatasetSplit(inputs, labels)

    def mean(self):
        """Mean of the inputs/Xs.

        Returns
        -------
        mean : np.ndarray
            Calculates mean across 0th (batch) dimension.
        """
        return np.mean(self.all_inputs, axis=0)

    def std(self):
        """Standard deviation of the inputs/Xs.

        Returns
        -------
        std : np.ndarray
            Calculates std across 0th (batch) dimension.
        """
        return np.std(self.all_inputs, axis=0)


text:
exports.name = 'Dog';

exports.initFunction = function (kabam) {
  var DogSchema = new kabam.mongoose.Schema({
    'nickname': String
  });

  DogSchema.index({
    nickname: 1
  });

  return kabam.mongoConnection.model('Dog', DogSchema);
};


text:
<?php
namespace Modules\contactoServicio;

class ContactoServicioModule{
	static function index(){

	}
}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
// copyright 2015 inbetweengames GBR

#pragma once

#include "GameFramework/Character.h"
#include "AnimatedPlaneComponent.h"
#include "AnimatedPlaneCharacter.generated.h"

// AAnimatedPlaneCharacter behaves like ACharacter, but uses a UAnimatedPlaneComponent instead of a USkeletalMeshComponent as a visual representation
// Note: The variable named Mesh will not be set up on this actor!
UCLASS()
class AAnimatedPlaneCharacter : public ACharacter
{
	GENERATED_UCLASS_BODY()

protected:

	// Name of the Sprite component
	static FName SpriteComponentName;

	/** Side view camera */
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
	class UCameraComponent* SideViewCameraComponent;

	/** Camera boom positioning the camera beside the character */
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
	class USpringArmComponent* CameraBoom;

	/** The main skeletal mesh associated with this Character (optional sub-object). */
	UPROPERTY(Category = Character, VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
	class UAnimatedPlaneComponent* m_animatedSprite;

	/** Called for side to side input */
	void MoveRight(float Val);

	// APawn interface
	virtual void SetupPlayerInputComponent(class UInputComponent* InputComponent) override;
	// End of APawn interface

	UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = Animation)
	FAnimationSetup m_idleAnim;

	UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = Animation)
	FAnimationSetup m_walkAnimR;

	UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = Animation)
	FAnimationSetup m_walkAnimL;

	UPROPERTY(BlueprintReadOnly, EditAnywhere, Category = Animation)
	FAnimationSetup m_fallingAnim;

	virtual void Tick(float DeltaSeconds) override;

	void UpdateAnimation();

public:

	virtual void PostInitializeComponents() override;

	/** Returns Sprite subobject **/
	FORCEINLINE class UAnimatedPlaneComponent* GetSprite() const { return m_animatedSprite; }
};


text:
{% extends PATH+"/inc/layout_citizen.html" %}

{% block case_content %}

  {#
    this is a macro: pass the name of the selected item
    and the number for the url.
    Code in inc/layout_case.html
  #}
  {{ case_tabs("support",1) }}

    Back

Travel to work payments claim

            Invoice reference
            00005

            Dates of claim
            From: 1st September 2017
To: 27th October 2017

            Number of units claimed
            128

            Amount claimed
            £640

            Was this an exisitng payee?
            Yes

            Was the receipt verified?
            Yes

            Payment status
            Paid

            Payment reference
            SOP1116

            Notes
            The recipet was paid after invesigating if Oliver had claimed for this

              period previuosly. Lorem ipsum dolor sit amet, consectetur adipiscing elit,

              sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

{% endblock %}