text:
package mod.upcraftlp.spookycraft.handler;

import com.google.common.collect.Lists;
import mod.upcraftlp.spookycraft.Reference;
import mod.upcraftlp.spookycraft.init.SpookyItems;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.entity.player.EntityItemPickupEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

/**
 * @author UpcraftLP
 */
@Mod.EventBusSubscriber
public class RecipeUnlockHandler {

    public static void init() {
        chocolate_bar_recipe = CraftingManager.getRecipe(new ResourceLocation(Reference.MODID, "chocolate_bar"));
        encyclopedia_recipe = CraftingManager.getRecipe(new ResourceLocation(Reference.MODID, "encyclopedia"));
    }

    private static IRecipe chocolate_bar_recipe;
    private static IRecipe encyclopedia_recipe;

    @SubscribeEvent
    public static void onPickupItem(EntityItemPickupEvent event) {
        if(event.getEntityPlayer() instanceof EntityPlayerMP) {
            EntityPlayerMP player = (EntityPlayerMP) event.getEntityPlayer();
            ItemStack stack = event.getItem().getItem();
            if(!player.getRecipeBook().isUnlocked(chocolate_bar_recipe)) {
                if(stack.getItem() == Items.DYE && EnumDyeColor.byDyeDamage(stack.getMetadata()) == EnumDyeColor.BROWN) player.unlockRecipes(Lists.newArrayList(chocolate_bar_recipe));
            }
            if(!player.getRecipeBook().isUnlocked(encyclopedia_recipe)) {
                if(stack.getItem() == SpookyItems.CANDY_CORN) player.unlockRecipes(Lists.newArrayList(encyclopedia_recipe));
            }
        }
    }
}


text:
The steps to contribute a change are:

1. Fork the IronPython3 repository. For more information see [Getting the Sources](Documentation/getting-the-sources.md).
2. Build the repository. For more information see [Building](Documentation/building.md).
1. Make your changes on your machine, ensure ```make.ps1 test-all``` runs successfully, and commit your changes. For more information see [Modifying the Sources](Documentation/modifying-the-sources.md).
1. Push the commits to your fork. This way your name will be the author of the commit in the main IronPython3 tree (once the commits are pulled into the main tree).
1. Create a pull request on Github, this will initiate a code review and CLA signing request
1. The IronPython team will review, and possibly request changes, to your PR
1. Once all comments/questions/concerns have been addressed, your PR will be merged.

Also, [Collaborative Github Workflow](http://www.eqqon.com/index.php/Collaborative_Github_Workflow) has a very good description of the workflow and tips and tricks when contributing to a project hosted on GitHub.

# Ideas for contributions

For our first release, we are currently aiming for a Python 3.4 compatible version of IronPython. To that end we have created checklists in order to help keep track of what remains to be done:

* [What's New In Python 3.0](WhatsNewInPython30.md)
* [What's New In Python 3.1](WhatsNewInPython31.md)
* [What's New In Python 3.2](WhatsNewInPython32.md)
* [What's New In Python 3.3](WhatsNewInPython33.md)
* [What's New In Python 3.4](WhatsNewInPython34.md)
* [What's New In Python 3.5](WhatsNewInPython35.md)

Suggestions for first time contributors:

* Updating documentation (such as checking off completed features in the above lists).
* Trying out failing tests to identify and/or fix the cause of the failures.
* [List of good first issues](https://github.com/IronLanguages/ironpython3/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22).

redpajama_set_name: RedPajamaGithub


text:
                 <?php
                    if($this->session->flashdata('success')){
                        ?>

                            <button type="button" class="close" data-dismiss="alert">×Close</button>
                            Berhasil! <?php echo $this->session->flashdata('success'); ?>

                        <?php
                    }

                    if($this->session->flashdata('warning')){
                        ?>

                            <button type="button" class="close" data-dismiss="alert">×Close</button>
                            Perhatian! <?php echo $this->session->flashdata('warning'); ?>

                        <?php
                    }
                ?>

Event<a class="btn btn-primary" href="<?php echo base_url(); ?>admin/event/add">Tambah

                                Title
                                Post By
                                Post Date
                                Modify Date
                                Aksi

							 <?php
                                foreach ($event as $q_event) {
                                    ?>

                                        <?php echo $q_event->title_eng ?>
                                        <?php echo $q_event->name ?>
                                        <?php echo convertDateTime($q_event->post_date) ?>
                                        <?php echo $q_event->modify_date ?>

                                            <a href="<?php echo base_url(); ?>admin/event/view/<?php echo $q_event->id ?>" class="btn btn-info">View
                                            <a href="<?php echo base_url(); ?>admin/event/edit/<?php echo $q_event->id ?>" class="btn btn-success">Edit
                                            <a href="<?php echo base_url(); ?>admin/event/delete/<?php echo $q_event->id ?>" class="btn btn-danger">Hapus

                                    <?php
                                }
                            ?>


text:
import { getBookingsForDay } from '../bookings';
import { makeAction } from './utils';

export const FETCH_BOOKINGS_REQUEST = "FETCH_BOOKINGS_REQUEST";
export const FETCH_BOOKINGS_SUCCESS = "FETCH_BOOKINGS_SUCCESS";
export const FETCH_BOOKINGS_FAILURE = "FETCH_BOOKINGS_FAILURE";

export const fetchBookingsRequest = makeAction(
  FETCH_BOOKINGS_REQUEST,
  "date"
);

export const fetchBookingsSuccess = makeAction(
  FETCH_BOOKINGS_SUCCESS,
  "date",
  "roomDiaries"
);

export const fetchBookingsFailure = makeAction(
  FETCH_BOOKINGS_FAILURE,
  "date",
  "error"
);

export function fetchBookings(date) {
  return function(dispatch) {
    dispatch(fetchBookingsRequest(date));
    return getBookingsForDay(date)
      .then((roomDiaries) => dispatch(fetchBookingsSuccess(date, roomDiaries)))
      .catch((error) => dispatch(fetchBookingsFailure(date, error)));
  }
}


text:
title: Tables
tags: [formatting]
keywords: datatables, tables, grids, markdown, multimarkdown, jquery plugins
last_updated: March 20, 2016
datatable: true
summary: "You can format tables using either multimarkdown syntax or HTML. You can also use jQuery datatables (a plugin) if you need more robust tables."
sidebar: mydoc_sidebar
permalink: /mydoc_tables/
---

{% unless site.output == "pdf" %}

{% endunless %}

## Multimarkdown Tables

You can use Multimarkdown syntax for tables. The following shows a sample:

```
Column 1 | Column 2
--------|----------
cell 1a | cell 1b
cell 2a | cell 2b
```

This renders to the following:

 Column 1 | Column 2
--------|----------
cell 1a | cell 1b
cell 2a | cell 2b

## jQuery datables

You also have the option of using a [jQuery datatable](https://www.datatables.net/), which gives you some more options. If you want to use a jQuery datatable, then add `datatable: true` in a page's frontmatter. This will load the right jQuery datatable scripts for the table on that page only (rather than loading the scripts on every page of the site.)

Also, you need to add this script to trigger the jQuery table on your page:

```js
<script>
$(document).ready(function(){

    $('table.display').DataTable( {
        paging: true,
        stateSave: true,
        searching: true
    }
        );
});
</script>
```

The available options for the datable are described in the [datatable documentation](https://www.datatables.net/manual/options), which is excellent.

Additionally, you must add a class of `display` to your tables. (You can change the class, but then you'll need to change the trigger above from `table.display` to whatever class you want to you. You might have different triggers with different options for different tables.)

Since Markdown doesn't allow you to add classes to tables, you'll need to use HTML for any datatables. Here's an example:

```html
<table id="sampleTable" class="display">
   <thead>
      <tr>
         <th>Parameter</th>
         <th>Description</th>
         <th>Type</th>
         <th>Default Value</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>Parameter 1</td>
         <td>Sample description
         </td>
         <td>Sample type</td>
         <td>Sample default value</td>
      </tr>
      <tr>
         <td>Parameter 2</td>
         <td>Sample description
         </td>
         <td>Sample type</td>
         <td>Sample default value</td>
      </tr>
    <tr>
       <td>Parameter 3</td>
       <td>Sample description
       </td>
       <td>Sample type</td>
       <td>Sample default value</td>
    </tr>
      <tr>
         <td>Parameter 4</td>
         <td>Sample description
         </td>
         <td>Sample type</td>
         <td>Sample default value</td>
      </tr>
   </tbody>
</table>
```

This renders to the following:

         Food
         Description
         Category
         Sample type

         Apples
         A small, somewhat round and often red-colored, crispy fruit grown on trees.

         Fruit
         Fuji

         Bananas
         A long and curved, often-yellow, sweet and soft fruit that grows in bunches in tropical climates.

         Fruit
         Snow

         Kiwis
         A small, hairy-skinned sweet fruit with green-colored insides and seeds.

         Fruit
         Golden

           Oranges
           A spherical, orange-colored sweet fruit commonly grown in Florida and California.

           Fruit
           Navel

Notice a few features:

* You can keyword search the table. When you type a word, the table filters to match your word.
* You can sort the column order.
* You can page the results so that you show only a certain number of values on the first page and then require users to click next to see more entries.

Read more of the [datatable documentation](https://www.datatables.net/manual/options) to get a sense of the options you can configure. You should probably only use datatables when you have long, massive tables full of information.

{{site.data.alerts.note}} Try to keep the columns to 3 or 4 columns only. If you add 5+ columns, your table may create horizontal scrolling with the theme. Additionally, keep the column heading titles short.{{site.data.alerts.end}}


text:
test ios
==========

Usage | Synopsis
------|-------
Run tests on all connected devices | `$ tns test ios [--watch] [--debug-brk]`
Run tests on a selected device | `$ tns test ios --device <Device ID> [--watch] [--debug-brk]`
Run tests in the iOS Simulator | `$ tns test ios --emulator [--watch] [--debug-brk]`

Runs the tests in your project on connected iOS devices or the iOS Simulator.<% if(isConsole && isMacOS) { %> Your project must already be configured for unit testing by running `$ tns test init`.<% } %>

<% if(isConsole && (isLinux || isWindows)) { %>WARNING: You can run this command only on OS X systems. To view the complete help for this command, run `$ tns help test ios`<% } %>

<% if((isConsole && isMacOS) || isHtml) { %>
### Options
* `--watch` - If set, when you save changes to the project, changes are automatically synchronized to the connected device and tests are re-ran.
* `--device` - Specifies the serial number or the index of the connected device on which you want to run tests. To list all connected devices, grouped by platform, run `$ tns device`. You cannot set `--device` and `--emulator` simultaneously.
* `--emulator` - Runs tests on the iOS Simulator. You cannot set `--device` and `--emulator` simultaneously.
* `--debug-brk` - Runs the tests under the debugger. The debugger will break just before your tests are executed, so you have a chance to place breakpoints.

### Attributes
* `<Device ID>` is the device index or identifier as listed by `$ tns device`<% } %>

<% if(isHtml) { %>
### Prerequisites

* Verify that [you have configured your project for unit testing](test-init.html).
* Verify that [you have stored your unit tests in `app` → `tests`](http://docs.nativescript.org/testing).
* Verify that [you have configured your system and devices properly](http://docs.nativescript.org/testing).

### Related Commands
Command | Description
--------|------------
[test init](test-init.html) | Configures your project for unit testing with a selected framework.
[test android](test-android.html) | Runs the tests in your project on Android devices or native emulators.
<% } %>


text:
module Tree.BTree where

import Tree.Types

leaf :: a -> BTree a
leaf v = Node v Empty Empty

--------------------
-- traverse

-- Modify value in each node.
mapTree :: (a -> b) -> BTree a -> BTree b
mapTree f = foldTree (\v lRes rRes -> Node (f v) lRes rRes) Empty

-- PRE-order traversal.  (1. root.  2. left.  3. right.)
-- f's args: nodeVal leftResult rightResult
foldTree :: (a -> b -> b -> b) -> b -> BTree a -> b
foldTree f acc Empty = acc
foldTree f acc (Node v left right) =
    f v (foldTree f acc left) (foldTree f acc right)

tSum :: Num a => BTree a -> a
tSum = foldTree (\v lRes rRes -> v + lRes + rRes) 0

-- Number of values.
tSize :: BTree a -> Int
tSize = foldTree (\_ lRes rRes -> 1 + lRes + rRes) 0

-- Number of levels in the tree.
tDepth :: BTree a -> Int
tDepth = foldTree (\_ lRes rRes -> 1 + maximum [lRes, rRes]) 0


text:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"./meta/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>
		<!-- Connection -->
		<property name="connection.driver_class">
			org.hsqldb.jdbcDriver
		</property>
		<property name="connection.url">
			jdbc:hsqldb:hsql://localhost/ticketline
		</property>
		<property name="dialect">
			org.hibernate.dialect.HSQLDialect
		</property>

		<property name="connection.username">sa</property>
		<property name="connection.password"></property>

		<!-- mapping files -->
		<mapping resource="hbm/Artikel.hbm.xml" />
		<mapping resource="hbm/Belegung.hbm.xml" />
		<mapping resource="hbm/Auffuehrung.hbm.xml" />
		<mapping resource="hbm/Engagement.hbm.xml" />
		<mapping resource="hbm/Kategorie.hbm.xml" />
		<mapping resource="hbm/Saal.hbm.xml" />
		<mapping resource="hbm/Transaktion.hbm.xml" />
		<mapping resource="hbm/Veranstaltung.hbm.xml" />
		<mapping resource="hbm/Ticketcard.hbm.xml" />
		<mapping resource="hbm/Ort.hbm.xml" />
		<mapping resource="hbm/Reihe.hbm.xml" />
		<mapping resource="hbm/Bestellung.hbm.xml" />
		<mapping resource="hbm/Kuenstler.hbm.xml" />
	</session-factory>

</hibernate-configuration>


text:
function FileData_Pairs(x)
{
x.t("files","topics");
x.t("describes","reports");
x.t("static","brb-arraytools");
x.t("download","product");
x.t("product","brb");
x.t("advanced","searches");
x.t("advanced","search");
x.t("results","overview");
x.t("results","high");
x.t("results","viewing");
x.t("results","section");
x.t("results","rembrandt");
x.t("results","genepattern");
x.t("overview","notification");
x.t("high","order");
x.t("searches","high");
x.t("search","results");
x.t("search","query");
x.t("array","tools");
x.t("queries","clinical");
x.t("brb-arraytools","archive");
x.t("viewing","results");
x.t("section","describes");
x.t("section","include");
x.t("reports","advanced");
x.t("reports","search");
x.t("rembrandt","returns");
x.t("notification","prolonged");
x.t("analyses","download");
x.t("include","following");
x.t("tools","static");
x.t("brb","array");
x.t("archive","files");
x.t("query","results");
x.t("topics","section");
x.t("order","analyses");
x.t("order","analysis");
x.t("following","results");
x.t("genepattern","analysis");
x.t("returns","advanced");
x.t("analysis","results");
x.t("analysis","reports");
x.t("prolonged","queries");
x.t("clinical","reports");
}


text:
/**
 *
 */
package org.socraticgrid.hl7.services.uc.db.dto.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

/**
 * @author steven
 * @created Jan 23, 2014

 */
@MappedTypes(Boolean.class)
public class DerbyBooleanTypeHandler implements TypeHandler<Boolean> {

	@Override
	public void setParameter(PreparedStatement ps, int i, Boolean parameter,
			JdbcType jdbcType) throws SQLException {
		ps.setInt(i, parameter?1:0 );
	}

	@Override
	public Boolean getResult(ResultSet rs, String columnName)
			throws SQLException {

		return rs.getInt(columnName)==1?true:false;
	}

	@Override
	public Boolean getResult(ResultSet rs, int columnIndex) throws SQLException {
		// TODO Auto-generated method stub

		return rs.getInt(columnIndex)==1?true:false;
	}

	@Override
	public Boolean getResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		// TODO Auto-generated method stub

		return cs.getInt(columnIndex)==1?true:false;
	}

}


text:
using System.Linq;
using CompaniesHouse.Tests.ResourceBuilders;
using AutoFixture;

namespace CompaniesHouse.Tests.CompaniesHouseCompanyFilingHistoryClientTests
{
    public class CompanyFilingHistoryBuilder
    {
        public static CompanyFilingHistory Build(CompaniesHouseCompanyFilingHistoryClientTestCase testCase)
        {
            var fixture = new Fixture();
            fixture.Customizations.Add(new UniversalDateSpecimenBuilder<FilingHistoryItem>(x => x.DateOfProcessing));
            fixture.Customizations.Add(new UniversalDateSpecimenBuilder<FilingHistoryItemAnnotation>(x => x.DateOfAnnotation));
            fixture.Customizations.Add(new UniversalDateSpecimenBuilder<FilingHistoryItemAssociatedFiling>(x => x.Date));
            fixture.Customizations.Add(new UniversalDateSpecimenBuilder<FilingHistoryItemResolution>(x => x.DateOfProcessing));

            var annotations = fixture.Build<FilingHistoryItemAnnotation>()
               .CreateMany().ToArray();

            var associatedFilings = fixture.Build<FilingHistoryItemAssociatedFiling>()
               .CreateMany().ToArray();

            var resolutions = fixture.Build<FilingHistoryItemResolution>()
                .With(x => x.Category, testCase.ResolutionCategory)
                .With(x => x.Subcategory, testCase.Subcategory)
               .CreateMany().ToArray();

            var items = fixture.Build<FilingHistoryItem>()
                .With(x => x.Category, testCase.Category)
                .With(x => x.Subcategory, testCase.Subcategory)
                .With(x => x.Annotations, annotations)
                .With(x => x.AssociatedFilings, associatedFilings)
                .With(x => x.Resolutions, resolutions)
                .CreateMany().ToArray();

            var filingHistory = fixture.Build<CompanyFilingHistory>()
                .With(x => x.HistoryStatus, testCase.HistoryStatus)
                .With(x => x.Items, items)
                .Create();

            return filingHistory;
        }

        public static FilingHistoryItem BuildOne(CompaniesHouseCompanyFilingHistoryClientTestCase testCase)
        {
            var fixture = new Fixture();
            fixture.Customizations.Add(new UniversalDateSpecimenBuilder<FilingHistoryItem>(x => x.DateOfProcessing));
            fixture.Customizations.Add(new UniversalDateSpecimenBuilder<FilingHistoryItemAnnotation>(x => x.DateOfAnnotation));
            fixture.Customizations.Add(new UniversalDateSpecimenBuilder<FilingHistoryItemAssociatedFiling>(x => x.Date));
            fixture.Customizations.Add(new UniversalDateSpecimenBuilder<FilingHistoryItemResolution>(x => x.DateOfProcessing));

            var annotations = fixture.Build<FilingHistoryItemAnnotation>()
                .CreateMany()
                .ToArray();

            var associatedFilings = fixture.Build<FilingHistoryItemAssociatedFiling>()
                .CreateMany()
                .ToArray();

            var resolutions = fixture.Build<FilingHistoryItemResolution>()
                .With(x => x.Category, testCase.ResolutionCategory)
                .With(x => x.Subcategory, testCase.Subcategory)
                .CreateMany()
                .ToArray();

           return fixture.Build<FilingHistoryItem>()
                .With(x => x.Category, testCase.Category)
                .With(x => x.Subcategory, testCase.Subcategory)
                .With(x => x.Annotations, annotations)
                .With(x => x.AssociatedFilings, associatedFilings)
                .With(x => x.Resolutions, resolutions)
                .Create();
        }
    }
}


text:
#pragma once
#include "library/tactic/tactic_state.h"
#include "library/tactic/elaborator_exception.h"
#include "library/vm/interaction_state.h"

namespace lean {
elaborator_exception unsolved_tactic_state(tactic_state const & ts, format const & fmt, expr const & ref);
elaborator_exception unsolved_tactic_state(tactic_state const & ts, char const * msg, expr const & ref);
[[noreturn]] void throw_unsolved_tactic_state(tactic_state const & ts, format const & fmt, expr const & ref);
[[noreturn]] void throw_unsolved_tactic_state(tactic_state const & ts, char const * msg, expr const & ref);

format mk_tactic_error_msg(tactic_state const & ts, format const & fmt);

class tactic_evaluator : public tactic::evaluator {
private:
    expr m_ref;
protected:
    virtual void process_failure(vm_state & S, vm_obj const & r) override;
public:
    tactic_evaluator(type_context_old & ctx, options const & opts, expr const & ref, bool allow_profiler = false):
            tactic::evaluator(ctx, opts, allow_profiler), m_ref(ref) {}
    virtual vm_obj operator()(expr const & tactic, buffer<vm_obj> const & args, tactic_state const & s) override;
    vm_obj operator()(expr const & tactic, tactic_state const & s) {
        return tactic::evaluator::operator()(tactic, s);
    }
};
}


text:
package pl.hycom.pip.messanger.controller.model;

import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

/**
 * Created by Piotr on 04.06.2017.
 */
@Data
@NoArgsConstructor
public class UserEmail {

    @NotNull
    @Size(min = 6, max = 40, message = "{validation.error.email.size}")
    @Pattern(regexp = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$", message = "{validation.error.email.format}")
    private String userMail;
}


text:
function stripURL(url) {
    return url ? url.match( /[^\/]+\/?$/ )[0] : url;
}

function throwException(message) {
    throw new Error(message ? message : "An exception");
}

var errorsSeen = 0;
function dumpOnErrorArgumentValuesAndReturn(returnValue, callback) {
    window.onerror = function (message, url, line, column, error) {
        debug("window.onerror: \"" + message + "\" at " + stripURL(url) + " (Line: " + line + ", Column: " + column + ")");
        if (error)
            debug(stripStackURLs(error.stack));
        else
            debug("No stack trace.");

        if (callback)
            callback(++errorsSeen);
        if (returnValue)
            debug("Returning 'true': the error should not be reported in the console as an unhandled exception.\n\n\n");
        else
            debug("Returning 'false': the error should be reported in the console as an unhandled exception.\n\n\n");
        return returnValue;
    };
}

function dumpErrorEventAndAllowDefault(callback) {
    window.addEventListener('error', function (e) {
        dumpErrorEvent(e)
        debug("Not calling e.preventDefault(): the error should be reported in the console as an unhandled exception.\n\n\n");
        if (callback)
            callback(++errorsSeen);
    });
}

function dumpErrorEventAndPreventDefault(callback) {
    window.addEventListener('error', function (e) {
        dumpErrorEvent(e);
        debug("Calling e.preventDefault(): the error should not be reported in the console as an unhandled exception.\n\n\n");
        e.preventDefault();
        if (callback)
            callback(++errorsSeen);
    });
}

var eventPassedToTheErrorListener = null;
var eventCurrentTarget = null;
function dumpErrorEvent(e) {
    debug("Handling '" + e.type + "' event (phase " + e.eventPhase + "): \"" + e.message + "\" at " + stripURL(e.filename) + ":" + e.lineno);
    if (e.error)
        debug(stripStackURLs(e.error.stack));
    else
        debug("No stack trace.");

    eventPassedToTheErrorListener = e;
    eventCurrentTarget = e.currentTarget;
    shouldBe('eventPassedToTheErrorListener', 'window.event');
    shouldBe('eventCurrentTarget', 'window');
    eventPassedToTheErrorListener = null;
    eventCurrentTarget = null;
}

function stripStackURLs(stackTrace) {
    stackTrace = stackTrace.split("\n");
    var length = Math.min(stackTrace.length, 100);
    var text = "Stack Trace:\n";
    for (var i = 0; i < length; i++) {
        text += stackTrace[i].replace(/at ((?:eval at \()?[a-zA-Z\.]+ )?\(?.+\/([^\/]+):(\d+):(\d+)\)?/, "at $1$2:$3:$4") + "\n";
    }
    return text;
}


text:
namespace content {
class SmsFetcher;
}  // namespace content

class SharingMessageHandler;
class SharingDeviceRegistration;
class SharingDeviceSource;
class SharingMessageSender;
class Profile;

// Interface for handling incoming SharingMessage.
class SharingHandlerRegistryImpl : public SharingHandlerRegistry {
 public:
  SharingHandlerRegistryImpl(
      Profile* profile,
      SharingDeviceRegistration* sharing_device_registration,
      SharingMessageSender* message_sender,
      SharingDeviceSource* device_source,
      content::SmsFetcher* sms_fetcher);
  ~SharingHandlerRegistryImpl() override;

  // Gets SharingMessageHandler registered for |payload_case|.
  SharingMessageHandler* GetSharingHandler(
      chrome_browser_sharing::SharingMessage::PayloadCase payload_case)
      override;

  // Register SharingMessageHandler for |payload_case|.
  void RegisterSharingHandler(
      std::unique_ptr<SharingMessageHandler> handler,
      chrome_browser_sharing::SharingMessage::PayloadCase payload_case)
      override;

  // Unregister SharingMessageHandler for |payload_case|.
  void UnregisterSharingHandler(
      chrome_browser_sharing::SharingMessage::PayloadCase payload_case)
      override;

 private:
  // Registers |handler| for handling |payload_cases| SharingMessages. No
  // handlers should have been registered with |payload_cases|.
  void AddSharingHandler(
      std::unique_ptr<SharingMessageHandler> handler,
      std::set<chrome_browser_sharing::SharingMessage::PayloadCase>
          payload_cases);

 private:
  std::vector<std::unique_ptr<SharingMessageHandler>> handlers_;
  std::map<chrome_browser_sharing::SharingMessage::PayloadCase,
           SharingMessageHandler*>
      handler_map_;
  std::map<chrome_browser_sharing::SharingMessage::PayloadCase,
           std::unique_ptr<SharingMessageHandler>>
      extra_handler_map_;
};

#endif  // CHROME_BROWSER_SHARING_SHARING_HANDLER_REGISTRY_IMPL_H_


text:
START_ATF_NAMESPACE
    namespace vc_attributes
    {
        template<>
        struct caseAttribute
        {
            int value;
        };
    }; // end namespace vc_attributes
END_ATF_NAMESPACE


text:
@interface Beacon : NSObject <CBPeripheralManagerDelegate>
@property CBPeripheralManager * manager;
@property (readonly) NSUUID * uuid;
@property (readonly) NSInteger major;
@property (readonly) NSInteger minor;

-(instancetype) initWithUUID:(NSUUID *)uuid major:(NSInteger)major andMinor:(NSInteger)minor;
-(NSDictionary *) advertisement;

@end

@implementation Beacon
-(instancetype) initWithUUID:(NSUUID *)uuid major:(NSInteger)major andMinor:(NSInteger)minor {
  if (self = [super init]) {
    _manager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
    _uuid    = uuid;
    _major   = major;
    _minor   = minor;
  }

  return self;
}

-(void) peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
  if(peripheral.state == CBPeripheralManagerStatePoweredOn) {
    [peripheral startAdvertising:[self advertisement]];
    NSLog(@"Advertising iBeacon with UUID: %@, major: %zd, minor: %zd", [self.uuid UUIDString], self.major, self.minor);
  }
}

- (NSDictionary *)advertisement {
    NSString *beaconKey = @"kCBAdvDataAppleBeaconKey";

    unsigned char advertisement[21];

    [self.uuid getUUIDBytes:(unsigned char *)&advertisement];

    advertisement[16] = (unsigned char)(self.major >> 8);
    advertisement[17] = (unsigned char)(self.major & 255);
    advertisement[18] = (unsigned char)(self.minor >> 8);
    advertisement[19] = (unsigned char)(self.minor & 255);
    advertisement[20] = -59;

    return  @{beaconKey: [NSData dataWithBytes:advertisement length:21]};
}

@end

int main(int argc, const char * argv[])
{

  @autoreleasepool {
      NSUserDefaults * options = [NSUserDefaults standardUserDefaults];

      NSArray * requiredArguments = @[@"uuid", @"major", @"minor"];

      for (NSString * argument in requiredArguments) {
        if(![options objectForKey:argument]) {
          NSLog(@"Usage: ibeacon -uuid uuid -major major -minor");
          exit(1);
        }
      }

      NSUUID * uuid = [[NSUUID alloc] initWithUUIDString:[options stringForKey:@"uuid"]];

      Beacon * beacon = [[Beacon alloc] initWithUUID:uuid
                                               major:[options integerForKey:@"major"]
                                            andMinor:[options integerForKey:@"minor"]];

      NSLog(@"Setting up iBeacon with UUID: %@", [beacon.uuid UUIDString]);

      [[NSRunLoop currentRunLoop] run];
  }
    return 0;
}


text:
package com.yahoo.athenz.zts.cert.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.yahoo.athenz.zts.cert.CertRecordStoreConnection;
import com.yahoo.athenz.zts.cert.X509CertRecord;
import com.yahoo.rdl.JSON;

public class FileCertRecordStoreConnection implements CertRecordStoreConnection {

    File rootDir;
    public FileCertRecordStoreConnection(File rootDir) {
        this.rootDir = rootDir;
    }

    @Override
    public void close() {
    }

    @Override
    public void setOperationTimeout(int opTimeout) {
    }

    @Override
    public X509CertRecord getX509CertRecord(String provider, String instanceId) {
        return getCertRecord(provider, instanceId);
    }

    @Override
    public boolean updateX509CertRecord(X509CertRecord certRecord) {
        if (certRecord != null) {
            putCertRecord(certRecord);
        }
        return true;
    }

    @Override
    public boolean insertX509CertRecord(X509CertRecord certRecord) {
        if (certRecord != null) {
            putCertRecord(certRecord);
        }
        return true;
    }

    @Override
    public boolean deleteX509CertRecord(String provider, String instanceId) {
        deleteCertRecord(provider, instanceId);
        return true;
    }

    @Override
    public int deleteExpiredX509CertRecords(int expiryTimeMins) {
        String[] fnames = rootDir.list();
        if (fnames == null) {
            return 0;
        }
        long currentTime = System.currentTimeMillis();
        int count = 0;
        for (String fname : fnames) {

            // if the modification timestamp is older than
            // specified number of minutes then we'll delete it

            File f = new File(rootDir, fname);
            if (currentTime - f.lastModified() < expiryTimeMins * 60 * 1000) {
                continue;
            }
            //noinspection ResultOfMethodCallIgnored
            f.delete();
            count += 1;
        }
        return count;
    }

    private synchronized X509CertRecord getCertRecord(String provider, String instanceId) {
        File f = new File(rootDir, provider + "-" + instanceId);
        if (!f.exists()) {
            return null;
        }
        X509CertRecord record = null;
        try {
            Path path = Paths.get(f.toURI());
            record = JSON.fromBytes(Files.readAllBytes(path), X509CertRecord.class);
        } catch (IOException ignore) {
        }
        return record;
    }

    private synchronized void putCertRecord(X509CertRecord certRecord) {

        File f = new File(rootDir, certRecord.getProvider() + "-" + certRecord.getInstanceId());
        String data = JSON.string(certRecord);
        try {
            FileWriter fileWriter = new FileWriter(f);
            fileWriter.write(data);
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException ignored) {
        }
    }

    private synchronized void deleteCertRecord(String provider, String instanceId) {
        File f = new File(rootDir, provider + "-" + instanceId);
        if (f.exists()) {
            if (!f.delete()) {
                throw new RuntimeException("Cannot delete file: " + f);
            }
        }
    }
}


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

<rootTag>
  <Award>
    <AwardTitle>PostDoctoral Research Fellowship</AwardTitle>
    <AwardEffectiveDate>10/01/2013</AwardEffectiveDate>
    <AwardExpirationDate>09/30/2017</AwardExpirationDate>
    <AwardAmount>150000</AwardAmount>
    <AwardInstrument>
      <Value>Fellowship</Value>
    </AwardInstrument>
    <Organization>
      03040000
      <Directorate>
        <LongName>Direct For Mathematical & Physical Scien</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Mathematical Sciences</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Bruce P. Palka</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>This award is made as part of the FY 2013 Mathematical Sciences Postdoctoral Research Fellowships Program. Each of the fellowships supports a research and training project at a host institution in the mathematical sciences, including applications to other disciplines, under the mentorship of a sponsoring scientist. The title of the project for this fellowship to Angela Hicks is "A New Approach to Parking Functions and the Diagonal Harmonics via the HMZ Conjecture." The host institution for the fellowship is Stanford University, and the sponsoring scientist is Dr. Persi Diaconis.</AbstractNarration>
    <MinAmdLetterDate>03/27/2013</MinAmdLetterDate>
    <MaxAmdLetterDate>03/27/2013</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1303761</AwardID>
    <Investigator>
      <FirstName>Angela</FirstName>
      <LastName>Hicks</LastName>
      <EmailAddress/>
      <StartDate>03/27/2013</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Hicks Angela S</Name>
      <CityName>La Jolla</CityName>
      <ZipCode>920371437</ZipCode>
      <PhoneNumber></PhoneNumber>
      <StreetAddress></StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>California</StateName>
      <StateCode>CA</StateCode>
    </Institution>
  </Award>
</rootTag>


text:
package mh.smartcard.multos.command;

import mh.smartcard.iso.CLA;
import mh.smartcard.iso.Command;
import mh.smartcard.multos.INS;

// For MULTOS 3-4.4
// 80 00 00 00 0 null 7F
//   2 MULTOS Version Number
//   1 IC Manufacturer ID
//   1 Implementation ID
//   6 MCD ID
//   1 Product ID
//   4 Issuer ID
//   1 MSM Controls Data Date
//   8 MCD Number
//  80 RFU
//   2 Maximum Dynamic Size
//   2 Maximum Public Size
//   2 Maximum DIR File Record Size
//   2 Maximum FCI Record Size
//   2 Maximum ATR Historical Byte Record Size
//   2 Maximum ATR File Record Size
//   2 MULTOS Public Key Certificate Length
//   1 Security Level
//   2 Certification Method ID
//   2 Application Signature Method ID
//   2 Encipherment Descriptor
//   2 Hash Method ID

public class GetMultosData extends Command.Short {
	public static final int NE = 0x7F;

	private GetMultosData(byte[] bytes) {
		super(bytes);
	}

	public static GetMultosData getInstance() {
		return getInstance(INS.GET_MULTOS_DATA, 0, 0, null, NE);
	}

	protected static GetMultosData getInstance(INS ins, int p1, int p2, byte[] data, int ne) {
		final CLA cla = CLA.PROP_80;
		return new GetMultosData(getBytes(cla, ins, p1, p2, data, ne));
	}
}


text:
import { call, put } from 'redux-saga/effects';
import { path } from 'ramda';
import TemperatureActions from '../Redux/TemperatureRedux';
import convertFromKelvin from '../Transforms/ConvertFromKelvin';

export function* getTemperature(api, action) {
  const { city } = action;
  // make the call to the api
  const response = yield call(api.getCity, city);

  // success?
  if (response.ok) {
    const kelvin = path(['data', 'main', 'temp_max'], response);
    const temperature = convertFromKelvin(kelvin);
    yield put(TemperatureActions.temperatureSuccess(temperature, 'bonus'));
  } else {
    yield put(TemperatureActions.temperatureFailure());
  }
}


text:
// AngularJS Utils
/**
 * @description
 * Determines if two objects or two values are equivalent. Supports value types, regular
 * expressions, arrays and objects.
 *
 * @param {*} o1 Object or value to compare.
 * @param {*} o2 Object or value to compare.
 * @returns {boolean} True if arguments are equal.
 */
function equals(o1, o2) {
  if (o1 === o2) return true;
  if (o1 === null || o2 === null) return false;
  if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  if (t1 == t2) {
    if (t1 == 'object') {
      if (isArray(o1)) {
        if (!isArray(o2)) return false;
        if ((length = o1.length) == o2.length) {
          for (key=0; key<length; key++) {
            if (!equals(o1[key], o2[key])) return false;
          }
          return true;
        }
      } else if (isDate(o1)) {
        if (!isDate(o2)) return false;
        return equals(o1.getTime(), o2.getTime());
      } else if (isRegExp(o1) && isRegExp(o2)) {
        return o1.toString() == o2.toString();
      } else {
        if (isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
        keySet = {};
        for (key in o1) {
          if (isFunction(o1[key])) continue;
          if (!equals(o1[key], o2[key])) return false;
          keySet[key] = true;
        }
        for (key in o2) {
          if (!keySet.hasOwnProperty(key) &&
            o2[key] !== undefined &&
            !isFunction(o2[key])) return false;
        }
        return true;
      }
    }
  }
  return false;
}

/**
 * @description
 * A function that returns its first argument.
 */
function value(a) {return a;}

/**
 * @description
 * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
 * to `dst`. You can specify multiple `src` objects.
 *
 * @param {Object} dst Destination object.
 * @param {...Object} src Source object(s).
 * @returns {Object} Reference to `dst`.
 */
function extend(dst) {
  for (var i = 1, ii = arguments.length; i < ii; i++) {
    var obj = arguments[i];
    if (obj) {
      var keys = Object.keys(obj);
      for (var j = 0, jj = keys.length; j < jj; j++) {
        var key = keys[j];
        dst[key] = obj[key];
      }
    }
  }
  return dst;
}

/**
 * @description
 * Creates a new object without a prototype.
 * @returns {Object}
 */
function createMap() {
  return Object.create(null);
}

/**
 * @description
 * A function that performs no operations.
 */
function noop() {}

/**
 * @description Converts the specified string to uppercase.
 * @param {string} string String to be converted to uppercase.
 * @returns {string} Uppercased string.
 */
var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};

/**
 * @description Converts the specified string to lowercase.
 * @param {string} string String to be converted to lowercase.
 * @returns {string} Lowercased string.
 */
var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};

/**
 * @description
 * Serializes input into a JSON-formatted string.
 *
 * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
 * @returns {string|undefined} JSON-ified string representing `obj`.
 */
function toJson(obj) {
  if (typeof obj === 'undefined') return undefined;
  return JSON.stringify(obj);
}

/**
 * @description
 * Creates a deep copy of `source`, which should be an object or an array.
 * @param {*} source The source that will be used to make a copy.
 *                   Can be any type, including primitives, `null`, and `undefined`.
 * @param {(Object|Array)=} destination Destination into which the source is copied. If
 *     provided, must be of the same type as `source`.
 * @returns {*} The copy or updated `destination`, if `destination` was specified.
 *
 */
function copy(source, destination, stackSource, stackDest) {
  if (isWindow(source)) {
    throw Error("Can't copy! Making copies of Window instances is not supported.");
  }

  if (!destination) {
    destination = source;
    if (source) {
      if (isArray(source)) {
        destination = copy(source, [], stackSource, stackDest);
      } else if (isDate(source)) {
        destination = new Date(source.getTime());
      } else if (isRegExp(source)) {
        destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
        destination.lastIndex = source.lastIndex;
      } else if (isObject(source)) {
        var emptyObject = Object.create(Object.getPrototypeOf(source));
        destination = copy(source, emptyObject, stackSource, stackDest);
      }
    }
  } else {
    if (source === destination) throw Error("Can't copy! Source and destination are identical.");

    stackSource = stackSource || [];
    stackDest = stackDest || [];

    if (isObject(source)) {
      var index = stackSource.indexOf(source);
      if (index !== -1) return stackDest[index];

      stackSource.push(source);
      stackDest.push(destination);
    }

    var result;
    if (isArray(source)) {
      destination.length = 0;
      for (var i = 0; i < source.length; i++) {
        result = copy(source[i], null, stackSource, stackDest);
        if (isObject(source[i])) {
          stackSource.push(source[i]);
          stackDest.push(result);
        }
        destination.push(result);
      }
    } else {
      if (isArray(destination)) {
        destination.length = 0;
      } else {
        forEach(destination, function(value, key) {
          delete destination[key];
        });
      }
      for (var key in source) {
        if (source.hasOwnProperty(key)) {
          result = copy(source[key], null, stackSource, stackDest);
          if (isObject(source[key])) {
            stackSource.push(source[key]);
            stackDest.push(result);
          }
          destination[key] = result;
        }
      }
    }

  }
  return destination;
}


text:
title: "Ignore Patterns"
sub_link: "cli/ignore"
meta_title: "A guide on how to set a custom ignore file for Polyaxon CLI - Core Concepts"
meta_description: "Polyaxon upload commands respect an ignore file that contains list of patterns while traversing the directory tree."
visibility: public
status: published
tags:
  - cli
  - reference
  - polyaxon
  - concepts
  - tutorials
sidebar: "core"
---

Please note that whenever a user triggers an upload mechanism, Polyaxon CLI or Client will check if the working directory is initialized with a `.polyaxonignore` file.

## Default behavior

If a user does not define a custom `.polyaxonignore`, the CLI will use a default list of patterns to avoid uploading some common ignorable files and dirs by default.
For example Polyaxon CLI will skip uploading the `.git` folder.

## Ignore manager

Every time an upload command is invoked it will invoke the ignore manager to check the defined patterns to ignore while traversing the directory's tree.

## Defining a custom ignore file

Users can add the `.polyaxonignore` file to their git repo, or they can create a new project with the `--init` flag, or manually initialize a project using the command `polyaxon init`.

> For more details about this command please run `polyaxon init --help`, or check the [command reference](/docs/core/cli/init/)


text:
<?php

namespace yunsong\shop\models;

use frontend\config\App;
use common\models\TraitBaseModel;
use yunsong\user\models\User;
use yunsong\feed\models\Feed;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\helpers\Url;
use yz\shoppingcart\CartPositionInterface;
use yz\shoppingcart\CartPositionTrait;

/**
 * This is the model class for table "{{%product}}".
 *
 * @property integer $id
 * @property string $title
 * @property string $description
 * @property double $price
 * @property string $image
 * @property integer $category_id
 * @property string $shop_name
 * @property integer $created_at
 * @property integer $created_by
 * @property integer $updated_at
 * @property integer $updated_by
 *
 * @property Category $category
 * @property Shop $shopName
 */
class Product extends \yii\db\ActiveRecord implements CartPositionInterface
{
    const PLATFORM_LOCAL = 0;
    const PLATFORM_TAOBAO = 1;
    const PLATFORM_JD = 2;

    public static $platformLabel = [
        self::PLATFORM_LOCAL => '本站',
        self::PLATFORM_TAOBAO => '淘宝',
        self::PLATFORM_JD => '京东',
    ];

    public function getUrl()
    {
        return Url::to(['product/view','id'=>$this->id]);
    }
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%shop_product}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'content', 'price'], 'required'],

            [['description'], 'string','max'=>255],
            [['price'], 'number'],
            [['category_id'], 'integer', 'min' => 1],

            [['created_by','updated_by'], 'integer', 'min' => 1],

            [['title', 'image'], 'string', 'max' => 255],
//            [['shop_name'], 'string', 'max' => 40],

            [['platform'], 'default', 'value' => 0],
            ['buy_link', 'url'],
//            [['platform', 'platform_item_id'], 'unique', 'targetAttribute' => ['platform', 'platform_item_id']],

            ['content','string'],
        ];
    }

    /**
     * @inheritdoc
     */
//    public function attributeLabels()
//    {
//        return [
//            'id' => Yii::t('shop', 'ID'),
//            'title' => Yii::t('shop', 'Title'),
//            'description' => Yii::t('shop', 'Description'),
//            'price' => Yii::t('shop', 'Price'),
//            'image' => Yii::t('shop', 'Image'),
//            'category_id' => Yii::t('shop', 'Category ID'),
//            'shop_name' => Yii::t('shop', 'Shop Name'),
//            'created_at' => Yii::t('shop', 'Created At'),
//            'created_by' => Yii::t('shop', 'Created By'),
//            'updated_at' => Yii::t('shop', 'Updated At'),
//            'updated_by' => Yii::t('shop', 'Updated By'),
//        ];
//    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            $meta = [
                'content' => mb_strcut($this->title.' '.strip_tags($this->description),0,255,'UTF-8'),
                'args' => [
                    'imgs' => [
                        ['path' => $this->image],
                    ],
                    'route' => [
                        '/shop/product/view',
                        'id' => $this->id
                    ],
                    'description' => $this->description
                ],
                'action'=>App::ACTION_TYPE_SHOP_PRODUCT_CREATE,
                'obj_type'=>App::OBJ_SHOP_PRODUCT,
                'obj_id'=>$this->id,
                'author_id'=>$this->created_by,
            ];
            Feed::add($meta);
        }
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
//    public function getShopName()
//    {
//        return $this->hasOne(Shop::className(), ['name' => 'shop_name']);
//    }

    public function getAuthor()
    {
        return $this->hasOne(User::className(), ['id' => 'created_by']);
    }

    /* END OF GII GENERATED CODE */
    /* END OF GII GENERATED CODE */
    /* END OF GII GENERATED CODE */

    use CartPositionTrait;

    public function getPrice()
    {
        return $this->price;
    }

    public function getId()
    {
        return $this->id;
    }

    /**
     * Automatically insert created_at, created_by, updated_at, updated_by
     * @see \yii\base\Component::behaviors()
     */
    public function behaviors()
    {
        return [
//            'blameable' => BlameableBehavior::className(),
            'timestamp' => TimestampBehavior::className(),
        ];
    }

}


text:
<?php
/**
 * Opauth Strategy
 * - Individual strategies to be extended from this class
 *
 */
class OpauthStrategy{

/**
 * Compulsory config keys, listed as unassociative arrays
 * eg. array('app_id', 'app_secret');
 */
	public $expects;

/**
 * Optional config keys with respective default values, listed as associative arrays
 * eg. array('scope' => 'email');
 */
	public $defaults;

/**
 * Auth array, containing results after successful authentication
 */
	public $auth;

/**
 * Name of strategy
 */
	public $name = null;

/**
 * Pointer to Opauth instance
 */
	protected $Opauth;

/**
 * Configurations and settings unique to a particular strategy
 */
	protected $strategy;

	public function __construct(&$Opauth, $strategy){
		$this->Opauth = $Opauth;
		$this->strategy = $strategy;

		// Include some useful values from Opauth's env
		$this->strategy['_opauth_callback_url'] = $this->Opauth->env['host'].$this->Opauth->env['Callback.uri'];

		if ($this->name === null){
			$this->name = (isset($name) ? $name : get_class($this));
		}

		if (is_array($this->expects)){
			foreach ($this->expects as $key){
				$this->expects($key);
			}
		}

		if (is_array($this->defaults)){
			foreach ($this->defaults as $key => $value){
				$this->optional($key, $this->Opauth->envReplace($value));
			}
		}
	}

/**
 * Auth request
 * aka Log in or Register
 */
	public function request(){
	}

/**
 * Packs $auth nicely and send to Callback.uri, ships $auth either via GET, POST or session.
 * Set shipping transport via Callback.transport config, default being session.
 */
	public function callback(){
		$timestamp = date('c');

		// Object doesn't translate very well when going through HTTP
		$this->auth = $this->recursiveGetObjectVars($this->auth);

		$params = array(
			'auth' => $this->auth,
			'timestamp' => $timestamp,
			'signature' => $this->sign($timestamp)
		);

		$transport = $this->Opauth->env['Callback.transport'];

		switch($transport){
			case 'get':
				$this->redirect($this->Opauth->env['Callback.uri'].'?'.http_build_query($params));
				break;
			case 'post':
				$this->clientPost($this->Opauth->env['Callback.uri'], $params);
				break;
			case 'session':
			default:
				session_start();
				$_SESSION['opauth'] = $params;
				$this->redirect($this->Opauth->env['Callback.uri']);
		}
	}

/**
 * Call an action from a defined strategy
 *
 * @param string $action Action name to call
 * @param string $defaultAction If an action is not defined in a strategy, calls $defaultAction
 */
	public function callAction($action, $defaultAction = 'request'){
		if (method_exists($this, $action)) return $this->{$action}();
		else return $this->{$defaultAction}();
	}

/**
 * Ensures that a compulsory value is set, throws an error if it's not set
 *
 * @return mixed The loaded value
 */
	protected function expects($key, $not = null){
		if (!array_key_exists($key, $this->strategy)){
			trigger_error($this->name." config parameter for \"$key\" expected.", E_USER_ERROR);
			exit();
		}

		$value = $this->strategy[$key];
		if (empty($value) || $value == $not){
			trigger_error($this->name." config parameter for \"$key\" expected.", E_USER_ERROR);
			exit();
		}

		return $value;
	}

/**
 * Loads a default value into $strategy if the associated key is not found
 *
 * @return mixed The loaded value
 */
	protected function optional($key, $default = null){
		if (!array_key_exists($key, $this->strategy)){
			$this->strategy[$key] = $default;
			return $default;
		}

		else return $this->strategy[$key];
	}

/**
 * Redirect to $url with HTTP header
 */
	protected function redirect($url, $exit = true){
		header("Location: $url");
		if ($exit) exit();
	}

/**
 * Simple HTTP request with file_get_contents
 * - Reluctant to use cURL at the moment for not wanting to add an additional dependency unless necessary
 *
 * @param $url Full URL to load
 * @param $options array with context of file_get_contents
 * @return string Content of destination, without headers
 */
	protected function httpRequest($url, $options = null){
		$context = null;
		if (!empty($options) && is_array($options)){
			$context = stream_context_create($options);
		}

		return file_get_contents($url, false, $context);
	}

/**
 * Security: Sign $auth before redirecting to Callback.uri
 *
 * @param $timestamp ISO 8601 formatted date
 * @return string Resulting signature
 */
	protected function sign($timestamp = null){
		if (is_null($timestamp)) $timestamp = date('c');

		$input = sha1(print_r($this->auth, true));
		$hash = $this->hash($input, $timestamp, $this->Opauth->env['Security.iteration'], $this->Opauth->env['Security.salt']);

		return $hash;
	}

/**
 * Static hashing funciton
 *
 * @param string $input Input string
 * @param string $timestamp ISO 8601 formatted date *
 * @param int $iteration Number of hash interations
 * @param string $salt
 * @return string Resulting hash
 */
	public static function hash($input, $timestamp, $iteration, $salt){
		$iteration = intval($iteration);
		if ($iteration <= 0) return false;

		for ($i = 0; $i < $iteration; ++$i) $input = base_convert(sha1($input.$salt.$timestamp), 16, 36);
		return $input;
	}

/**
* Recursively converts object into array
*/
	protected static function recursiveGetObjectVars($obj){
		$_arr = is_object($obj) ? get_object_vars($obj) : $obj;
		foreach ($_arr as $key => $val){
			$val = (is_array($val) || is_object($val)) ? self::recursiveGetObjectVars($val) : $val;
			$arr[$key] = $val;
		}

		return $arr;
	}

/**
 * Recursively converts multidimensional array into POST-friendly single dimensional array
 */
	protected static function flattenArray($array, $prefix = null, $results = array()){
		//if (is_null($prefix)) $prefix = 'array';

		foreach ($array as $key => $val){
			$name = (empty($prefix)) ? $key : $prefix."[$key]";

			if (is_array($val)){
				$results = array_merge($results, self::flattenArray($val, $name));
			}
			else{
				$results[$name] = $val;
			}
		}

		return $results;
	}

/**
 * Generates a simple HTML form with $params initialized and post results via JavaScript
 */
	protected static function clientPost($url, $params = array()){
		$html = '<form name="auth" method="post" action="'.$url.'">';

		if (!empty($params) && is_array($params)){
			$flat = self::flattenArray($params);
			foreach ($flat as $key => $value){
				$html .= '<input type="hidden" name="'.$key.'" value="'.$value.'">';
			}
		}

		$html .= '</form>';
		$html .= '';
		$html .= '';
		echo $html;
	}
}


text:
{% from "_macros.html" import form_group_field %}
{% extends "base.html" %}
{% block content %}
    <form class="form-horizontal" action="" method="post">
        {{form.hidden_tag()}}
        <fieldset>
            <legend>Select a new password:</legend>

            {{form_group_field(form.password, size=20, maxlength=256)}}
            {{form_group_field(form.confirm_password, size=20, maxlength=256)}}

        </fieldset>
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary">Change Password</button>
        </div>
    </form>
{% endblock %}


text:
package dao;

import java.util.List;

import model.History;

public interface HistoryDAO {

	//thêm mới một lịch sử mua hàng.
	public void addHistory(History h);

	//lọc lịch sử của khách hàng.
	public List<History> getList(int user_id);

}


text:
<?php

/**
 * namespace de localizacao do nosso controller
 */
namespace Contato\Controller;

// import ZendMvc
use Zend\Mvc\Controller\AbstractActionController;

// import ZendView
use Zend\View\Model\ViewModel;

// import de ContatoForm
use Contato\Form\ContatoForm;

// import ModelContato
use Contato\Model\Contato;

class ContatosController extends AbstractActionController
{
    protected $contatoTable;

    // GET /contatos
    public function indexAction()
    {
        // colocar parametros da url em um array
        $paramsUrl = [
            'pagina_atual'  => $this->params()->fromQuery('pagina', 1),
            'itens_pagina'  => $this->params()->fromQuery('itens_pagina', 10),
            'coluna_nome'   => $this->params()->fromQuery('coluna_nome', 'nome'),
            'coluna_sort'   => $this->params()->fromQuery('coluna_sort', 'ASC'),
            'search'        => $this->params()->fromQuery('search', null),
        ];

        // configurar método de paginação
        $paginacao = $this->getContatoTable()->fetchPaginator(
                /* $pagina */           $paramsUrl['pagina_atual'],
                /* $itensPagina */      $paramsUrl['itens_pagina'],
                /* $ordem */            "{$paramsUrl['coluna_nome']} {$paramsUrl['coluna_sort']}",
                /* $search */           $paramsUrl['search'],
                /* $itensPaginacao */   5
        );

        // retonar paginação mais os params de url para view
        return new ViewModel(['contatos' => $paginacao] + $paramsUrl);
    }

    // GET /contatos/novo
    public function novoAction()
    {
        return ['formContato' => new ContatoForm()];
    }

    // POST /contatos/adicionar
    public function adicionarAction()
    {
        // obtém a requisição
        $request = $this->getRequest();

        // verifica se a requisição é do tipo post
        if ($request->isPost()) {
            // instancia formulário
            $form = new ContatoForm();
            // instancia model contato com regras de filtros e validações
            $modelContato = new Contato();
            // passa para o objeto formulário as regras de filtros e validações
            // contidas na entity contato
            $form->setInputFilter($modelContato->getInputFilter());
            // passa para o objeto formulário os dados vindos da submissão
            $form->setData($request->getPost());

            // verifica se o formulário segue a validação proposta
            if ($form->isValid()) {
                // aqui vai a lógica para adicionar os dados à tabela no banco
                // 1 - popular model com valores do formulário
                $modelContato->exchangeArray($form->getData());
                // 2 - persistir dados do model para banco de dados
                $this->getContatoTable()->save($modelContato);

                // adicionar mensagem de sucesso
                $this->flashMessenger()
                        ->addSuccessMessage("Contato criado com sucesso!");

                // redirecionar para action index no controller contatos
                return $this->redirect()->toRoute('contatos');
            } else { // em caso da validação não seguir o que foi definido

                // renderiza para action novo com o objeto form populado,
                // com isso os erros serão tratados pelo helpers view
                return (new ViewModel())
                                ->setVariable('formContato', $form)
                                ->setTemplate('contato/contatos/novo');
            }
        }
    }

    // GET /contatos/detalhes/id
    public function detalhesAction()
    {
        // filtra id passado pela url
        $id = (int) $this->params()->fromRoute('id', 0);

        // se id = 0 ou não informado redirecione para contatos
        if (!$id) {
            // adicionar mensagem
            $this->flashMessenger()->addMessage("Contato não encotrado");

            // redirecionar para action index
            return $this->redirect()->toRoute('contatos');
        }

        try {
            // aqui vai a lógica para pegar os dados referente ao contato
            // 1 - solicitar serviço para pegar o model responsável pelo find
            // 2 - solicitar form com dados desse contato encontrado
            // formulário com dados preenchidos
            // lógica cache objeto contatos
            $nome_cache_contato_id = "nome_cache_contato_{$id}";
            if (!$this->cache()->hasItem($nome_cache_contato_id)) {
                $contato = $this->getContatoTable()->find($id);

                $this->cache()->setItem($nome_cache_contato_id, $contato);
            } else {
                $contato = $this->cache()->getItem($nome_cache_contato_id);
            }
        } catch (Exception $exc) {
            // adicionar mensagem
            $this->flashMessenger()->addErrorMessage($exc->getMessage());

            // redirecionar para action index
            return $this->redirect()->toRoute('contatos');
        }

        // dados eviados para detalhes.phtml
        return (new ViewModel())
        ->setTerminal($this->getRequest()->isXmlHttpRequest())
        ->setVariable('contato', $contato);
    }

    // GET /contatos/editar/id
    // GET /contatos/editar/id
    public function editarAction()
    {
        // filtra id passsado pela url
        $id = (int) $this->params()->fromRoute('id', 0);

        // se id = 0 ou não informado redirecione para contatos
        if (!$id) {
            // adicionar mensagem de erro
            $this->flashMessenger()->addMessage("Contato não encotrado");

            // redirecionar para action index
            return $this->redirect()->toRoute('contatos');
        }

        try {
            // variável com objeto contato localizado
            $contato = (array) $this->getContatoTable()->find($id);
        } catch (Exception $exc) {
            // adicionar mensagem
            $this->flashMessenger()->addErrorMessage($exc->getMessage());

            // redirecionar para action index
            return $this->redirect()->toRoute('contatos');
        }

        // objeto form contato vazio
        $form = new ContatoForm();
        // popula objeto form contato com objeto model contato
        $form->setData($contato);

        // dados eviados para editar.phtml
        return ['formContato' => $form];
    }

// POST /contatos/editar/id
    public function atualizarAction()
    {
        // obtém a requisição
        $request = $this->getRequest();

        // verifica se a requisição é do tipo post
        if ($request->isPost()) {
            // instancia formulário
            $form = new ContatoForm();
            // instancia model contato com regras de filtros e validações
            $modelContato = new Contato();
            // passa para o objeto formulário as regras de viltros e validações
            // contidas na entity contato
            $form->setInputFilter($modelContato->getInputFilter());
            // passa para o objeto formulário os dados vindos da submissão
            $form->setData($request->getPost());

            // verifica se o formulário segue a validação proposta
            if ($form->isValid()) {
                // aqui vai a lógica para atualizar os dados à tabela no banco
                // 1 - popular model com valores do formulário
                $modelContato->exchangeArray($form->getData());
                // 2 - atualizar dados do model para banco de dados
                $this->getContatoTable()->update($modelContato);

                // adicionar mensagem de sucesso
                $this->flashMessenger()
                        ->addSuccessMessage("Contato editado com sucesso");

                $nome_cache_contato_id = "nome_cache_contato_{$modelContato->id}";
                if ($this->cache()->hasItem($nome_cache_contato_id)) {
                    $this->cache()->removeItem($nome_cache_contato_id);
                }

                // redirecionar para action detalhes
                return $this->redirect()->toRoute('contatos', array("action" => "detalhes", "id" => $modelContato->id));
            } else { // em caso da validação não seguir o que foi definido
                // renderiza para action editar com o objeto form populado,
                // com isso os erros serão tratados pelo helpers view
                return (new ViewModel())
                                ->setVariable('formContato', $form)
                                ->setTemplate('contato/contatos/editar');
            }
        }
    }

    // DELETE /contatos/deletar/id
    public function deletarAction()
    {
        // filtra id passsado pela url
        $id = (int) $this->params()->fromRoute('id', 0);

        // se id = 0 ou não informado redirecione para contatos
        if (!$id) {
            // adicionar mensagem de erro
            $this->flashMessenger()->addMessage("Contato não encotrado");
        } else {
            // aqui vai a lógica para deletar o contato no banco
            // 1 - solicitar serviço para pegar o model responsável pelo delete
            // 2 - deleta contato
            $this->getContatoTable()->delete($id);

            // adicionar mensagem de sucesso
            $this->flashMessenger()->addSuccessMessage("Contato de ID $id deletado com sucesso");
        }

            // redirecionar para action index
        return $this->redirect()->toRoute('contatos');
    }

    /**
    * Metodo privado para obter instacia do Model ContatoTable
    *
    * @return ContatoTable
    */
    private function getContatoTable()
    {
        // adicionar service ModelContato a variável de classe
        if (!$this->contatoTable) {
            $this->contatoTable = $this->getServiceLocator()->get('ModelContato');
        }

        // return variável de classe com service ModelContato
        return $this->contatoTable;
    }

    // GET /contatos/search?query=[nome]
    public function searchAction()
    {
        $nome = $this->params()->fromQuery('query', null);
        if (isset($nome)) {
            $result = $this->getContatoTable()->search($nome);
        } else  {
            $result = [];
        }

        return new \Zend\View\Model\JsonModel($result);
    }
}


text:
package egovframework.com.ext.oauth.service.impl;

import egovframework.com.cmm.LoginVO;
import egovframework.com.ext.oauth.service.EgovSignupService;
import egovframework.com.uss.umt.service.MberManageVO;
import egovframework.com.uss.umt.service.impl.MberManageDAO;
import egovframework.com.utl.fcc.service.EgovStringUtil;
import egovframework.com.utl.sim.service.EgovFileScrty;

import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;

import javax.annotation.Resource;

import org.springframework.social.connect.UserProfile;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.WebRequest;

/**
 * 소셜 계정으로 일반회원 가입을 처리하는 컨트롤러 클래스
 * @author 이기하
 * @since 2014.10.08
 * @version 1.0
 * @see
 *
 * <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일     	수정자          수정내용
 *  -----------    --------    ---------------------------
 *  2014.10.08		이기하          최초 생성
 *  </pre>
 */

@Service("signupService")
public class EgovSignupServiceImpl extends EgovAbstractServiceImpl implements EgovSignupService {

	@Resource(name="mberManageDAO")
	private MberManageDAO mberManageDAO;

	/**
	 * 소셜 계정으로 일반회원 가입을 처리한다
	 * @param UserProfile profile
	 * @param WebRequest request
	 * @param String key
	 * @return String
	 * @exception Exception
	 */
	@Override
	public String signup(UserProfile profile, WebRequest request, String key) throws Exception {

		String result = null;

		key = EgovStringUtil.replace(key, "facebook", "F");
		key = EgovStringUtil.replace(key, "twitter", "T");

		if (mberManageDAO.selectMber(key) == null) {
			MberManageVO mberManageVO = new MberManageVO();

			mberManageVO.setUniqId(key);
			mberManageVO.setMberId(key);

			if (profile.getLastName() != null) {
				mberManageVO.setMberNm(profile.getFirstName() + " " + profile.getLastName());
			} else {
				mberManageVO.setMberNm(profile.getFirstName());
			}

			// 필수사항
			mberManageVO.setPassword(EgovStringUtil.getRandomStr("a".charAt(0), "z".charAt(0)));
			mberManageVO.setZip("000000");
			mberManageVO.setAdres("소셜로그인");
			mberManageVO.setAreaNo("00");
			mberManageVO.setMiddleTelno("000");
			mberManageVO.setMoblphonNo("0000-0000");
			mberManageVO.setEndTelno("0000");

			// 선택사항
			mberManageVO.setMberSttus("P");
			mberManageVO.setMberEmailAdres(profile.getEmail());	// facebook만 가능 twitter은 불가
			mberManageVO.setGroupId("GROUP_00000000000000");

			//패스워드 암호화
			String pass = EgovFileScrty.encryptPassword(mberManageVO.getPassword(), mberManageVO.getMberId());
			mberManageVO.setPassword(pass);

			result = mberManageDAO.insertMber(mberManageVO);

		} else {
			result = "true";
		}

		// 1. 소셜 로그인 처리
		LoginVO resultVO = new LoginVO();
		resultVO.setId(key);

		if (profile.getLastName() != null) {
			resultVO.setName(profile.getFirstName() + " " + profile.getLastName());
		} else {
			resultVO.setName(profile.getFirstName());
		}

		resultVO.setEmail(profile.getEmail());

		// 2. 로그인 정보를 세션에 저장
		request.setAttribute("loginVO", resultVO, 1);

		return result;
	}

}


text:
package com.facebook.stetho.inspector.elements.android;

import android.app.Application;

import com.facebook.stetho.common.Util;
import com.facebook.stetho.inspector.elements.DOMProvider;

public class AndroidDOMProviderFactory implements DOMProvider.Factory {
  private final Application mApplication;

  public AndroidDOMProviderFactory(Application application) {
    mApplication = Util.throwIfNull(application);
  }

  @Override
  public DOMProvider create() {
    return new AndroidDOMProvider(mApplication);
  }
}


text:
require("./polyfill");

var maps = {};
var node = require("./node");
var old  = require.extensions[".js"];

// TODO: source maps - Error.prepareStackTrace override

require.extensions[".js"] =
require.extensions[".es6"] = function (m, filename) {
  if (filename.indexOf("node_modules") >= 0) {
    return old.apply(this, arguments);
  }

  var result = node.transformFileSync(filename, {
    sourceMapObject: true
  });

  //maps[filename] = result.map;

  m._compile(result.code, filename);
};


text:
package org.apache.cassandra.db;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.utils.ByteBufferUtil;

/**
 * Exception thrown when we read a column internally that is unknown. Note that
 * this is an internal exception and is not meant to be user facing.
 */
public class UnknownColumnException extends IOException
{
    public final ByteBuffer columnName;

    public UnknownColumnException(String ksName, String cfName, ByteBuffer columnName)
    {
        super(String.format("Unknown column %s in table %s.%s", stringify(columnName), ksName, cfName));
        this.columnName = columnName;
    }

    public UnknownColumnException(CFMetaData metadata, ByteBuffer columnName)
    {
        this(metadata.ksName, metadata.cfName, columnName);
    }

    private static String stringify(ByteBuffer name)
    {
        try
        {
            return UTF8Type.instance.getString(name);
        }
        catch (Exception e)
        {
            return ByteBufferUtil.bytesToHex(name);
        }
    }
}


text:
@interface ___PROJECTNAMEASIDENTIFIER___AppDelegate : NSObject <NSApplicationDelegate>

@property (nonatomic, weak) IBOutlet NSWindow    *window;
@property (nonatomic, weak) IBOutlet CCGLView    *glView;

- (IBAction)toggleFullScreen:(id)sender;

@end


text:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Infrastructure;

namespace Microsoft.AspNetCore.Mvc;

/// <summary>
/// A <see cref="StatusCodeResult"/> that when executed will produce a 204 No Content response.
/// </summary>
[DefaultStatusCode(DefaultStatusCode)]
public class NoContentResult : StatusCodeResult
{
    private const int DefaultStatusCode = StatusCodes.Status204NoContent;

    /// <summary>
    /// Initializes a new <see cref="NoContentResult"/> instance.
    /// </summary>
    public NoContentResult()
        : base(DefaultStatusCode)
    {
    }
}


text:
package sci2s.mrfingerprint;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.ArrayPrimitiveWritable;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.zookeeper.common.IOUtils;

public class LocalStructureCylinder extends LocalStructure {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	public static final int NS = 8;
	public static final int ND = 6;
	public static final int R = 70;
//	public static final double SIGMAS = 9.333333;
	public static final int OMEGA = 50;
	public static final float MINME = 0.6f; //!< Minimum number of matching elements in two matchable cylinders
	public static final float RELSHIFT = 0.5f*(NS+1);
	public static final float MINVC = 0.75f;
	public static final int NEIGHBORHOODRADIUS = 28;
	public static final int RNEIGHBORHOODRADIUS = R+NEIGHBORHOODRADIUS;
	public static final int MINM = 4;
	public static final int NUMCELLS = ND*NS*NS;
	public static final int MAXNVCELLS = (int) Math.floor((1.0-MINVC*(2-4/Math.PI)) * NUMCELLS);
	public static final float ISIGMAD = 1.43239448783f; //1.0/SIGMAD;
	public static final float DELTAD = 1.047197551f; //(2.0*PI)/Nd;
	public static final float GAUSSIANDEN = 0.042743816f; //1.0 / (SIGMAS * sqrt(2*PI));
	public static final float ISIGMASQ2 = 0.005739796f; //1.0 / (2.0*SIGMAS*SIGMAS);
	public static final float MUPSI = 0.01f; //!< Sigmoid parameter 1 for function Psi
	public static final float TAUPSI = 400f; //!< Sigmoid parameter 2 for function Psi
	public static final float DELTAS = (2.0f*R)/NS;
	public static final float DELTAZETA = 1.57079633f;
	public static final byte DELTAZETABYTE = 64;
	public static final int MINCELLS = (int)Math.floor(MINME*NUMCELLS);

	protected float[] cm_vector;

	protected Minutia minutia;
	protected float norm;

	public LocalStructureCylinder() {
		super();

		cm_vector = new float[NUMCELLS];
		minutia = new Minutia();
		norm = 0;
	}

	public LocalStructureCylinder(LocalStructureCylinder lsc) {
		super(lsc);

		cm_vector = Arrays.copyOf(lsc.cm_vector, lsc.cm_vector.length);
		minutia = new Minutia(lsc.minutia);
		norm = lsc.norm;
	}

//	public LocalStructureCylinder(String value) throws LSException {
//
//		StringTokenizer st = new StringTokenizer(value, ";");
//
//		// The first two elements are the FPID and LSID
//		fpid = st.nextToken();
//		lsid = Integer.parseInt(st.nextToken());
//
//		// Then goes the minutia
//		minutia = new Minutia(st.nextToken());
//
//	// Then goes the validity
//	valid = Boolean.parseBoolean(st.nextToken());
//
//	// Then goes the norm
//	norm = Float.parseFloat(st.nextToken());
//
//		// Now only the feature vector remains
//		StringTokenizer stfv = new StringTokenizer(st.nextToken(), " ");
//
//		// The line must have NUMCELLS elements
//		if(stfv.countTokens() != NUMCELLS) {
//			throw new LSException("LocalStructureCylinder(String): error when reading \"" + stfv.toString() + "\": it has " + stfv.countTokens() + " instead of NUMCELLS = " + NUMCELLS);
//		}
//
//		cm_vector = new float[stfv.countTokens()];
//
//		int i = 0;
//
//		while(stfv.hasMoreTokens()) {
//			cm_vector[i] = Float.parseFloat(stfv.nextToken());
//			i++;
//		}
//
//		computeNorm();
//	}

	public LocalStructureCylinder(String fpid, int lsid) {

		super(fpid,lsid);

		cm_vector = new float[NUMCELLS];
		minutia = new Minutia();
		norm = 0;
	}

	public LocalStructureCylinder(String fpid, int lsid, ArrayList<Minutia> minutiae, int minutia_id) {

		super(fpid,lsid);
		cm_vector = new float[NUMCELLS];

		minutia = new Minutia(minutiae.get(minutia_id));

		Point [] convex = MonotoneChain.convex_hull(minutiae);

		int count = 0;

		for (int i=1, pos = 0; i<=NS; i++)
			for (int j=1; j<=NS; j++)
			{
				float [] abscoord = pij(i,j);

				if (xiM(abscoord[0],abscoord[1],convex))
				{
					for (int k=1; k<=ND; k++, pos++)
						cm_vector[pos] = cm(abscoord[0],abscoord[1],k,minutiae,convex);
				}
				else
				{
					for (int k=1; k<=ND; k++, pos++)
						cm_vector[pos] = -1;

					count += ND;
				}
			}

		if (count >= MAXNVCELLS)
		{
			norm = -1;
		}
		else
		{
			count = 0;
			int coordx = minutia.getX();
			int coordy = minutia.getY();
			for (int jj=0; count < MINM && (count+minutiae.size()-jj) >= MINM && jj<minutiae.size(); jj++)
				if (minutiae.get(jj).getSDistance(coordx, coordy) <= RNEIGHBORHOODRADIUS*RNEIGHBORHOODRADIUS)
					count++;

			if(count >= MINM)
				computeNorm();
			else
				norm = -1;
		}
	}

	protected void computeNorm() {

		double sum = 0;

		for (int i=0; i<NUMCELLS; i++)
			if(cm_vector[i] > 0)
				sum += Util.square(cm_vector[i]);

		norm = (float) Math.sqrt(sum);
	}

	public float cm(float i, float j, int k, ArrayList<Minutia> minutiae, Point[] convex)
	{
		float sum = 0.0f;
		byte angle = minutia.getbT();
		byte dfikk = dFikb(k);

		for (Minutia min : minutiae)
			if (minutia.index != min.index && min.getSDistance(i,j) <= NEIGHBORHOODRADIUS*NEIGHBORHOODRADIUS)
				sum += contributionS(min, i, j) * contributionD(min, angle, dfikk);

		return Util.psi(sum, MUPSI, TAUPSI);
	}

	public float [] pij(int i, int j)
	{
		float relative_i = i - RELSHIFT;
		float relative_j = j - RELSHIFT;
		float cosT = (float) Math.cos(minutia.getrT());
		float sinT = (float) Math.sin(minutia.getrT());

		float [] res = new float[2];

		res[0] = DELTAS * (cosT*relative_i + sinT*relative_j) + minutia.getX();
		res[1] = DELTAS * (cosT*relative_j - sinT*relative_i) + minutia.getY();

		return res;
	}

	public boolean xiM(float i, float j, Point [] convex)
	{
	    if (minutia.getSDistance(i,j) > R*R) {
	        return false;
	    } else {
	        if (pnpoly(convex,i,j)) {
	            return true;
	        } else {

	            int last = convex.length - 1;

	            if (Util.DistanceFromLine(i,j,convex[last].x,convex[last].y,convex[0].x,convex[0].y) > OMEGA) {
	                for (int k=0; k<last; k++) {
	                    if (Util.DistanceFromLine(i,j,convex[k].x,convex[k].y,convex[k+1].x,convex[k+1].y) <= OMEGA) {
	                        return true;
	                    }
	                }

	                return false;
	            } else {
	                return true;
	            }
	        }
	   }
	}

	public static boolean pnpoly(Point [] convex, double testx, double testy)
	{
		double pivote;
		int last = convex.length-1;
		boolean right;

		pivote = (testy-convex[last].y)*(convex[0].x-convex[last].x) -
							(testx-convex[last].x)*(convex[0].y-convex[last].y);

		if(pivote == 0.0)
			return true;

		right = (pivote < 0);

		for (int i=0; i<last; i++) {
			pivote = (testy-convex[i].y)*(convex[i+1].x-convex[i].x) - (testx-convex[i].x)*(convex[i+1].y-convex[i].y);

			if ((pivote < 0 && !right) || (pivote > 0 && right))
				return false;
			else if(pivote == 0)
				return true;
		}

		return true;
	}

    static float dFik(int k)
    {
        return (float) ((k - 0.5f)*DELTAD - Math.PI);
    }

    static byte dFikb(int k)
    {
        return (byte) ((k - 0.5)*256/ND - 128);
    }

    static float contributionS(Minutia min, float p_i, float p_j)
    {
        return (float) (GAUSSIANDEN / Math.exp(min.getSDistance(p_i,p_j)*ISIGMASQ2));
    }

    static float contributionD(Minutia min, float angle, float k_angle)
    {
    	float alpha = Util.dFiMCC(Util.dFiMCC(angle, min.getrT()), k_angle) * ISIGMAD;

    	/*Area of the curve computation*/
    	return Util.doLeft(alpha + 0.5f) - Util.doLeft(alpha - 0.5f);
    }

    static float contributionD(Minutia min, byte angle, byte k_angle)
    {
    	float alpha = (float) (Util.dFi256(Util.dFi256(angle, min.getbT()), k_angle) * ISIGMAD * Math.PI/128);

    	/*Area of the curve computation*/
    	return Util.doLeft(alpha + 0.5f) - Util.doLeft(alpha - 0.5f);
    }

	public Minutia getMinutia() {
		return new Minutia(minutia);
	}

	protected Minutia getMinutiaRef() {
		return minutia;
	}

	public static <T extends LocalStructure> T [] extractLocalStructures(Class<T> lsclass, String encoded) {
		String fpid = decodeFpid(encoded);
		ArrayList<Minutia> minutiae = decodeTextMinutiae(encoded);

		return extractLocalStructures(lsclass, fpid, minutiae);
	}

	public static LocalStructureCylinder [] extractLocalStructures(String fpid, ArrayList<Minutia> minutiae) {

		LocalStructureCylinder [] ls = new LocalStructureCylinder[minutiae.size()];

		for(int i = 0; i < minutiae.size(); i++)
			ls[i] = new LocalStructureCylinder(fpid, i, minutiae, i);

		return ls;
	}

	@Override
	public void write(DataOutput out) throws IOException {

		super.write(out);

		ArrayPrimitiveWritable ow = new ArrayPrimitiveWritable(cm_vector);

		ow.write(out);
		minutia.write(out);
		out.writeFloat(norm);
	}

	@Override
	public void readFields(DataInput in) throws IOException {

		super.readFields(in);

		ArrayPrimitiveWritable ow = new ArrayPrimitiveWritable(cm_vector);

		ow.readFields(in);
		cm_vector = (float[]) ow.get();

		minutia.readFields(in);
		norm = in.readFloat();

	}

	@Override
	public String toString() {

		String result = super.toString() + ";" + minutia.toString() + ";" + norm + ";";

		for(float i : cm_vector)
			result = result + " " + i;

		return result;
	}

	@Override
	public boolean isValid() {
		return (norm >= 0);
	}

	@Override
	public float similarity(LocalStructure ls) throws LSException
	{
		int count = 0;
		float norm_diff = 0;
		float ca_b, cb_a;

		if(!(ls instanceof LocalStructureCylinder))
			throw new LSException("The similarity can only be computed for local structures of the same type");

		LocalStructureCylinder lsc = (LocalStructureCylinder) ls;

		if(norm < 0 || lsc.norm < 0)
			return -1;

		if (Math.abs(Util.dFi256(minutia.getbT(),lsc.minutia.getbT())) > DELTAZETABYTE)
			return 0;

		for (int i=0; i<NUMCELLS; i++)
		{
			ca_b = cm_vector[i];
			cb_a = lsc.cm_vector[i];

			if (ca_b>=0 && cb_a>=0)
			{
				count++;
				norm_diff += Util.square(ca_b-cb_a);
			}
		}

		//Check if two cylinders are matchable
		if(count >= MINCELLS)
			return (float) (1.0 - (Math.sqrt(norm_diff)/(norm+lsc.norm)));
		else
			return 0;
	}

	@Override
	public ArrayWritable newArrayWritable(LocalStructure[] ails) {
		return new LSCylinderArray(ails);
	}

	@Override
	public ArrayWritable newArrayWritable() {
		return new LSCylinderArray();
	}

	public static LocalStructureCylinder [][] loadLSMapFile(Configuration conf) {

		String name = conf.get(Util.MAPFILENAMEPROPERTY, Util.MAPFILEDEFAULTNAME);
    	MapFile.Reader lsmapfile = Util.createMapFileReader(conf, name);

    	LocalStructureCylinder [][] result = null;

		WritableComparable<?> key = (WritableComparable<?>) ReflectionUtils.newInstance(lsmapfile.getKeyClass(), conf);

		LSCylinderArray value = (LSCylinderArray) ReflectionUtils.newInstance(lsmapfile.getValueClass(), conf);

		try {
			while(lsmapfile.next(key, value)) {
				result = (LocalStructureCylinder [][]) ArrayUtils.add(result,
						Arrays.copyOf(value.get(), value.get().length, LocalStructureCylinder[].class));
			}
		} catch (Exception e) {
			System.err.println("LocalStructureCylinder.loadLSMapFile: unable to read fingerprint "
					+ key + " in MapFile " + name + ": " + e.getMessage());
			e.printStackTrace();
		}

		IOUtils.closeStream(lsmapfile);

		return result;
	}

	public static void saveLSMapFile(LocalStructure[][] inputls, Configuration conf) {

		String name = conf.get(Util.MAPFILENAMEPROPERTY, Util.MAPFILEDEFAULTNAME);

    	MapFile.Writer lsmapfile = Util.createMapFileWriter(conf, name, Text.class, inputls[0][0].newArrayWritable().getClass());

    	Arrays.sort(inputls, new Comparator<LocalStructure[]>() {
		   public int compare(LocalStructure [] als1, LocalStructure [] als2) {
		      return als1[0].getFpid().compareTo(als2[0].getFpid());
		   }
		});

    	Text fpid = new Text();
    	ArrayWritable aw = null;

		for(LocalStructure [] ails : inputls) {
			fpid.set(ails[0].getFpid());

		    try {
		    	aw = ails[0].newArrayWritable(ails);
		    	lsmapfile.append(fpid, aw);
			} catch (IOException e) {
				System.err.println("LocalStructureCylinder.saveLSMapFile: unable to save fingerprint "
						+ fpid.toString() + " in MapFile " + name + ": " + e.getMessage());
				e.printStackTrace();
			}
		}

		IOUtils.closeStream(lsmapfile);

	}

}


text:
package sasl

import (
	"golang.org/x/net/context"
)

// unexported to prevent collisions with context keys defined in
// other packages.
type _key int

// If this package defined other context keys, they would have
// different integer values.
const (
	statusKey _key = iota
)

func withStatus(ctx context.Context, s statusType) context.Context {
	return context.WithValue(ctx, statusKey, s)
}

func statusFrom(ctx context.Context) statusType {
	s, ok := ctx.Value(statusKey).(statusType)
	if !ok {
		panic("missing status in context")
	}
	return s
}


text:
module Avalon
	require 'avalon-workflow/version'
	require 'avalon/workflow'
#	autoload :Workflow
end


text:
package se.bjurr.gitchangelog.semantic;

import static org.assertj.core.api.Assertions.assertThat;
import static se.bjurr.gitchangelog.api.GitChangelogApi.gitChangelogApiBuilder;
import static se.bjurr.gitchangelog.internal.semantic.SemanticVersioning.VERSION_STEP.MAJOR;
import static se.bjurr.gitchangelog.internal.semantic.SemanticVersioning.VERSION_STEP.MINOR;
import static se.bjurr.gitchangelog.internal.semantic.SemanticVersioning.VERSION_STEP.NONE;
import static se.bjurr.gitchangelog.internal.semantic.SemanticVersioning.VERSION_STEP.PATCH;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import se.bjurr.gitchangelog.api.GitChangelogApi;
import se.bjurr.gitchangelog.internal.semantic.SemanticVersion;
import se.bjurr.gitchangelog.internal.semantic.SemanticVersioning;
import se.bjurr.gitchangelog.internal.semantic.SemanticVersioning.VERSION_STEP;

public class SemanticVersioningTest {

  private List<String> tags;
  private List<String> commits;
  private String majorPattern;
  private String minorPattern;
  private String patchPattern;
  private SemanticVersioning sut;

  @Before
  public void before() {
    this.tags = new ArrayList<>();
    this.commits = new ArrayList<>();
    this.majorPattern = null;
    this.minorPattern = "[Uu]pdate:.*";
    this.patchPattern = null;
    this.sut =
        new SemanticVersioning(
            this.tags, this.commits, this.majorPattern, this.minorPattern, this.patchPattern);
  }

  @Test
  public void smokeTest1() throws Throwable {
    final GitChangelogApi builder1 =
        gitChangelogApiBuilder() //
            .withToCommit("7c1c366") //
            .withSemanticMajorVersionPattern("breaking:.*") //
            .withSemanticMinorVersionPattern("update:.*");

    assertThat(builder1.getNextSemanticVersion().toString()).isEqualTo("1.144.5");
    assertThat(builder1.getNextSemanticVersion().getVersionStep()).isEqualTo(PATCH);

    final GitChangelogApi builder2 =
        gitChangelogApiBuilder() //
            .withToCommit("7c1c366") //
            .withSemanticMajorVersionPattern("breaking:.*") //
            .withSemanticMinorVersionPattern("update:.*");
    assertThat(builder2.getHighestSemanticVersion().toString()).isEqualTo("1.144.4");
    assertThat(builder2.getNextSemanticVersion().getVersionStep()).isEqualTo(VERSION_STEP.PATCH);
  }

  @Test
  public void smokeTest2() throws Throwable {
    final SemanticVersion nextSemanticVersion =
        gitChangelogApiBuilder()
            .withToRef("1.155.0") //
            .withSemanticMajorVersionPattern("^[Bb]reaking.*")
            .withSemanticMinorVersionPattern("^[Ff]eat.*")
            .getNextSemanticVersion();
    assertThat(nextSemanticVersion.toString()).isEqualTo("1.155.1");
    assertThat(nextSemanticVersion.getVersionStep()).isEqualTo(PATCH);
  }

  @Test
  public void testMajorStep() throws Throwable {
    this.tags.add("v1.0.0");
    this.commits.add("breaking: whatever");

    final SemanticVersion highestVersion = SemanticVersioning.getHighestVersion(this.tags);
    assertThat(highestVersion + " -> " + this.sut.getNextVersion(highestVersion)) //
        .isEqualTo("1.0.0 -> 2.0.0");
    assertThat(this.sut.getNextVersion(highestVersion).getVersionStep()).isEqualTo(MAJOR);
  }

  @Test
  public void testMajorExclamation() throws Throwable {
    this.tags.add("v1.0.0");
    this.commits.add("feat!: whatever");

    final SemanticVersion highestVersion = SemanticVersioning.getHighestVersion(this.tags);
    assertThat(highestVersion + " -> " + this.sut.getNextVersion(highestVersion)) //
        .isEqualTo("1.0.0 -> 2.0.0");
    assertThat(this.sut.getNextVersion(highestVersion).getVersionStep()).isEqualTo(MAJOR);
  }

  @Test
  public void testMajorBreaking() throws Throwable {
    this.tags.add("v1.0.0");
    this.commits.add("feat: whatever\n\nBREAKING CHANGE: this is a text");

    final SemanticVersion highestVersion = SemanticVersioning.getHighestVersion(this.tags);
    final SemanticVersion nextVersion = this.sut.getNextVersion(highestVersion);
    assertThat(highestVersion + " -> " + nextVersion) //
        .isEqualTo("1.0.0 -> 2.0.0");
    assertThat(nextVersion.getVersionStep()).isEqualTo(MAJOR);
  }

  @Test
  public void testMinorStep() throws Throwable {
    this.tags.add("v1.0.0");
    this.commits.add("update: whatever");

    final SemanticVersion highestVersion = SemanticVersioning.getHighestVersion(this.tags);
    assertThat(highestVersion + " -> " + this.sut.getNextVersion(highestVersion)) //
        .isEqualTo("1.0.0 -> 1.1.0");
    assertThat(this.sut.getNextVersion(highestVersion).getVersionStep()).isEqualTo(MINOR);
  }

  @Test
  public void testPatchStep() throws Throwable {
    this.tags.add("v1.0.0");
    this.commits.add("chore: whatever");

    final SemanticVersion highestVersion = SemanticVersioning.getHighestVersion(this.tags);
    assertThat(highestVersion + " -> " + this.sut.getNextVersion(highestVersion)) //
        .isEqualTo("1.0.0 -> 1.0.1");
    assertThat(this.sut.getNextVersion(highestVersion).getVersionStep()).isEqualTo(PATCH);
  }

  @Test
  public void testPatchStepWithNoNewCommitsAndNoPattern() throws Throwable {
    this.tags.add("v1.0.0");

    final SemanticVersion highestVersion = SemanticVersioning.getHighestVersion(this.tags);
    assertThat(highestVersion + " -> " + this.sut.getNextVersion(highestVersion)) //
        .isEqualTo("1.0.0 -> 1.0.1");
    assertThat(this.sut.getNextVersion(highestVersion).getVersionStep()).isEqualTo(PATCH);
  }

  @Test
  public void testPatchStepWithNoNewCommitsAndPattern() throws Throwable {
    this.tags.add("v1.0.0");
    this.patchPattern = "fix:.*";
    this.sut =
        new SemanticVersioning(
            this.tags, this.commits, this.majorPattern, this.minorPattern, this.patchPattern);
    final SemanticVersion highestVersion = SemanticVersioning.getHighestVersion(this.tags);
    assertThat(highestVersion + " -> " + this.sut.getNextVersion(highestVersion)) //
        .isEqualTo("1.0.0 -> 1.0.0");
    assertThat(this.sut.getNextVersion(highestVersion).getVersionStep()).isEqualTo(NONE);
  }

  @Test
  public void testPatchStepWithPatternNotMatching() throws Throwable {
    this.tags.add("v1.0.0");
    this.commits.add("chore: whatever");

    final SemanticVersion highestVersion = SemanticVersioning.getHighestVersion(this.tags);
    this.patchPattern = "fix:.*";
    this.sut =
        new SemanticVersioning(
            this.tags, this.commits, this.majorPattern, this.minorPattern, this.patchPattern);
    assertThat(highestVersion + " -> " + this.sut.getNextVersion(highestVersion)) //
        .isEqualTo("1.0.0 -> 1.0.0");
    assertThat(this.sut.getNextVersion(highestVersion).getVersionStep()).isEqualTo(NONE);
  }

  @Test
  public void testPatchStepWithPatternMatching() throws Throwable {
    this.tags.add("v1.0.0");
    this.commits.add("fix: whatever");

    final SemanticVersion highestVersion = SemanticVersioning.getHighestVersion(this.tags);
    this.patchPattern = "fix:.*";
    this.sut =
        new SemanticVersioning(
            this.tags, this.commits, this.majorPattern, this.minorPattern, this.patchPattern);
    assertThat(highestVersion + " -> " + this.sut.getNextVersion(highestVersion)) //
        .isEqualTo("1.0.0 -> 1.0.1");
    assertThat(this.sut.getNextVersion(highestVersion).getVersionStep()).isEqualTo(PATCH);
  }

  @Test
  public void testTagCleanup() throws Throwable {
    assertThat(this.getTagNameFrom("whatever1.2.3.4")).isEqualTo("1.2.3");
    assertThat(this.getTagNameFrom("1.2.3.4whatever")).isEqualTo("1.2.3");
    assertThat(this.getTagNameFrom("1.2.3.4whatever-5.6.7")).isEqualTo("1.2.3");
    assertThat(this.getTagNameFrom("whatever-v1-1.2.3")).isEqualTo("1.2.3");
    assertThat(this.getTagNameFrom("whatever-v1-1.2.3.4")).isEqualTo("1.2.3");
  }

  private String getTagNameFrom(final String tagName) {
    return SemanticVersioning.getHighestVersion(Arrays.asList(tagName)).toString();
  }
}


text:
<?php

require $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php';

use Cbix\Cbix;
use Cbix\CbixException;

$cbix = Cbix::make();

/*
 * Get CBVIX data
 * The Volatility API returns daily historical index volatility data
 */

try {
    $result = $cbix->volatility(['limit' => 10]);
    //var_dump($result);
    foreach ($result->series as $r) {
        echo $r->cbix->hist_vol_30;
    }
} catch (CbixException $e) {
    //There was an error more information in $e->getMessage();
    //var_dump($e->getMessage());
    echo "Something went wrong!";
}


text:
from typing import List, Optional, Union

from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.utils.email import send_email

class EmailOperator(BaseOperator):
    """
    Sends an email.

    :param to: list of emails to send the email to. (templated)
    :type to: list or string (comma or semicolon delimited)
    :param subject: subject line for the email. (templated)
    :type subject: str
    :param html_content: content of the email, html markup
        is allowed. (templated)
    :type html_content: str
    :param files: file names to attach in email
    :type files: list
    :param cc: list of recipients to be added in CC field
    :type cc: list or string (comma or semicolon delimited)
    :param bcc: list of recipients to be added in BCC field
    :type bcc: list or string (comma or semicolon delimited)
    :param mime_subtype: MIME sub content type
    :type mime_subtype: str
    :param mime_charset: character set parameter added to the Content-Type
        header.
    :type mime_charset: str
    """

    template_fields = ('to', 'subject', 'html_content')
    template_ext = ('.html',)
    ui_color = '#e6faf9'

    @apply_defaults
    def __init__(
            self,
            to: Union[List[str], str],
            subject: str,
            html_content: str,
            files: Optional[List] = None,
            cc: Optional[Union[List[str], str]] = None,
            bcc: Optional[Union[List[str], str]] = None,
            mime_subtype: str = 'mixed',
            mime_charset: str = 'utf-8',
            *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.to = to  # pylint: disable=invalid-name
        self.subject = subject
        self.html_content = html_content
        self.files = files or []
        self.cc = cc  # pylint: disable=invalid-name
        self.bcc = bcc
        self.mime_subtype = mime_subtype
        self.mime_charset = mime_charset

    def execute(self, context):
        send_email(self.to, self.subject, self.html_content,
                   files=self.files, cc=self.cc, bcc=self.bcc,
                   mime_subtype=self.mime_subtype, mime_charset=self.mime_charset)