text:
layout: post
title:  "bunch o' books"
date:   2016-04-19 13:59:00 +0100
categories: books, learning
---

https://mitpress.mit.edu/decision-making-under-uncertainty

https://mitpress.mit.edu/books/little-prover

https://mitpress.mit.edu/books/introduction-agent-based-modeling

https://mitpress.mit.edu/books/workflow-patterns

https://mitpress.mit.edu/hci

https://mitpress.mit.edu/emerging

https://mitpress.mit.edu/books/principles-cyber-physical-systems

https://mitpress.mit.edu/books/thinking-things-through-0

https://mitpress.mit.edu/books/structure-and-interpretation-classical-mechanics-0

https://mitpress.mit.edu/books/advanced-structured-prediction

https://mitpress.mit.edu/books/category-theory-sciences

https://mitpress.mit.edu/books/human-robotics

https://mitpress.mit.edu/books/programming-distributed-computing-systems

https://mitpress.mit.edu/books/multiagent-systems-0

https://mitpress.mit.edu/books/machine-learning-0

https://mitpress.mit.edu/books/musimathics-0

https://mitpress.mit.edu/books/markov-random-fields-vision-and-image-processing

https://mitpress.mit.edu/books/modeling-business-processes

https://mitpress.mit.edu/books/metareasoning

https://mitpress.mit.edu/books/introduction-autonomous-mobile-robots

https://mitpress.mit.edu/books/self-reconfigurable-robots

https://mitpress.mit.edu/books/semi-supervised-learning

https://mitpress.mit.edu/books/bio-inspired-artificial-intelligence

https://mitpress.mit.edu/books/quantum-computing-without-magic

https://mitpress.mit.edu/books/robotics-primer

https://mitpress.mit.edu/books/autonomous-bidding-agents

https://mitpress.mit.edu/books/designing-interactions

https://mitpress.mit.edu/books/ontologies-bioinformatics

https://mitpress.mit.edu/books/probabilistic-robotics

https://mitpress.mit.edu/books/molecular-computing

https://mitpress.mit.edu/books/reasoning-about-uncertainty

https://mitpress.mit.edu/books/microarrays-integrative-genomics

https://mitpress.mit.edu/books/immunological-bioinformatics

https://mitpress.mit.edu/books/principles-robot-motion

https://mitpress.mit.edu/books/selfish-routing-and-price-anarchy

https://mitpress.mit.edu/books/cognition-basic-musical-structures

https://mitpress.mit.edu/books/ontological-semantics

https://mitpress.mit.edu/books/introduction-bioinformatics-algorithms

https://mitpress.mit.edu/books/kernel-methods-computational-biology

https://mitpress.mit.edu/books/social-capital-and-information-technology

https://mitpress.mit.edu/books/activity-centered-design

https://mitpress.mit.edu/books/machine-musicianship

https://mitpress.mit.edu/books/virtual-music

https://mitpress.mit.edu/books/evolutionary-robotics

https://mitpress.mit.edu/books/workflow-management

https://mitpress.mit.edu/books/computational-modeling-genetic-and-biochemical-networks

https://mitpress.mit.edu/books/reasoning-about-knowledge

https://mitpress.mit.edu/books/gutenberg-global-information-infrastructure

https://mitpress.mit.edu/books/introduction-distributed-algorithms

https://mitpress.mit.edu/books/participating-explanatory-dialogues

https://mitpress.mit.edu/books/reasoning-about-rational-agents

https://mitpress.mit.edu/books/qualitative-reasoning

https://mitpress.mit.edu/books/foundations-robotics

https://mitpress.mit.edu/books/made-minds

https://mitpress.mit.edu/books/sparse-distributed-memory

https://mitpress.mit.edu/books/neurobiology-neural-networks

https://mitpress.mit.edu/books/psychology-proof

https://mitpress.mit.edu/books/neurotechnology-biomimetic-robots

https://mitpress.mit.edu/books/current-topics-computational-molecular-biology

https://mitpress.mit.edu/books/truth-trash

https://mitpress.mit.edu/books/learning-kernels

https://mitpress.mit.edu/books/strategic-negotiation-multiagent-environments

https://mitpress.mit.edu/books/bioinformatics

https://mitpress.mit.edu/books/advances-evolutionary-synthesis-intelligent-agents

https://mitpress.mit.edu/books/music-cognition-and-computerized-sound

https://mitpress.mit.edu/books/computational-molecular-biology

https://mitpress.mit.edu/books/high-level-vision

https://mitpress.mit.edu/books/heterogeneous-agent-systems

https://mitpress.mit.edu/books/layered-learning-multiagent-systems

https://mitpress.mit.edu/books/neurons-networks-and-motor-behavior

https://mitpress.mit.edu/books/advances-genetic-programming-1

https://mitpress.mit.edu/books/musical-networks

https://mitpress.mit.edu/books/systems-learn-0

https://mitpress.mit.edu/books/melodic-similarity

https://mitpress.mit.edu/books/behavior-based-robotics

https://mitpress.mit.edu/books/philosophical-computer

https://mitpress.mit.edu/books/introduction-fuzzy-sets

https://mitpress.mit.edu/books/invitation-cognitive-science-2

https://mitpress.mit.edu/books/expertise-context

https://mitpress.mit.edu/books/dynamic-patterns

https://mitpress.mit.edu/books/turtles-termites-and-traffic-jams

https://mitpress.mit.edu/books/mental-leaps

https://mitpress.mit.edu/books/language-complexity-game

https://mitpress.mit.edu/books/machine-models-music

https://mitpress.mit.edu/books/actors


text:
.. _pyb.LED:

class LED -- LED object
=======================

The LED object controls an individual LED (Light Emitting Diode).

Constructors
------------

.. class:: pyb.LED(id)

   Create an LED object associated with the given LED:

     - ``id`` is the LED number, 1-4.

Methods
-------

.. method:: led.intensity([value])

   Get or set the LED intensity.  Intensity ranges between 0 (off) and 255 (full on).
   If no argument is given, return the LED intensity.
   If an argument is given, set the LED intensity and return ``None``.

   *Note:* Only LED(3) and LED(4) can have a smoothly varying intensity, and
   they use timer PWM to implement it.  LED(3) uses Timer(2) and LED(4) uses
   Timer(3).  These timers are only configured for PWM if the intensity of the
   relevant LED is set to a value between 1 and 254.  Otherwise the timers are
   free for general purpose use.

.. method:: led.off()

   Turn the LED off.

.. method:: led.on()

   Turn the LED on, to maximum intensity.

.. method:: led.toggle()

   Toggle the LED between on (maximum intensity) and off.  If the LED is at
   non-zero intensity then it is considered "on" and toggle will turn it off.

redpajama_set_name: RedPajamaGithub


text:
package datasource

// A collection of tests to test the storagenode interface


text:
/**
 *
 * Norwegian translation (Nynorsk: no-NN)
 * By Tore Kjørsvik 21-January-2008
 *
 */
Ext.onReady(function (){
if(Ext.Updater) {
    Ext.Updater.defaults.indicatorText = '
Lastar...
';
}

if(Ext.view.View){
  Ext.view.View.prototype.emptyText = "";
}

if(Ext.grid.Panel){
  Ext.grid.Panel.prototype.ddText = "{0} markert(e) rad(er)";
}

if(Ext.TabPanelItem){
  Ext.TabPanelItem.prototype.closeText = "Lukk denne fana";
}

if(Ext.form.field.Base){
  Ext.form.field.Base.prototype.invalidText = "Verdien i dette feltet er ugyldig";
}

if(Ext.LoadMask){
  Ext.LoadMask.prototype.msg = "Lastar...";
}

if(Ext.Date) {
    Ext.Date.monthNames = [
      "Januar",
      "Februar",
      "Mars",
      "April",
      "Mai",
      "Juni",
      "Juli",
      "August",
      "September",
      "Oktober",
      "November",
      "Desember"
    ];

    Ext.Date.getShortMonthName = function(month) {
      return Ext.Date.monthNames[month].substring(0, 3);
    };

    Ext.Date.monthNumbers = {
      Jan : 0,
      Feb : 1,
      Mar : 2,
      Apr : 3,
      Mai : 4,
      Jun : 5,
      Jul : 6,
      Aug : 7,
      Sep : 8,
      Okt : 9,
      Nov : 10,
      Des : 11
    };

    Ext.Date.getMonthNumber = function(name) {
      return Ext.Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
    };

    Ext.Date.dayNames = [
      "Søndag",
      "Måndag",
      "Tysdag",
      "Onsdag",
      "Torsdag",
      "Fredag",
      "Laurdag"
    ];

    Ext.Date.getShortDayName = function(day) {
      return Ext.Date.dayNames[day].substring(0, 3);
    };
}

if(Ext.MessageBox){
  Ext.MessageBox.buttonText = {
    ok     : "OK",
    cancel : "Avbryt",
    yes    : "Ja",
    no     : "Nei"
  };
}

if(Ext.util.Format){
    Ext.apply(Ext.util.Format, {
        thousandSeparator: '.',
        decimalSeparator: ',',
        currencySign: 'kr',  // Norwegian Krone
        dateFormat: 'd.m.Y'
    });
}

if(Ext.picker.Date){
  Ext.apply(Ext.picker.Date.prototype, {
    todayText         : "I dag",
    minText           : "Denne datoen er før tidlegaste tillatne dato",
    maxText           : "Denne datoen er etter seinaste tillatne dato",
    disabledDaysText  : "",
    disabledDatesText : "",
    monthNames	      : Ext.Date.monthNames,
    dayNames		      : Ext.Date.dayNames,
    nextText          : 'Neste månad (Control+Pil Høgre)',
    prevText          : 'Førre månad (Control+Pil Venstre)',
    monthYearText     : 'Velj ein månad (Control+Pil Opp/Ned for å skifte år)',
    todayTip          : "{0} (Mellomrom)",
    format            : "d.m.y",
    startDay          : 1
  });
}

if(Ext.picker.Month) {
  Ext.apply(Ext.picker.Month.prototype, {
      okText            : " OK ",
      cancelText        : "Avbryt"
  });
}

if(Ext.toolbar.Paging){
  Ext.apply(Ext.PagingToolbar.prototype, {
    beforePageText : "Side",
    afterPageText  : "av {0}",
    firstText      : "Første sida",
    prevText       : "Førre sida",
    nextText       : "Neste sida",
    lastText       : "Siste sida",
    refreshText    : "Oppdater",
    displayMsg     : "Viser {0} - {1} av {2}",
    emptyMsg       : 'Ingen data å vise'
  });
}

if(Ext.form.field.Text){
  Ext.apply(Ext.form.field.Text.prototype, {
    minLengthText : "Den minste lengda for dette feltet er {0}",
    maxLengthText : "Den største lengda for dette feltet er {0}",
    blankText     : "Dette feltet er påkravd",
    regexText     : "",
    emptyText     : null
  });
}

if(Ext.form.field.Number){
  Ext.apply(Ext.form.field.Number.prototype, {
    minText : "Den minste verdien for dette feltet er {0}",
    maxText : "Den største verdien for dette feltet er {0}",
    nanText : "{0} er ikkje eit gyldig nummer"
  });
}

if(Ext.form.field.Date){
  Ext.apply(Ext.form.field.Date.prototype, {
    disabledDaysText  : "Deaktivert",
    disabledDatesText : "Deaktivert",
    minText           : "Datoen i dette feltet må vere etter {0}",
    maxText           : "Datoen i dette feltet må vere før {0}",
    invalidText       : "{0} er ikkje ein gyldig dato - han må vere på formatet {1}",
    format            : "d.m.y",
    altFormats        : "d.m.Y|d/m/y|d/m/Y|d-m-y|d-m-Y|d.m|d/m|d-m|dm|dmy|dmY|Y-m-d|d"
  });
}

if(Ext.form.field.ComboBox){
  Ext.apply(Ext.form.field.ComboBox.prototype, {
    valueNotFoundText : undefined
  });
    Ext.apply(Ext.form.field.ComboBox.prototype.defaultListConfig, {
        loadingText       : "Lastar..."
    });
}

if(Ext.form.field.VTypes){
   Ext.apply(Ext.form.field.VTypes, {
      emailText    : 'Dette feltet skal vere ei epost adresse på formatet "bruker@domene.no"',
      urlText      : 'Dette feltet skal vere ein link (URL) på formatet "http:/'+'/www.domene.no"',
      alphaText    : 'Dette feltet skal berre innehalde bokstavar og _',
      alphanumText : 'Dette feltet skal berre innehalde bokstavar, tal og _'
   });
}

if(Ext.form.field.HtmlEditor){
  Ext.apply(Ext.form.field.HtmlEditor.prototype, {
    createLinkText : 'Ver venleg og skriv inn URL for lenken:',
    buttonTips : {
      bold : {
        title: 'Feit (Ctrl+B)',
        text: 'Gjer den valde teksten feit.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      italic : {
        title: 'Kursiv (Ctrl+I)',
        text: 'Gjer den valde teksten kursiv.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      underline : {
        title: 'Understrek (Ctrl+U)',
        text: 'Understrek den valde teksten.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      increasefontsize : {
        title: 'Forstørr tekst',
        text: 'Gjer fontstorleik større.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      decreasefontsize : {
        title: 'Forminsk tekst',
        text: 'Gjer fontstorleik mindre.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      backcolor : {
        title: 'Tekst markeringsfarge',
        text: 'Endre bakgrunnsfarge til den valde teksten.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      forecolor : {
        title: 'Font farge',
        text: 'Endre farge på den valde teksten.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      justifyleft : {
        title: 'Venstrejuster tekst',
        text: 'Venstrejuster teksten.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      justifycenter : {
        title: 'Sentrer tekst',
        text: 'Sentrer teksten.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      justifyright : {
        title: 'Høgrejuster tekst',
        text: 'Høgrejuster teksten.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      insertunorderedlist : {
        title: 'Punktliste',
        text: 'Start ei punktliste.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      insertorderedlist : {
        title: 'Nummerert liste',
        text: 'Start ei nummerert liste.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      createlink : {
        title: 'Lenke',
        text: 'Gjer den valde teksten til ei lenke.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      },
      sourceedit : {
        title: 'Rediger kjelde',
        text: 'Bytt til kjelderedigeringsvising.',
        cls: Ext.baseCSSPrefix + 'html-editor-tip'
      }
    }
  });
}

if(Ext.grid.header.Container){
  Ext.apply(Ext.grid.header.Container.prototype, {
    sortAscText  : "Sorter stigande",
    sortDescText : "Sorter fallande",
    lockText     : "Lås kolonne",
    unlockText   : "Lås opp kolonne",
    columnsText  : "Kolonner"
  });
}

if(Ext.grid.GroupingFeature){
  Ext.apply(Ext.grid.GroupingFeature.prototype, {
    emptyGroupText : '(Ingen)',
    groupByText    : 'Grupper etter dette feltet',
    showGroupsText : 'Vis i grupper'
  });
}

if(Ext.grid.PropertyColumnModel){
  Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
    nameText   : "Namn",
    valueText  : "Verdi",
    dateFormat : "d.m.Y"
  });
}

if(Ext.layout.BorderLayout && Ext.layout.BorderLayout.SplitRegion){
  Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, {
    splitTip            : "Dra for å endre storleik.",
    collapsibleSplitTip : "Dra for å endre storleik. Dobbelklikk for å skjule."
  });
}

});


text:
This application is written as an introduction to the technology.
It is not a ready-made product that can be used in life.

Данное приложение написанно в качестве ознакомления с технологией.
Не является готовым продуктом который можно использовать в жизни.

![Screen shot 1](/res/main.jpg)
![Screen shot 2](/res/army.jpg)


text:
using Autofac;
using Newbe.Mahua.NativeApi;

namespace Newbe.Mahua.QQLight.Native
{
    public class MahuaModule : IMahuaModule
    {
        Module[] IMahuaModule.GetModules()
        {
            return new Module[] { new QqLightApiModule() };
        }

        private class QqLightApiModule : Module
        {
            protected override void Load(ContainerBuilder builder)
            {
                builder.RegisterType<QQLightApi>().As<IQQLightApi>().InstancePerLifetimeScope();
                builder.RegisterType<QqLightAuthCodeContainer>().As<IQqLightAuthCodeContainer>().SingleInstance();
            }
        }
    }
}


text:
/**
 * \file
 * \brief Arch specific definition of the registers, can be included by anyone.
 * Definitions shared by kernel and user
 */

/*
 * Copyright (c) 2010, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
 */

#ifndef TARGET_X86_64_BARRELFISH_KPI_REGISTERS_H
#define TARGET_X86_64_BARRELFISH_KPI_REGISTERS_H

#include <barrelfish_kpi/eflags_arch.h> // for USER_EFLAGS

/** \brief Number of registers to be saved for this architecture
 *
 * This is the same as ARCH_NUMREGS, but it is used by assembler stubs, so needs
 * to be defined here as a constant.
 */
#define X86_64_NUM_REGS                        20

#ifndef __ASSEMBLER__

// Warning: both the GDB stubs and any number of asm fragments depend
// on the order of these fields. Don't change them without due care!
struct registers_x86_64 {
    uint64_t rax, rbx, rcx, rdx, rsi, rdi, rbp, rsp,
        r8, r9, r10, r11, r12, r13, r14, r15, rip, eflags;
    uint16_t fs, gs; ///< Only meaningful segment selectors in 64-bit mode
};

struct registers_fpu_x86_64 {
    // Should be aligned at 16-byte boundary, according to Intel
    // description of FXRSTOR instruction.
    uint8_t registers[512 + 16] __attribute__ ((aligned (16)));
};

static inline void
registers_x86_64_set_entry(struct registers_x86_64 *regs, lvaddr_t entry)
{
    regs->rip    = entry;
    regs->eflags = USER_EFLAGS;
    regs->fs = 0;
    regs->gs = 0;
}

static inline void
registers_x86_64_set_param(struct registers_x86_64 *regs, uint64_t param)
{
    regs->rax = param;
}

static inline void
registers_x86_64_get_param(struct registers_x86_64 *regs, uint64_t *param)
{
    *param = regs->rax;
}

static inline uint64_t
registers_x86_64_get_ip(struct registers_x86_64 *regs)
{
    return regs->rip;
}

#endif // __ASSEMBLER__
#endif // TARGET_X86_64_BARRELFISH_KPI_REGISTERS_H


text:
//
// Generated by JTB 1.3.2
//

package com.mhs.qsol.syntaxtree;

/**
 * Grammar production: f0 -> FieldSearch() | SearchToken() | ParenthesisSearch()
 */
public class BasicSearchType implements Node {
  public NodeChoice f0;

  public BasicSearchType(NodeChoice n0) {
    f0 = n0;
  }

  public void accept(com.mhs.qsol.visitor.Visitor v) {
    v.visit(this);
  }

  public <R, A> R accept(com.mhs.qsol.visitor.GJVisitor<R, A> v, A argu) {
    return v.visit(this, argu);
  }

  public <R> R accept(com.mhs.qsol.visitor.GJNoArguVisitor<R> v) {
    return v.visit(this);
  }

  public <A> void accept(com.mhs.qsol.visitor.GJVoidVisitor<A> v, A argu) {
    v.visit(this, argu);
  }
}


text:
@implementation DevMenuREAEventNode {
  NSArray *_argMapping;
}

- (instancetype)initWithID:(DevMenuREANodeID)nodeID config:(NSDictionary<NSString *,id> *)config
{
  if ((self = [super initWithID:nodeID config:config])) {
    _argMapping = config[@"argMapping"];
  }
  return self;
}

- (void)processEvent:(id<RCTEvent>)event
{
  NSArray *args = event.arguments;
  // argMapping is an array of eventPaths, each even path ends with a target node ID
  for (NSArray *eventPath in _argMapping) {
    // Supported events args are in the following order: viewTag, eventName, eventData.
    id value = args[2];
    for (NSUInteger i = 0; i < eventPath.count; i++) {
      if (i < eventPath.count - 1) {
        value = [value valueForKey:eventPath[i]];
      } else {
        DevMenuREAValueNode *node = (DevMenuREAValueNode *)[self.nodesManager findNodeByID:eventPath[i]];
        [node setValue:value];
      }
    }
  }
}

@end


text:
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    # Examples:
    # url(r'^$', 'buscoayuda4101.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^', include('polls.urls', namespace="principal")),
    url(r'^admin/', include(admin.site.urls)),
]


text:
package in.twizmwaz.cardinal.module.filter;

public interface FilterParser {
}


text:
import { FETCH_POSTS, FETCH_POST } from '../actions/index';

const INITIAL_STATE = {
  all: [], // array of blog posts
  post: null // a single post
};

export default (state = INITIAL_STATE, action) => {
  switch(action.type){
    case FETCH_POSTS:
      // takes in our new state, then concatenates the payload data to it.
      return {
        ...state,
        all: action.payload.data
      };
    case FETCH_POST:
      return {
        ...state,
        post: action.payload.data
      };
    default:
      return state;
  }
}


text:
export GOOS=linux
export GOARCH=arm

echo "[INFO] Fetching dependencies"
go get -d -v

echo "[INFO] Building"
go build -v github.com/yurigorokhov/go-pibot

echo "[INFO] Creating Package"
mkdir -p build
tar -c go-pibot public scripts > build/package.tar && gzip -f build/package.tar

echo "[INFO] Uploading Package"
s3cmd put build/package.tar.gz s3://batbot/package/package.tar.gz


text:
import json

# django imports
from django.contrib.auth.decorators import permission_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.http import require_POST

# portlets imports
import portlets.utils
from portlets.models import PortletAssignment
from portlets.models import PortletBlocking
from portlets.models import PortletRegistration
from portlets.models import Slot

# lfs imports
from lfs.core.utils import LazyEncoder

@permission_required("core.manage_shop")
def portlets_inline(request, obj, template_name="manage/portlets/portlets_inline.html"):
    """Displays the assigned portlets for given object.
    """
    ct = ContentType.objects.get_for_model(obj)

    parent_for_portlets = obj.get_parent_for_portlets()
    if parent_for_portlets:
        parent_slots = portlets.utils.get_slots(parent_for_portlets)

    else:
        parent_slots = None

    return render_to_string(template_name, request=request, context={
        "slots": portlets.utils.get_slots(obj),
        "parent_slots": parent_slots,
        "parent_for_portlets": parent_for_portlets,
        "portlet_types": PortletRegistration.objects.filter(active=True),
        "object": obj,
        "object_type_id": ct.id,
    })

@permission_required("core.manage_shop")
def update_portlets(request, object_type_id, object_id):
    """Update portlets blocking.
    """
    # Get content type to which the portlet should be added
    object_ct = ContentType.objects.get(pk=object_type_id)
    obj = object_ct.get_object_for_this_type(pk=object_id)

    blocked_slots = request.POST.getlist("block_slot")

    # Delete all slots that were NOT checked
    PortletBlocking.objects.filter(content_type_id=object_type_id,
                                   content_id=object_id).exclude(slot_id__in=blocked_slots).delete()

    for slot in Slot.objects.filter(id__in=blocked_slots):
        PortletBlocking.objects.get_or_create(slot=slot,
                                              content_type_id=object_type_id,
                                              content_id=object_id)

    result = json.dumps({
        "html": [["#portlets", portlets_inline(request, obj)]],
        "message": _(u"Portlet has been updated.")},
        cls=LazyEncoder
    )
    return HttpResponse(result, content_type='application/json')

@permission_required("core.manage_shop")
def add_portlet(request, object_type_id, object_id, template_name="manage/portlets/portlet_add.html"):
    """Form and logic to add a new portlet to the object with given type and id.
    """
    # Get content type to which the portlet should be added
    object_ct = ContentType.objects.get(pk=object_type_id)
    obj = object_ct.get_object_for_this_type(pk=object_id)

    # Get the portlet type
    portlet_type = (request.POST if request.method == 'POST' else request.GET).get("portlet_type", "")

    if request.method == "POST":
        try:
            ct = ContentType.objects.filter(model=portlet_type.lower())[0]
            mc = ct.model_class()
            form = mc().form(prefix="portlet", data=request.POST)

            if form.is_valid():
                portlet = form.save()

                slot_id = request.POST.get("slot")
                pa = PortletAssignment.objects.create(
                    slot_id=slot_id, content=obj, portlet=portlet, position=1000)

                update_portlet_positions(pa)

                html = [["#portlets", portlets_inline(request, obj)]]

                result = json.dumps({
                    "html": html,
                    "close-dialog": True,
                    "message": _(u"Portlet has been added.")},
                    cls=LazyEncoder
                )
            else:
                html = [["#portlet-form-inline", render_to_string('manage/lfs_form.html', request=request, context={'form': form})]]

                result = json.dumps({
                    "html": html,
                    "close-dialog": False,
                    "message": _(u"Please correct errors and try again.")},
                    cls=LazyEncoder
                )
            return HttpResponse(result, content_type='application/json')

        except ContentType.DoesNotExist:
            pass
    else:
        try:
            portlet_ct = ContentType.objects.filter(model=portlet_type.lower())[0]
            mc = portlet_ct.model_class()
            form = mc().form(prefix="portlet")
            result = render_to_string(template_name, request=request, context={
                "form": form,
                "object_id": object_id,
                "object_type_id": object_ct.id,
                "portlet_type": portlet_type,
                "slots": Slot.objects.all(),
            })

            return HttpResponse(json.dumps({'html': result}),
                                content_type='application/json')

        except ContentType.DoesNotExist:
            pass

@permission_required("core.manage_shop")
@require_POST
def delete_portlet(request, portletassignment_id):
    """Deletes a portlet for given portlet assignment.
    """
    try:
        pa = PortletAssignment.objects.get(pk=portletassignment_id)
    except PortletAssignment.DoesNotExist:
        pass
    else:
        pa.delete()
        update_portlet_positions(pa)
        result = json.dumps({
            "html": [["#portlets", portlets_inline(request, pa.content)]],
            "close-dialog": True,
            "message": _(u"Portlet has been deleted.")},
            cls=LazyEncoder
        )
        return HttpResponse(result, content_type='application/json')

@permission_required("core.manage_shop")
def edit_portlet(request, portletassignment_id, template_name="manage/portlets/portlet_edit.html"):
    """Form and logic to edit the portlet of the given portlet assignment.
    """
    try:
        pa = PortletAssignment.objects.get(pk=portletassignment_id)
    except PortletAssignment.DoesNotExist:
        return ""

    if request.method == "POST":
        form = pa.portlet.form(prefix="portlet", data=request.POST)
        if form.is_valid():
            form.save()

            # Save the rest
            pa.slot_id = request.POST.get("slot")
            pa.save()

            html = [["#portlets", portlets_inline(request, pa.content)]]

            result = json.dumps({
                "html": html,
                "close-dialog": True,
                "message": _(u"Portlet has been saved.")},
                cls=LazyEncoder
            )
        else:
            html = [["#portlet-form-inline", render_to_string('manage/lfs_form.html', request=request, context={'form': form})]]

            result = json.dumps({
                "html": html,
                "close-dialog": False,
                "message": _(u"Please correct errors and try again.")},
                cls=LazyEncoder
            )
        return HttpResponse(result, content_type='application/json')
    else:
        slots = []
        for slot in Slot.objects.all():
            slots.append({
                "id": slot.id,
                "name": slot.name,
                "selected": slot.id == pa.slot.id,
            })

        form = pa.portlet.form(prefix="portlet")
        return render(request, template_name, {
            "form": form,
            "portletassigment_id": pa.id,
            "slots": slots,
        })

@permission_required("core.manage_shop")
def move_portlet(request, portletassignment_id):
    """
    Moves a portlet up/down within a slot.

    **Parameters:**

        portletassignment_id
            The portlet assignment (hence the portlet) which should be moved.

    **Query String:**

        direction
            The direction to which the portlet should be moved. One of 0 (up)
            or 1 (down).
    """
    try:
        pa = PortletAssignment.objects.get(pk=portletassignment_id)
    except PortletAssignment.DoesNotExist:
        return ""

    direction = request.GET.get("direction", "0")
    if direction == "1":
        pa.position += 15
    else:
        pa.position -= 15
        if pa.position < 0:
            pa.position = 10
    pa.save()

    update_portlet_positions(pa)

    result = json.dumps({
        "html": [["#portlets", portlets_inline(request, pa.content)]]},
        cls=LazyEncoder
    )

    return HttpResponse(result, content_type='application/json')

def update_portlet_positions(pa):
    """Updates the portlet positions for a content object and a slot.

    **Parameters:**

        pa
            PortletAssignment which contains the slot and the content object
            in question.

    **Permission:**

        None (as this is not called from outside)
    """
    for i, pa in enumerate(PortletAssignment.objects.filter(content_type=pa.content_type, content_id=pa.content_id, slot=pa.slot)):
        pa.position = (i + 1) * 10
        pa.save()


text:
import { Plugin } from './Plugin';

import type { DisplayObject } from '@pixi/display';
import type { IPointData } from '@pixi/math';
import type { Viewport } from '../Viewport';

/** Options for {@link Follow}. */
export interface IFollowOptions
{
    /**
     * Speed to follow in px/frame (0 = teleport to location)
     *
     * @default 9
     */
    speed?: number;

    /**
     * Set acceleration to accelerate and decelerate at this rate; speed cannot be 0 to use acceleration
     *
     * @default null
     */
    acceleration?: number | null;

    /**
     * Radius (in world coordinates) of center circle where movement is allowed without moving the viewport
     *
     * @default null
     */
    radius?: number | null;
}

const DEFAULT_FOLLOW_OPTIONS: Required<IFollowOptions> = {
    speed: 0,
    acceleration: null,
    radius: null
};

/**
 * Plugin to follow a display-object.
 *
 * @see Viewport.follow
 * @public
 */
export class Follow extends Plugin
{
    /** The options used to initialize this plugin. */
    public readonly options: Required<IFollowOptions>;

    /** The target this plugin will make the viewport follow. */
    public target: DisplayObject;

    /** The velocity provided the viewport by following, at the current time. */
    protected velocity: IPointData;

    /**
     * This is called by {@link Viewport.follow}.
     *
     * @param parent
     * @param target - target to follow
     * @param options
     */
    constructor(parent: Viewport, target: DisplayObject, options: IFollowOptions = {})
    {
        super(parent);

        this.target = target;
        this.options = Object.assign({}, DEFAULT_FOLLOW_OPTIONS, options);
        this.velocity = { x: 0, y: 0 };
    }

    public update(elapsed: number): void
    {
        if (this.paused)
        {
            return;
        }

        const center = this.parent.center;
        let toX = this.target.x;
        let toY = this.target.y;

        if (this.options.radius)
        {
            const distance = Math.sqrt(Math.pow(this.target.y - center.y, 2) + Math.pow(this.target.x - center.x, 2));

            if (distance > this.options.radius)
            {
                const angle = Math.atan2(this.target.y - center.y, this.target.x - center.x);

                toX = this.target.x - (Math.cos(angle) * this.options.radius);
                toY = this.target.y - (Math.sin(angle) * this.options.radius);
            }
            else
            {
                return;
            }
        }

        const deltaX = toX - center.x;
        const deltaY = toY - center.y;

        if (deltaX || deltaY)
        {
            if (this.options.speed)
            {
                if (this.options.acceleration)
                {
                    const angle = Math.atan2(toY - center.y, toX - center.x);
                    const distance = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));

                    if (distance)
                    {
                        const decelerationDistance = (Math.pow(this.velocity.x, 2) + Math.pow(this.velocity.y, 2)) / (2 * this.options.acceleration);

                        if (distance > decelerationDistance)
                        {
                            this.velocity = {
                                x: Math.min(this.velocity.x + this.options.acceleration * elapsed, this.options.speed),
                                y: Math.min(this.velocity.y + this.options.acceleration * elapsed, this.options.speed)
                            };
                        }
                        else
                        {
                            this.velocity = {
                                x: Math.max(this.velocity.x - this.options.acceleration * this.options.speed, 0),
                                y: Math.max(this.velocity.y - this.options.acceleration * this.options.speed, 0)
                            };
                        }
                        const changeX = Math.cos(angle) * this.velocity.x;
                        const changeY = Math.sin(angle) * this.velocity.y;
                        const x = Math.abs(changeX) > Math.abs(deltaX) ? toX : center.x + changeX;
                        const y = Math.abs(changeY) > Math.abs(deltaY) ? toY : center.y + changeY;

                        this.parent.moveCenter(x, y);
                        this.parent.emit('moved', { viewport: this.parent, type: 'follow' });
                    }
                }
                else
                {
                    const angle = Math.atan2(toY - center.y, toX - center.x);
                    const changeX = Math.cos(angle) * this.options.speed;
                    const changeY = Math.sin(angle) * this.options.speed;
                    const x = Math.abs(changeX) > Math.abs(deltaX) ? toX : center.x + changeX;
                    const y = Math.abs(changeY) > Math.abs(deltaY) ? toY : center.y + changeY;

                    this.parent.moveCenter(x, y);
                    this.parent.emit('moved', { viewport: this.parent, type: 'follow' });
                }
            }
            else
            {
                this.parent.moveCenter(toX, toY);
                this.parent.emit('moved', { viewport: this.parent, type: 'follow' });
            }
        }
    }
}


text:
<project name="HelloWorld" default="dist" basedir=".">

  <!-- set global properties for this build -->
  <property name="src" location="./src"/>
  <property name="build" location="./build"/>
  <property name="dist" location="./dist"/>

  <target name="clean"
          description="clean up" >
      <!-- Delete the ${build} and ${dist} directory trees -->
      <delete dir="${build}"/>
      <delete dir="${dist}"/>
  </target>

  <target name="init" depends="clean">
    <!-- Create the time stamp -->
    <mkdir dir="${build}"/>
    <mkdir dir="${dist}"/>
  </target>

  <target name="compile" depends="init"
        description="compile the source " >
    <!-- Compile the java code from ${src} into ${build} -->
    <javac srcdir="${src}" destdir="${build}">
		<classpath>
			<pathelement location="${src}"/>
		</classpath>
    </javac>
  </target>

  <target name="dist" depends="compile"
        description="generate the distribution" >
    <jar jarfile="${dist}/Test1.jar" basedir="${build}" includes="com/kirkk/analyzer/jar1/**"/>
    <jar jarfile="${dist}/Test2.jar" basedir="${build}" includes="com/kirkk/analyzer/jar2/**"/>
  </target>

</project>


text:
from botoflow import *

from various_activities import BunchOfActivities

class NoActivitiesWorkflow(WorkflowDefinition):
    @execute(version='1.2', execution_start_to_close_timeout=60)
    def execute(self, arg1):
        return_(arg1)

        class OneActivityWorkflow(WorkflowDefinition):

            @execute(version='1.1', execution_start_to_close_timeout=60)
            def execute(self, arg1, arg2):
                arg_sum = yield BunchOfActivities.sum(arg1, arg2)
                return_(arg_sum)

class NoActivitiesFailureWorkflow(WorkflowDefinition):

    @execute(version='1.1', execution_start_to_close_timeout=60)
    def execute(self, arg1):
        raise RuntimeError("ExecutionFailed")

class OneActivityWorkflow(WorkflowDefinition):

    @execute(version='1.1', execution_start_to_close_timeout=60)
    def execute(self, arg1, arg2):
        arg_sum = yield BunchOfActivities.sum(arg1, arg2)
        return_(arg_sum)

class OneMultiWorkflow(WorkflowDefinition):
    @execute(version='1.2', execution_start_to_close_timeout=60)
    def execute(self, arg1, arg2):
        arg_sum = yield BunchOfActivities.sum(arg1, arg2)
        return_(arg_sum)

class TwoMultiWorkflow(WorkflowDefinition):
    @execute(version='1.2', execution_start_to_close_timeout=60)
    def execute(self, arg1, arg2):
        arg_sum = yield BunchOfActivities.sum(arg1, arg2)
        return_(arg_sum)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using CascadeExample.Data;
using Microsoft.EntityFrameworkCore;

namespace CascadeExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Db db = new Db();

            // List<User> users = db.Users.ToList();

            // db.Users.Add(new User()
            // {
            //     Name = "Test user",
            //     Entries = new List<Entry>()
            //     {
            //         new Entry() { Content = "Entry 1" },
            //         new Entry() { Content = "Entry 2" }
            //     }
            // });
            // db.SaveChanges();

            // List<User> users2 = db.Users.Include(u => u.Entries).ToList();
            //
            db.Users.RemoveRange(db.Users.Include(u => u.Entries));
            db.SaveChanges();
        }
    }
}


text:
package org.apache.sysml.runtime.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.JobConf;

import org.apache.sysml.conf.ConfigurationManager;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.matrix.CSVReblockMR;
import org.apache.sysml.runtime.matrix.data.CSVFileFormatProperties;
import org.apache.sysml.runtime.matrix.data.MatrixBlock;
import org.apache.sysml.runtime.util.UtilFunctions;

public class ReaderTextCSV extends MatrixReader
{

	private CSVFileFormatProperties _props = null;

	public ReaderTextCSV(CSVFileFormatProperties props)
	{
		_props = props;
	}

	@Override
	public MatrixBlock readMatrixFromHDFS(String fname, long rlen, long clen, int brlen, int bclen, long estnnz)
		throws IOException, DMLRuntimeException
	{
		//allocate output matrix block
		MatrixBlock ret = null;
		if( rlen>0 && clen>0 ) //otherwise CSV reblock based on file size for matrix w/ unknown dimensions
			ret = createOutputMatrixBlock(rlen, clen, estnnz, true, false);

		//prepare file access
		JobConf job = new JobConf(ConfigurationManager.getCachedJobConf());
		FileSystem fs = FileSystem.get(job);
		Path path = new Path( fname );

		//check existence and non-empty file
		checkValidInputFile(fs, path);

		//core read
		ret = readCSVMatrixFromHDFS(path, job, fs, ret, rlen, clen, brlen, bclen,
				   _props.hasHeader(), _props.getDelim(), _props.isFill(), _props.getFillValue() );

		//finally check if change of sparse/dense block representation required
		//(nnz explicitly maintained during read)
		ret.examSparsity();

		return ret;
	}

	/**
	 *
	 * @param path
	 * @param job
	 * @param fs
	 * @param dest
	 * @param rlen
	 * @param clen
	 * @param brlen
	 * @param bclen
	 * @param hasHeader
	 * @param delim
	 * @param fill
	 * @param fillValue
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	private MatrixBlock readCSVMatrixFromHDFS( Path path, JobConf job, FileSystem fs, MatrixBlock dest,
			long rlen, long clen, int brlen, int bclen, boolean hasHeader, String delim, boolean fill, double fillValue )
		throws IOException
	{
		ArrayList<Path> files=new ArrayList<Path>();
		if(fs.isDirectory(path)) {
			for(FileStatus stat: fs.listStatus(path, CSVReblockMR.hiddenFileFilter))
				files.add(stat.getPath());
			Collections.sort(files);
		}
		else
			files.add(path);

		if ( dest == null ) {
			dest = computeCSVSize(files, job, fs, hasHeader, delim, fill, fillValue);
			clen = dest.getNumColumns();
		}

		boolean sparse = dest.isInSparseFormat();

		/////////////////////////////////////////
		String value = null;
		int row = 0;
		int col = -1;
		double cellValue = 0;
		long lnnz = 0;

		for(int fileNo=0; fileNo<files.size(); fileNo++)
		{
			BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(files.get(fileNo))));
			if(fileNo==0 && hasHeader )
				br.readLine(); //ignore header

			// Read the data
			boolean emptyValuesFound = false;
			try
			{
				if( sparse ) //SPARSE<-value
				{
					while( (value=br.readLine())!=null ) //foreach line
					{
						String cellStr = value.toString().trim();
						emptyValuesFound = false;
						String[] parts = IOUtilFunctions.split(cellStr, delim);
						col = 0;

						for(String part : parts) //foreach cell
						{
							part = part.trim();
							if ( part.isEmpty() ) {
								emptyValuesFound = true;
								cellValue = fillValue;
							}
							else {
								cellValue = UtilFunctions.parseToDouble(part);
							}
							if ( cellValue != 0 ) {
								dest.appendValue(row, col, cellValue);
								lnnz++;
							}
							col++;
						}

						//sanity checks for empty values and number of columns
						IOUtilFunctions.checkAndRaiseErrorCSVEmptyField(cellStr, fill, emptyValuesFound);
						IOUtilFunctions.checkAndRaiseErrorCSVNumColumns(path.toString(), cellStr, parts, clen);
						row++;
					}
				}
				else //DENSE<-value
				{
					while( (value=br.readLine())!=null ) //foreach line
					{
						String cellStr = value.toString().trim();
						emptyValuesFound = false;
						String[] parts = IOUtilFunctions.split(cellStr, delim);
						col = 0;

						for( String part : parts ) //foreach cell
						{
							part = part.trim();
							if ( part.isEmpty() ) {
								emptyValuesFound = true;
								cellValue = fillValue;
							}
							else {
								cellValue = UtilFunctions.parseToDouble(part);
							}
							if ( cellValue != 0 ) {
								dest.setValueDenseUnsafe(row, col, cellValue);
								lnnz++;
							}
							col++;
						}

						//sanity checks for empty values and number of columns
						IOUtilFunctions.checkAndRaiseErrorCSVEmptyField(cellStr, fill, emptyValuesFound);
						IOUtilFunctions.checkAndRaiseErrorCSVNumColumns(path.toString(), cellStr, parts, clen);
						row++;
					}
				}
			}
			finally {
				IOUtilFunctions.closeSilently(br);
			}
		}

		//post processing
		dest.setNonZeros( lnnz );

		return dest;
	}

	/**
	 *
	 * @param files
	 * @param job
	 * @param fs
	 * @param hasHeader
	 * @param delim
	 * @param fill
	 * @param fillValue
	 * @return
	 * @throws IOException
	 */
	private MatrixBlock computeCSVSize ( List<Path> files, JobConf job, FileSystem fs, boolean hasHeader, String delim, boolean fill, double fillValue)
		throws IOException
	{
		int nrow = -1;
		int ncol = -1;
		String value = null;

		String cellStr = null;
		for(int fileNo=0; fileNo<files.size(); fileNo++)
		{
			BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(files.get(fileNo))));
			try
			{
				// Read the header line, if there is one.
				if(fileNo==0)
				{
					if ( hasHeader )
						br.readLine(); //ignore header
					if( (value = br.readLine()) != null ) {
						cellStr = value.toString().trim();
						ncol = StringUtils.countMatches(cellStr, delim) + 1;
						nrow = 1;
					}
				}

				while ( (value = br.readLine()) != null ) {
					nrow++;
				}
			}
			finally {
				IOUtilFunctions.closeSilently(br);
			}
		}

		//create new matrix block (assume sparse for consistency w/ compiler)
		return new MatrixBlock(nrow, ncol, true);
	}
}


text:
\documentclass{article}
\usepackage{amsmath,amssymb,amsfonts}
\usepackage{graphicx}
\usepackage{multicol}
\setlength{\oddsidemargin}{0in} \setlength{\evensidemargin}{0in}
\setlength{\topmargin}{0in} \setlength{\textheight}{8.5in}
\setlength{\textwidth}{6.5in}
\pagestyle{empty}

\begin{document}
\begin{flushleft}
	\bfseries{MATH 260, Homework 8, Fall `14}\\
	\bfseries{Due: October 17, 2014 at 2:20 PM}\\
	\bfseries{Honor Code:} \hspace{3.5in}\bfseries{Name:}\\
	\hspace{4.37in}\bfseries{Section:}
\end{flushleft}
\begin{flushleft}
\vspace{.25in}

1) (12 pts) Determine if the following sets of vectors are linearly independent.  Briefly explain your reasoning.

\vspace{0.2in}

a) $\left\{ \begin{bmatrix} 2\\4\\6\\ \end{bmatrix}, \begin{bmatrix} 1\\2\\3\\ \end{bmatrix} \right\}$

\vspace{1.5in}

b) $\left\{ \begin{bmatrix} 1\\1\\1\\ \end{bmatrix}, \begin{bmatrix} 0\\1\\1\\ \end{bmatrix}, \begin{bmatrix} 0\\0\\-1\\\end{bmatrix} \right\}$

\vspace{1.5in}

c) $\left\{\begin{bmatrix} 2\\0\\1\\ \end{bmatrix}, \begin{bmatrix} 0\\1\\0\\ \end{bmatrix}, \begin{bmatrix} 0\\3\\4\\ \end{bmatrix} \begin{bmatrix} -1\\0\\0\\ \end{bmatrix}\right\}$

\vspace{1.5in}

d) $\left\{\begin{bmatrix} 1\\0\\1\\ \end{bmatrix}, \begin{bmatrix} 0\\1\\0\\ \end{bmatrix}, \begin{bmatrix} 1\\1\\1\\ \end{bmatrix} \right\}$

\pagebreak

2) (13 pts) For each vector space below, determine if the accompanying set is a basis for it.  If it is not, add or remove vectors from the set until your new set is a basis for the vector space.  State the dimension of the vector space.

\vspace{0.2in}

a) $\mathbb{R}^2$; \hspace{0.1in} $\left\{\begin{bmatrix} 1\\2\\\end{bmatrix}, \begin{bmatrix} 3\\4\\\end{bmatrix}, \begin{bmatrix} 5\\6\\\end{bmatrix} \right\}$

\vspace{2.5in}

b) $\mathbb{R}^3$; \hspace{0.1in} $\left\{ \begin{bmatrix} 1\\0\\1\\ \end{bmatrix}, \begin{bmatrix} 0\\1\\1\\ \end{bmatrix}, \begin{bmatrix} 1\\1\\0\\ \end{bmatrix} \right\}$

\vspace{2.5in}

c) $\left\{ \begin{bmatrix} x\\y\\z\\\end{bmatrix} | x+y=0 \right\}$; \hspace{0.1in} $\left\{ \begin{bmatrix} -1\\1\\0\\\end{bmatrix} \right\}$

%
%4) (12 pts) Find the null space and the column space for the matrix $\textbf{A} = \begin{bmatrix} 1&2&3&4 \\ 2&3&4&5\\ 3&5&7&9 \end{bmatrix}$.  Give the dimension of each of the two subspaces you found.
%
%\pagebreak
%
%5) (12 pts) Re-do problem 4 using $\textbf{A}^T$ instead.
%
%\vspace{6.5in}
%
%6) (6 pts) Find the sum of the dimensions of the two subspaces from problem 4, then do so again for problem 5.  Note that $\textbf{A}$ is $3 \times 4$.  How do the dimensions of these subspaces relate to the dimensions of $\textbf{A}$?

\end{flushleft}
\end{document}


text:
#import <WebKit/WebHistoryItem.h>

@interface WebHistoryItem (WebPrivate)
- (_Bool)_hasCachedPageExpired;
- (_Bool)_isInPageCache;
- (void)_setSharedLinkUniqueIdentifier:(id)arg1;
- (id)_sharedLinkUniqueIdentifier;
- (void)_setBookmarkID:(unsigned int)arg1;
- (unsigned int)_bookmarkID;
- (void)_setScrollPoint:(struct CGPoint)arg1;
- (struct CGPoint)_scrollPoint;
- (void)_setViewportArguments:(id)arg1;
- (id)_viewportArguments;
- (_Bool)_scaleIsInitial;
- (float)_scale;
- (void)_setScale:(float)arg1 isInitial:(_Bool)arg2;
- (unsigned long long)_getWeeklyVisitCounts:(const int **)arg1;
- (unsigned long long)_getDailyVisitCounts:(const int **)arg1;
- (id)_redirectURLs;
- (_Bool)_lastVisitWasHTTPNonGet;
- (void)_setLastVisitWasFailure:(_Bool)arg1;
- (_Bool)lastVisitWasFailure;
- (void)_setTransientProperty:(id)arg1 forKey:(id)arg2;
- (id)_transientPropertyForKey:(id)arg1;
- (id)targetItem;
- (id)_lastVisitedDate;
- (void)_setLastVisitedTimeInterval:(double)arg1;
- (id)URL;
- (void)setAlwaysAttemptToUsePageCache:(_Bool)arg1;
- (id)children;
- (void)setRSSFeedReferrer:(id)arg1;
- (id)RSSFeedReferrer;
- (int)visitCount;
- (_Bool)isTargetItem;
- (id)target;
- (id)dictionaryRepresentationIncludingChildren:(_Bool)arg1;
- (id)dictionaryRepresentation;
- (id)initWithURL:(id)arg1 title:(id)arg2;
@end


text:
<form role="form" class="search-pf has-button">

      Buscar
      <input id="search1" type="search" class="form-control" placeholder="Buscar...">
      <button type="button" class="clear" aria-hidden="true"></button>

    <button class="btn btn-default" type="button"></button>

</form>


text:
static NSString *const kNameCellIdentifier = @"NameCell";

@interface BlockLeakViewController ()

#pragma mark - Model
@property (strong, nonatomic) NSArray *nameList;

#pragma mark - Data source
@property (strong, nonatomic) ArrayDataSource *dataSource;

@end

@implementation BlockLeakViewController

#pragma mark - Lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.dataSource = self.dataSource;
}

#pragma mark - Lazy initialization
- (NSArray *)nameList
{
    if (!_nameList) {
        _nameList = @[@"Sam", @"Mike", @"John", @"Paul", @"Jason"];
    }
    return _nameList;
}

- (ArrayDataSource *)dataSource
{
    if (!_dataSource) {
        _dataSource = [[ArrayDataSource alloc] initWithItems:self.nameList
                                              cellIdentifier:kNameCellIdentifier
                                              tableViewStyle:UITableViewCellStyleDefault
                                          configureCellBlock:^(UITableViewCell *cell, NSString *item, NSIndexPath *indexPath) {
                                              cell.textLabel.text = item;

                                              [self configureCell];
                                          }];
    }
    return _dataSource;
}

- (void)configureCell
{
    NSLog(@"Just for test");
}

- (void)dealloc
{
    NSLog(@"release BlockLeakViewController");
}

@end


text:
module Wor
  module Paginate
    module Config
      DEFAULTS_CONFIGS = {
        default_per_page: 25,
        default_page: 1,
        page_param: :page,
        per_page_param: :limit,
        formatter: Wor::Paginate::Formatters::Base,
        max_limit: 50,
        default_adapter: nil
      }.freeze

      DEFAULT_ADAPTERS = {
        kaminari_paginated: Adapters::KaminariAlreadyPaginated,
        will_paginate_paginated: Adapters::WillPaginateAlreadyPaginated,
        will_paginate: Adapters::WillPaginate,
        kaminari: Adapters::Kaminari,
        active_record: Adapters::ActiveRecord,
        enumerable: Adapters::Enumerable
      }.freeze

      @adapters = DEFAULT_ADAPTERS.values

      module_function

      DEFAULTS_CONFIGS.each do |key, value|
        define_method key do
          instance_variable_get("@#{key}") || instance_variable_set("@#{key}", value)
        end

        define_method "#{key}=" do |v|
          instance_variable_set("@#{key}", v)
        end
      end

      def add_adapter(adapter)
        @adapters << adapter
      end

      def remove_adapter(adapter)
        @adapters.delete(adapter)
      end

      def clear_adapters
        @adapters.clear
      end

      def adapters
        @adapters
      end

      # This is mostly useful for the tests
      def reset!
        DEFAULTS_CONFIGS.each { |k, v| send("#{k}=", v) }
      end

      def reset_adapters!
        @adapters = DEFAULT_ADAPTERS.values
      end
    end
  end
end


text:
<?php
/**
 * This file is part of UnglinLand_User
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 7.2
 *
 * @category Role
 * @package  UnglinLand_User
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace UnglinLand\UserModule\Model;

/**
 * Entity Version control trait
 *
 * This trait is used to manage version control of the entities
 *
 * @category Entity
 * @package  UnglinLand_User
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
trait EntityVersionControlTrait
{
    /**
     * Reference
     *
     * This property store the identifyer reference of the entity
     *
     * @var mixed
     */
    private $reference;

    /**
     * Creation date
     *
     * This property store the creation date of the entity
     *
     * @var \DateTime
     */
    private $creationDate;

    /**
     * Deleted
     *
     * This property store the deletion state of the entity
     *
     * @var bool
     */
    private $deleted;

    /**
     * Set reference
     *
     * This method allow to set the identifyer reference of the entity
     *
     * @param mixed $reference The entity identifyer reference
     *
     * @return $this
     */
    public function setReference($reference)
    {
        $this->reference = $reference;
        return $this;
    }

    /**
     * Set deleted
     *
     * This method allow to set the deletion state of the entity
     *
     * @param bool $deleted The deletion state of the entity
     *
     * @return $this
     */
    public function setDeleted(bool $deleted)
    {
        $this->deleted = $deleted;
        return $this;
    }

    /**
     * Get reference
     *
     * Return the identifyer reference of the entity
     *
     * @return mixed
     */
    public function getReference()
    {
        return $this->reference;
    }

    /**
     * Get creation date
     *
     * This method return the creation date of the entity
     *
     * @return \DateTime
     */
    public function getCreationDate() : \DateTime
    {
        return $this->creationDate;
    }

    /**
     * Is deleted
     *
     * This method return the deletion state of the entity
     *
     * @return bool
     */
    public function isDeleted() : bool
    {
        return $this->deleted;
    }
}


text:
package logical

import (
	"context"

	log "github.com/hashicorp/go-hclog"
)

// BackendType is the type of backend that is being implemented
type BackendType uint32

// The these are the types of backends that can be derived from
// logical.Backend
const (
	TypeUnknown    BackendType = 0 // This is also the zero-value for BackendType
	TypeLogical    BackendType = 1
	TypeCredential BackendType = 2
)

// Stringer implementation
func (b BackendType) String() string {
	switch b {
	case TypeLogical:
		return "secret"
	case TypeCredential:
		return "auth"
	}

	return "unknown"
}

// Backend interface must be implemented to be "mountable" at
// a given path. Requests flow through a router which has various mount
// points that flow to a logical backend. The logic of each backend is flexible,
// and this is what allows materialized keys to function. There can be specialized
// logical backends for various upstreams (Consul, PostgreSQL, MySQL, etc) that can
// interact with remote APIs to generate keys dynamically. This interface also
// allows for a "procfs" like interaction, as internal state can be exposed by
// acting like a logical backend and being mounted.
type Backend interface {
	// Initialize is used to initialize a plugin after it has been mounted.
	Initialize(context.Context, *InitializationRequest) error

	// HandleRequest is used to handle a request and generate a response.
	// The backends must check the operation type and handle appropriately.
	HandleRequest(context.Context, *Request) (*Response, error)

	// SpecialPaths is a list of paths that are special in some way.
	// See PathType for the types of special paths. The key is the type
	// of the special path, and the value is a list of paths for this type.
	// This is not a regular expression but is an exact match. If the path
	// ends in '*' then it is a prefix-based match. The '*' can only appear
	// at the end.
	SpecialPaths() *Paths

	// System provides an interface to access certain system configuration
	// information, such as globally configured default and max lease TTLs.
	System() SystemView

	// Logger provides an interface to access the underlying logger. This
	// is useful when a struct embeds a Backend-implemented struct that
	// contains a private instance of logger.
	Logger() log.Logger

	// HandleExistenceCheck is used to handle a request and generate a response
	// indicating whether the given path exists or not; this is used to
	// understand whether the request must have a Create or Update capability
	// ACL applied. The first bool indicates whether an existence check
	// function was found for the backend; the second indicates whether, if an
	// existence check function was found, the item exists or not.
	HandleExistenceCheck(context.Context, *Request) (bool, bool, error)

	// Cleanup is invoked during an unmount of a backend to allow it to
	// handle any cleanup like connection closing or releasing of file handles.
	Cleanup(context.Context)

	// InvalidateKey may be invoked when an object is modified that belongs
	// to the backend. The backend can use this to clear any caches or reset
	// internal state as needed.
	InvalidateKey(context.Context, string)

	// Setup is used to set up the backend based on the provided backend
	// configuration.
	Setup(context.Context, *BackendConfig) error

	// Type returns the BackendType for the particular backend
	Type() BackendType
}

// BackendConfig is provided to the factory to initialize the backend
type BackendConfig struct {
	// View should not be stored, and should only be used for initialization
	StorageView Storage

	// The backend should use this logger. The log should not contain any secrets.
	Logger log.Logger

	// System provides a view into a subset of safe system information that
	// is useful for backends, such as the default/max lease TTLs
	System SystemView

	// BackendUUID is a unique identifier provided to this backend. It's useful
	// when a backend needs a consistent and unique string without using storage.
	BackendUUID string

	// Config is the opaque user configuration provided when mounting
	Config map[string]string
}

// Factory is the factory function to create a logical backend.
type Factory func(context.Context, *BackendConfig) (Backend, error)

// Paths is the structure of special paths that is used for SpecialPaths.
type Paths struct {
	// Root are the API paths that require a root token to access
	Root []string

	// Unauthenticated are the API paths that can be accessed without any auth.
	// These can't be regular expressions, it is either exact match, a prefix
	// match and/or a wildcard match. For prefix match, append '*' as a suffix.
	// For a wildcard match, use '+' in the segment to match any identifier
	// (e.g. 'foo/+/bar'). Note that '+' can't be adjacent to a non-slash.
	Unauthenticated []string

	// LocalStorage are storage paths (prefixes) that are local to this cluster;
	// this indicates that these paths should not be replicated across performance clusters
	// (DR replication is unaffected).
	LocalStorage []string

	// SealWrapStorage are storage paths that, when using a capable seal,
	// should be seal wrapped with extra encryption. It is exact matching
	// unless it ends with '/' in which case it will be treated as a prefix.
	SealWrapStorage []string
}

type Auditor interface {
	AuditRequest(ctx context.Context, input *LogInput) error
	AuditResponse(ctx context.Context, input *LogInput) error
}

// Externaler allows us to check if a backend is running externally (i.e., over GRPC)
type Externaler interface {
	IsExternal() bool
}

type PluginVersion struct {
	Version string
}

// PluginVersioner is an optional interface to return version info.
type PluginVersioner interface {
	// PluginVersion returns the version for the backend
	PluginVersion() PluginVersion
}

var EmptyPluginVersion = PluginVersion{""}


text:
package com.cloudbees.jenkins;

import hudson.Extension;
import hudson.model.AbstractProject;
import hudson.model.PeriodicWork;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.github.GitHubPlugin;
import org.jenkinsci.plugins.github.webhook.WebhookManager;

import java.net.URL;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

import static org.jenkinsci.plugins.github.util.FluentIterableWrapper.from;
import static org.jenkinsci.plugins.github.util.JobInfoHelpers.associatedNames;
import static org.jenkinsci.plugins.github.util.JobInfoHelpers.isAlive;

/**
 * Removes post-commit hooks from repositories that we no longer care.
 *
 * This runs periodically in a delayed fashion to avoid hitting GitHub too often.
 *
 * @author Kohsuke Kawaguchi
 */
@Extension
public class Cleaner extends PeriodicWork {
    /**
     * Queue contains repo names prepared to cleanup.
     * After configure method on job, trigger calls {@link #onStop(AbstractProject)}
     * which converts to repo names with help of contributors.
     *
     * This queue is thread-safe, so any thread can write or
     * fetch names to this queue without additional sync
     */
    private final Queue<GitHubRepositoryName> cleanQueue = new ConcurrentLinkedQueue<GitHubRepositoryName>();

    /**
     * Called when a {@link GitHubPushTrigger} is about to be removed.
     */
    /* package */ void onStop(AbstractProject<?, ?> job) {
        cleanQueue.addAll(GitHubRepositoryNameContributor.parseAssociatedNames(job));
    }

    @Override
    public long getRecurrencePeriod() {
        return TimeUnit.MINUTES.toMillis(3);
    }

    /**
     * Each run this work fetches alive repo names (which has trigger for it)
     * then if names queue is not empty (any job was reconfigured with GH trigger change),
     * next name passed to {@link WebhookManager} with list of active names to check and unregister old hooks
     */
    @Override
    protected void doRun() throws Exception {
        URL url = GitHubPlugin.configuration().getHookUrl();

        List<AbstractProject> jobs = Jenkins.getInstance().getAllItems(AbstractProject.class);
        List<GitHubRepositoryName> aliveRepos = from(jobs)
                .filter(isAlive())  // live repos
                .transformAndConcat(associatedNames()).toList();

        while (!cleanQueue.isEmpty()) {
            GitHubRepositoryName name = cleanQueue.poll();

            WebhookManager.forHookUrl(url).unregisterFor(name, aliveRepos);
        }
    }

    public static Cleaner get() {
        return PeriodicWork.all().get(Cleaner.class);
    }
}


text:
set :application, 'heathen'

require 'infrad'

Infrad.deploy(self, app: application)

set(:rack_env) { stage }

set :branch,   fetch(:branch, "master")

# =========================================================================
# Dependencies
# =========================================================================
depend :remote, :command, "gem"
depend :remote, :command, "git"

# =========================================================================
# Extensions
# =========================================================================
def compile(template)
  location = fetch(:template_dir, File.expand_path('../deploy', __FILE__)) + "/#{template}"
  config   = ERB.new File.read(location)
  config.result(binding)
end

namespace :deploy do
  desc 'Restarts the application.'
  task :restart, :roles => :app do
    pid = "#{deploy_to}/.unicorn.pid"
    run "test -f #{pid} && kill -USR2 `cat #{pid}` || true"
  end

  namespace :ifad do
    # Harden permisssions up
    on :after, :only => %w( deploy:setup deploy:create_symlink ),
      :except => { :no_release => true } do
      run '/home/rails/bin/setup_permissions'
    end

    desc '[internal] Symlink ruby version'
    task :symlink_ruby_version, :except => { :no_release => true } do
      run "ln -s #{deploy_to}/.ruby-version #{release_path}"
    end
    after 'deploy:update_code', 'deploy:ifad:symlink_ruby_version'
  end

  namespace :secret do
    desc '[internal] Creates the secret.rb configuration file in shared path.'
    task :setup do
      run "mkdir -p #{shared_path}/config"
      put compile('secret.rb.erb'), "#{shared_path}/config/secret.rb"
    end
    after "deploy:setup", "deploy:secret:setup"

    desc '[internal] Updates the symlink for secret.rb file to the just deployed release.'
    task :symlink do
      run "ln -nfs #{shared_path}/config/secret.rb #{release_path}/config/secret.rb"
    end
    after "deploy:update_code", "deploy:secret:symlink"
  end
end

namespace :heathen do
  namespace :cache do
    desc 'Clears the cache, causing access to existing conversion urls to reprocess content'
    task :clear, roles: :app do
      run "cd #{release_path}; #{rake} heathen:cache:clear RACK_ENV=#{rack_env}"
    end
  end

  namespace :redis do
    desc "Clear the redis database keys"
    task :clear, roles: :app do
      run "cd #{release_path}; #{rake} heathen:redis:clear RACK_ENV=#{rack_env}"
    end
  end

  desc 'Clear the redis database keys and the cache'
  task :clear, roles: :app do
    run "cd #{release_path}; #{rake} heathen:clear RACK_ENV=#{rack_env}"
  end
end

after 'deploy', 'deploy:cleanup'

require 'bundler/capistrano'
set :bundle_flags, "--deployment --quiet --binstubs #{deploy_to}/bin"

#require 'airbrake/capistrano'


text:
CREATE FUNCTION [dbo].[udf_CalculateEndTerm]
(
	@initial int
)
RETURNS INT
AS
BEGIN

	declare @initialstr varchar(6) = convert(varchar(6), @initial), @year int, @end varchar(6)

	set @year = convert(int,substring(@initialstr, 0, 5)) + 1
	set @end = convert(varchar(4), @year) + '01'

	RETURN @end

END


text:
package org.mjd.xml;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

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

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.BasicConfigurator;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import org.mjd.util.TestConstants;
import org.mjd.xml.domain.Model;

/**
 * The Class XMLGeneratorTest.
 *
 * This class validates the operations of generating
 * the xml files of the maven repository.
 *
 * @author Luis Eduardo Ferro Diez - Innova4j
 */
public class XMLGeneratorTest {

	private JAXBContext jaxbContext;
	private XMLGenerator xmlGenerator;
	private String groupId = "com.oracle.adf";
	private String artifactId = "adf-faces";
	private String version = "11.1.1.7.0";
	private String packaging = "jar";
	private String modelVersion = "4.0.0";
	private String name = artifactId;
	private String description = "Generated by maven jar deployer.";

	@BeforeClass
	public static void beforeClass(){
		BasicConfigurator.configure();
	}

	@Before
	public void beforeMethod(){
		try {
			xmlGenerator = new DefaultXMLGenerator();
			jaxbContext = JAXBContext.newInstance(Model.class);
		} catch (JAXBException e) {
			fail(e.getMessage());
			e.printStackTrace();
		}
	}
	/**
	 * Test generate meta data for dependency success.
	 */
	@Test
	public void testGeneratePomDependencySuccess(){
		Path pom = Paths.get(System.getProperty("user.dir")+ TestConstants.DUMMY_RESULT_PATH+"pom.xml");

		Model project = new Model();
		project.setGroupId(groupId);
		project.setArtifactId(artifactId);
		project.setVersion(version);
		project.setPackaging(packaging);
		project.setName(name);
		project.setDescription(description);
		project.setModelVersion(modelVersion);

		xmlGenerator.generateDependencyPom(project, pom);

		assertTrue(Files.exists(pom));
		try {
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			Model projectSaved = ((JAXBElement<Model>) unmarshaller.unmarshal(pom.toFile())).getValue();
			assertEquals(groupId, projectSaved.getGroupId());
			assertEquals(artifactId, projectSaved.getArtifactId());
			assertEquals(version, projectSaved.getVersion());
			assertEquals(packaging, projectSaved.getPackaging());
			assertEquals(name, projectSaved.getName());
			assertEquals(description, projectSaved.getDescription());
			assertEquals(modelVersion, projectSaved.getModelVersion());
		} catch (JAXBException e) {
			fail(e.getMessage());
			e.printStackTrace();
		}finally{
			try {
				Files.deleteIfExists(pom);
			} catch (IOException e) {
				fail(e.getMessage());
				e.printStackTrace();
			}
		}
	}

}


text:
'use strict';

// MODULES //

var resolve = require( 'path' ).resolve;
var logger = require( 'debug' );
var dirname = require( '@stdlib/utils/dirname' );
var exists = require( '@stdlib/fs/exists' );

// VARIABLES //

var debug = logger( 'pkgs:add-ons:resolve' );

// MAIN //

/**
* Inspects packages for add-ons.
*
* @private
* @param {StringArray} files - list of `package.json` files
* @param {Callback} clbk - callback to invoke upon completion
* @returns {void}
*/
function inspect( files, clbk ) {
	var total;
	var out;
	var i;

	total = files.length;
	i = -1;
	out = [];

	return next();

	/**
	* Inspects the next package.
	*
	* @private
	*/
	function next() {
		var fpath;
		var dir;

		i += 1;
		debug( 'Inspecting package %d of %d: %s', i+1, total, files[ i ] );

		dir = dirname( files[ i ] );
		fpath = resolve( dir, 'src', 'Makefile' );

		debug( 'Checking for add-on...' );
		exists( fpath, onExists );
	}

	/**
	* Callback invoked upon testing if a file exists.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @param {boolean} bool - boolean indicating whether a file exists
	* @returns {void}
	*/
	function onExists( error, bool ) {
		var j = i + 1;
		if ( error ) {
			debug( 'Encountered an error when testing for add-on: %s (%d of %d). Error: %s', files[ i ], j, total, error.message );
		} else if ( bool ) {
			debug( 'Detected add-on.' );
			out.push( dirname( files[ i ] ) );
		} else {
			debug( 'Unable to detect add-on.' );
		}
		return done();
	}

	/**
	* Callback invoked upon inspecting all packages.
	*
	* @private
	* @returns {void}
	*/
	function done() {
		var j;
		j = i + 1;
		if ( j < total ) {
			debug( 'Inspected %d of %d packages.', j, total );
			return next();
		}
		debug( 'Successfully inspected all packages.' );
		return clbk( null, out );
	}
}

// EXPORTS //

module.exports = inspect;


text:
using System;
using System.IO;

namespace Microsoft.DotNet.Cli.Build.Framework
{
    public class AnsiConsole
    {
        private AnsiConsole(TextWriter writer)
        {
            Writer = writer;

            OriginalForegroundColor = Console.ForegroundColor;
        }

        private int _boldRecursion;

        public static AnsiConsole GetOutput()
        {
            return new AnsiConsole(Console.Out);
        }

        public static AnsiConsole GetError()
        {
            return new AnsiConsole(Console.Error);
        }

        public TextWriter Writer { get; }

        public ConsoleColor OriginalForegroundColor { get; }

        private void SetColor(ConsoleColor color)
        {
            const int Light = 0x08;
            int c = (int)color;

            Console.ForegroundColor =
                c < 0 ? color :                                   // unknown, just use it
                _boldRecursion > 0 ? (ConsoleColor)(c | Light) :  // ensure color is light
                (ConsoleColor)(c & ~Light);                       // ensure color is dark
        }

        private void SetBold(bool bold)
        {
            _boldRecursion += bold ? 1 : -1;
            if (_boldRecursion > 1 || (_boldRecursion == 1 && !bold))
            {
                return;
            }

            // switches on _boldRecursion to handle boldness
            SetColor(Console.ForegroundColor);
        }

        public void WriteLine(string message)
        {
            Write(message);
            Writer.WriteLine();
        }

        public void Write(string message)
        {
            var escapeScan = 0;
            for (;;)
            {
                var escapeIndex = message.IndexOf("\x1b[", escapeScan);
                if (escapeIndex == -1)
                {
                    var text = message.Substring(escapeScan);
                    Writer.Write(text);
                    break;
                }
                else
                {
                    var startIndex = escapeIndex + 2;
                    var endIndex = startIndex;
                    while (endIndex != message.Length &&
                        message[endIndex] >= 0x20 &&
                        message[endIndex] <= 0x3f)
                    {
                        endIndex += 1;
                    }

                    var text = message.Substring(escapeScan, escapeIndex - escapeScan);
                    Writer.Write(text);
                    if (endIndex == message.Length)
                    {
                        break;
                    }

                    switch (message[endIndex])
                    {
                        case 'm':
                            int value;
                            if (int.TryParse(message.Substring(startIndex, endIndex - startIndex), out value))
                            {
                                switch (value)
                                {
                                    case 1:
                                        SetBold(true);
                                        break;
                                    case 22:
                                        SetBold(false);
                                        break;
                                    case 30:
                                        SetColor(ConsoleColor.Black);
                                        break;
                                    case 31:
                                        SetColor(ConsoleColor.Red);
                                        break;
                                    case 32:
                                        SetColor(ConsoleColor.Green);
                                        break;
                                    case 33:
                                        SetColor(ConsoleColor.Yellow);
                                        break;
                                    case 34:
                                        SetColor(ConsoleColor.Blue);
                                        break;
                                    case 35:
                                        SetColor(ConsoleColor.Magenta);
                                        break;
                                    case 36:
                                        SetColor(ConsoleColor.Cyan);
                                        break;
                                    case 37:
                                        SetColor(ConsoleColor.Gray);
                                        break;
                                    case 39:
                                        Console.ForegroundColor = OriginalForegroundColor;
                                        break;
                                }
                            }
                            break;
                    }

                    escapeScan = endIndex + 1;
                }
            }
        }
    }
}


text:
const config = require('./src/utils/config');

const COMMON_ENV = {
  ...config.db,

  // Use a single connection to execute migrations.
  pool: {
    min: 1,
    max: 1,
  },
  migrations: {
    tableName: 'knex_migrations',
    directory: 'db/migrations',
  },
};

// Feel free to create any number of other environments.
// The ones below are a best attempt at sensible defaults.
module.exports = {
  // Developer's local machine
  development: {
    ...COMMON_ENV,

    seeds: {
      directory: 'db/seeds-dev',
    },
  },

  // Production environment
  production: {
    ...COMMON_ENV,

    seeds: {
      directory: 'db/seeds-dev', // TODO: change to -prod before final deployment
    },
  },
};


text:
namespace Umbraco.Cms.Infrastructure.Persistence.DatabaseAnnotations;

/// <summary>
///     Attribute that represents a Primary Key
/// </summary>
/// <remarks>
///     By default, Clustered and AutoIncrement is set to true.
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
public class PrimaryKeyColumnAttribute : Attribute
{
    public PrimaryKeyColumnAttribute()
    {
        Clustered = true;
        AutoIncrement = true;
    }

    /// <summary>
    ///     Gets or sets a boolean indicating whether the primary key is clustered.
    /// </summary>
    /// <remarks>Defaults to true</remarks>
    public bool Clustered { get; set; }

    /// <summary>
    ///     Gets or sets a boolean indicating whether the primary key is auto incremented.
    /// </summary>
    /// <remarks>Defaults to true</remarks>
    public bool AutoIncrement { get; set; }

    /// <summary>
    ///     Gets or sets the name of the PrimaryKey.
    /// </summary>
    /// <remarks>
    ///     Overrides the default naming of a PrimaryKey constraint:
    ///     PK_tableName
    /// </remarks>
    public string? Name { get; set; }

    /// <summary>
    ///     Gets or sets the names of the columns for this PrimaryKey.
    /// </summary>
    /// <remarks>
    ///     Should only be used if the PrimaryKey spans over multiple columns.
    ///     Usage: [nodeId], [otherColumn]
    /// </remarks>
    public string? OnColumns { get; set; }

    /// <summary>
    ///     Gets or sets the Identity Seed, which is used for Sql Ce databases.
    /// </summary>
    /// <remarks>
    ///     We'll only look for changes to seeding and apply them if the configured database
    ///     is an Sql Ce database.
    /// </remarks>
    public int IdentitySeed { get; set; }
}


text:
Basic Implementation of GENERATOR - YIELD, WEBSOCKET, GRAPHQL

### Contributor
[Kristoforusrp]

### License
[MIT](./LICENSE)

### Basic Usage
- [yield]
- [graphql]
- [websocket]

[yield]: https://github.com/kristoforusrp/tryout-01/tree/master/yield
[graphql]: https://github.com/kristoforusrp/tryout-01/tree/master/graphql
[websocket]: https://github.com/kristoforusrp/tryout-01/tree/master/websocket
[Kristoforusrp]: https://github.com/kristoforusrp


text:
package com.thoughtworks.go.api.spring;

import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.thoughtworks.go.api.ApiVersion;
import com.thoughtworks.go.server.service.support.toggle.FeatureToggleService;
import com.thoughtworks.go.spark.RerouteLatestApis;
import com.thoughtworks.go.spark.spring.RouteEntry;
import com.thoughtworks.go.spark.spring.RouteInformationProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import spark.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;

import static com.thoughtworks.go.api.ApiVersion.LATEST_VERSION_MIMETYPE;

@Component
public class RerouteLatestApisImpl implements RerouteLatestApis, ApplicationContextAware {
    private final RouteInformationProvider routeInformationProvider;
    private final FeatureToggleService features;
    private ApplicationContext applicationContext;
    private RouteToggles routeToggles;

    @Autowired
    public RerouteLatestApisImpl(RouteInformationProvider routeInformationProvider, FeatureToggleService features) {
        this.routeInformationProvider = routeInformationProvider;
        this.features = features;
    }

    // ignore special paths and those that are toggled off
    private boolean shouldIgnore(RouteEntry entry) {
        if (routeToggles.matches(entry)) {
            return !routeToggles.isToggledOn(entry);
        }

        return entry.getAcceptedType().equals("*/*");
    }

    // ignore feed API paths
    private boolean ignoreFeedApis(String path) {
        return StringUtils.startsWithIgnoreCase(path, "/api/feed/");
    }

    @Override
    public void registerLatest() {
        List<RouteEntry> routes = routeInformationProvider.getRoutes();
        Multimap<String, ApiVersion> pathToVersionsMap = LinkedHashMultimap.create();

        routeToggles = resolveRouteToggles();

        routes.forEach(entry -> {
            if (shouldIgnore(entry) || ignoreFeedApis(entry.getPath())) {
                return;
            }

            ApiVersion version = ApiVersion.parse(entry.getAcceptedType());
            pathToVersionsMap.put(entry.getPath(), version);
        });

        routes.forEach(routeEntry -> {
            if (shouldIgnore(routeEntry) || ignoreFeedApis(routeEntry.getPath())) {
                return;
            }

            // get the api versions for this path
            Collection<ApiVersion> apiVersions = pathToVersionsMap.get(routeEntry.getPath());
            // get the max version supported by this path
            ApiVersion maxVersion = apiVersions.stream().max(Comparator.naturalOrder()).orElseThrow(() -> new IllegalArgumentException("Unable to lookup apiversion for " + routeEntry.getPath()));

            // if this route corresponds to the latest version, then also register that route with latest version.
            if (maxVersion.mimeType().equals(routeEntry.getAcceptedType())) {
                Service service = routeInformationProvider.getService();
                if (routeEntry.getTarget() instanceof Route) {
                    service.addRoute(routeEntry.getHttpMethod(), RouteImpl.create(routeEntry.getPath(), LATEST_VERSION_MIMETYPE, (Route) routeEntry.getTarget()));
                } else if (routeEntry.getTarget() instanceof Filter) {
                    service.addFilter(routeEntry.getHttpMethod(), new FilterImpl(routeEntry.getPath(), LATEST_VERSION_MIMETYPE, ((Filter) routeEntry.getTarget())) {
                        @Override
                        public void handle(Request request, Response response) throws Exception {
                            ((Filter) routeEntry.getTarget()).handle(request, response);
                        }
                    });
                } else {
                    throw new IllegalArgumentException("Unexpected target type " + routeEntry.getTarget().getClass());
                }
            }

        });
        routeInformationProvider.cacheRouteInformation();
    }

    private RouteToggles resolveRouteToggles() {
        return new RouteToggles(applicationContext.getBeansWithAnnotation(ToggleRegisterLatest.class).values().stream().
                reduce(new ArrayList<>(), (BiFunction<List<RouteToggle>, Object, List<RouteToggle>>) (all, o) -> {
                    for (ToggleRegisterLatest meta : o.getClass().getAnnotationsByType(ToggleRegisterLatest.class)) {
                        all.add(new RouteToggle(meta.controllerPath(), meta.apiVersion(), meta.as(), meta.includeDescendants()));
                    }
                    return all;
                }, (l, r) -> r) /* ignored, not parallel */,
                features);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}


text:
About memory profiling in Ruby.

## Notes

WIP: just dropping some unorganised notes for now..

### Get current ruby process memory usage

See also:

* [Get current ruby process memory usage (SO)](https://stackoverflow.com/questions/7220896/get-current-ruby-process-memory-usage)
* [os gem](https://rubygems.org/gems/os)

Running the [test_get_process_memory.rb](./test_get_process_memory.rb) script:

    $ ruby test_get_process_memory.rb
    RSS according to OS.rss_bytes: 17.5104 MB
    RSS according to ps: 17.522688 MB

### memory_profiler gem

* [memory_profiler gem](https://rubygems.org/gems/memory_profiler)
* [memory_profiler github](https://github.com/SamSaffron/memory_profiler)
* [Ruby on Rails Memory Profiling (2015)](https://thejspr.com/blog/ruby-on-rails-memory-profiling/)

### With NewRelic

<https://docs.newrelic.com/docs/agents/ruby-agent/features/developer-mode>
Developer mode is removed and no longer supported as of Ruby agent version 4.1.0.

Include the newrelic_rpm gem in your Gemfile and invoke it thus:

NewRelic::Agent::Samplers::MemorySampler.new.sampler.get_sample

## Credits and References

* [os gem](https://rubygems.org/gems/os)
* [memory_profiler gem](https://rubygems.org/gems/memory_profiler)
* [How do I track down a memory leak in my Ruby code? (SO)](https://stackoverflow.com/questions/20956401/how-do-i-track-down-a-memory-leak-in-my-ruby-code)
* [rack-mini-profiler - the Secret Weapon of Ruby and Rails Speed](https://www.speedshop.co/2015/08/05/rack-mini-profiler-the-secret-weapon.html)
* [Finding the cause of a memory leak in Ruby](https://stackoverflow.com/questions/20385767/finding-the-cause-of-a-memory-leak-in-ruby)
* [Memory-hungry Ruby daemons](http://www.mikeperham.com/2009/05/25/memory-hungry-ruby-daemons/)
* [Visualizing Your Ruby Heap](https://tenderlovemaking.com/2017/09/27/visualizing-your-ruby-heap.html)


text:
require_relative "../server/comments.rb"

require 'test/unit'
require 'rack/test'

#
#  These test-cases make simulated HTTP-requests against our application.
#
class HTTPSiteTests < Test::Unit::TestCase

  include Rack::Test::Methods

  def app
    CommentStore
  end

  #
  # Unknown end-points should return a redirect.
  #
  def test_missing_endpoints

    #
    # Unknown end-points return a 302-redirect
    #
    %w( /  /help /version /api /foo ).each do |endpoint|

      get endpoint
      assert_equal(last_response.status, 302,
                   "We got a redirect for a missing end-point" )
    end
  end

  #
  # Test getting comments for an ID returns JSON.
  #
  def test_get
    get "/comments/foo"
    assert_equal( 200, last_response.status, "We got a 200 response" )

    assert( last_response.body =~ /^comments\(\[/, "The result looked like JSON" )
  end

  #
  #  Test various error-handlers for setting comments.
  #
  def test_set

    #
    #  Missing body
    #
    data = '{"author":"Steve","id":"foo"}'
    post '/comments/test', JSON.parse(data)

    assert_equal( 500, last_response.status, "A missing body was rejected" )
    assert( last_response.body =~ /Missing.*body/i,
            "A missing body was identified");

    #
    #  Missing author
    #
    data = '{"body":"Steve left this","id":"foo"}'
    post '/comments/test', JSON.parse(data)

    assert_equal( 500, last_response.status, "A missing author was rejected" )
    assert( last_response.body =~ /Missing.*author/i,
            "A missing author was identified");

    #
    #  Spam is rejected
    #
    data = '{"body":"Viagra is good","author":"Bobby"}'
    post '/comments/test', JSON.parse(data)

    assert_equal( 500, last_response.status, "SPAM was rejected" )
    assert( last_response.body =~ /spam/i,
            "SPAM was identified");

    #
    #  Not going to test adding because that's going to touch the
    # production use.
    #
  end

end


text:
/**
 *需要jquery
 */
var CommView = (function () {
    var option = {
        title: '',
        subtitle: '',
        navmenu: {
            isShow: false,
            content: [
                { text: 'sectionA', attr: { id: "A", name: "A" } },
                { text: 'sectionB', attr: { id: "B", name: "B" } }
            ]
        },
        content: '',
        navquestion: { isShow: false, content: [] }
    };

    var CommView = function () {
        //标题
        this.title = $('#title');
        //副标题
        this.subtitle = $('#sub_title');
        //左上菜单导航区
        this.navmenu = $('#nav_menu');
        //内容
        this.content = $('#content');
        //问题导航区
        this.navquestion = $('#nav_question');

        this.option = option;
    };

    CommView.prototype.show = function (option) {
        var _this = this;
        _this.option = option;//$.extend(_this.option, option);
        var _option = _this.option;

        _this.showTitle(_option.title);

        if (_option.subtitle) {
            _this.subtitle.show();
            _this.showSubTitle(_option.subtitle);
        } else {
            _this.subtitle.hide();
        }

        if (_option.content) {
            _this.showContent(_option.content);
        }

        if (_option.navmenu && _option.navmenu.isShow) {
            _this.navmenu.show();
            var html = _this.getNavMenuHtml();
            _this.showNavMenu(html);
        } else {
            _this.navmenu.hide();
        }

        if (_option.navquestion && _option.navquestion.isShow) {
            _this.navquestion.show();
            var html = _this.getNavQuestionHtml();
            _this.showNavQuestion(html);
        } else {
            _this.navquestion.hide();
        }
    };

    CommView.prototype.getNavMenuHtml = function () {
        var _this = this;
        var html = '';
        var navMenu = _this.option.navmenu.content;
        if (navMenu instanceof Array) {
            var len = navMenu.length;
            for (var i = 0; i < len; i++) {
                var item = navMenu[i];
                html += _this.navMenuItem(item);
            }
        }
        return html;
    }

    CommView.prototype.navMenuItem = function (data) {
        var val = data['text'];
        var pros = data['attr'];

        var isCurrent = data['isCurrent'];

        var html = '<input type="button" ';

        if (isCurrent) {
            html += ' class="btn-blue" ';
        } else {
            html += ' class="btn-lightblue" ';
        }

        var attrHtml = '';
        for (var p in pros) {
            attrHtml += p + '="' + pros[p] + '"';
        }
        attrHtml += 'value="' + val + '"';
        html += attrHtml + ' />';
        return html;
    }

    CommView.prototype.getNavQuestionHtml = function () {
        var _this = this;
        var html = '';
        var navQuestion = _this.option.navquestion.content;
        if (navQuestion instanceof Array) {
            var len = navQuestion.length;
            for (var i = 0; i < len; i++) {
                var item = navQuestion[i];
                html += _this.navQuestionItem(item);
            }
        }
        return html;
    }

    CommView.prototype.navQuestionItem = function (data) {
        var html = '<input type="button" nav="questionPage" value="" ';
        var attrHtml = '';
        var pros = data['attr'];
        var isCurrent = data['isCurrent'];
        if (isCurrent) {
            html += ' class="btn-pagenow" '
        } else {
            html += ' class="btn-page" '
        }
        for (var p in pros) {
            attrHtml += p + '="' + pros[p] + '"';
        }

        html += attrHtml + ' />';

        return html;
    }

    //展示内容
    CommView.prototype.showContent = function (html) {
        var _this = this;
        _this.content.html(html);
    };

    //展示标题
    CommView.prototype.showTitle = function (html) {
        var _this = this;
        _this.title.html(html);
    };

    //展示标题
    CommView.prototype.showNavMenu = function (html) {
        var _this = this;
        _this.navmenu.html(html);
    };

    //展示副标题栏
    CommView.prototype.showSubTitle = function (html) {
        var _this = this;
        if (html) {
            var stHtml = '';
            //var arr = html.split(' ');
            //var len = arr.length;
            //if (len > 1) {
            //    stHtml = '' + arr[0] + '';
            //    for (var i = 1; i < len; i++) {
            //        stHtml += arr[i];
            //    }
            //} else {
                stHtml = html;
            //}

            html = '' + stHtml + '';
            _this.subtitle.show().html(html);
        } else {
            _this.subtitle.css({ display: 'none' }).hide();
        }

    };

    //显示问题导航
    CommView.prototype.showNavQuestion = function (html) {
        var _this = this;
        _this.navquestion.html(html);
    };

    CommView.prototype.initPapeNow = function (jqObj) {
        //恢复当前样式
        $('.paperpage>input').removeClass().addClass("btn-page");
        jqObj.removeClass().addClass('btn-pagenow');
    };

    CommView.prototype.getTplHtml = function (tplname, data) {
        var contenthtml = new TemplateBuilder().getHtml(tplname, data);
        return contenthtml;
    };

    CommView.prototype.NumToChar = function (index) {
        var num = 65 + index;
        var char = String.fromCharCode(num);
        return char;
    };

    CommView.prototype.FormatChoices = function (choiceArr) {
        var _this = this;
        if (choiceArr instanceof Array) {
            var len = choiceArr.length;
            for (var i = 0; i < len; i++) {
                var item = choiceArr[i];
                choiceArr[i] = _this.NumToChar(i) + '.' + item;
            }
        }
        return choiceArr;
    };
    CommView.prototype.FormatAnswer = function (data) {
        var _this = this;
        if (data) {
            var answerInfo = '';
            var answerArr = data.split('|');
            var answerLen = answerArr.length;
            var questionNum = 1;
            for (var i = 0; i < answerLen; i++) {
                if (answerArr[i] >= 0) {
                    answerInfo += (questionNum++) + '.' + _this.NumToChar(parseInt(answerArr[i])) + '
';
                }
            }
            return answerInfo;
        }
        return data;
    };

    CommView.prototype.FormatAnswerToArr = function (data) {
        var _this = this;
        if (data) {
            var answerArr = data.split('|');
            return answerArr;
        }
        return data;
    };

    return CommView;
})()


text:
require 'rails_helper'

RSpec.describe UserLink, :type => :model do
  pending "add some examples to (or delete) #{__FILE__}"
end


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

  <title>Description of resolve_names</title>
  <meta name="keywords" content="resolve_names">
  <meta name="description" content="RESOLVE_NAMES - returns files/folders that can be found by the pattern">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html © 2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../m2html.css">

resolve_names

PURPOSE

RESOLVE_NAMES - returns files/folders that can be found by the pattern

SYNOPSIS

function out = resolve_names( pattern )

DESCRIPTION

 RESOLVE_NAMES - returns files/folders that can be found by the pattern

CROSS-REFERENCE INFORMATION

This function calls:

resolve_names	RESOLVE_NAMES - returns files/folders that can be found by the pattern

This function is called by:

resolve_names	RESOLVE_NAMES - returns files/folders that can be found by the pattern

SOURCE CODE

0001 function out = resolve_names( pattern )
0002 % RESOLVE_NAMES - returns files/folders that can be found by the pattern
0003 %
0004 %
0005 pts = regexp(pattern, '(?<=\*[^/]*)/(?=.)', 'split');
0006 baseDir = pts{1};
0007 dirFs = dir( baseDir );
0008 finds = {};
0009
0010 if isempty(dirFs)
0011     out = false;
0012     return;
0013 end
0014
0015 for k=1:length(dirFs)
0016     % Ignoring not folders
0017     if( any( strcmp( dirFs(k).name, {'.', '..'} ) ) )
0018         continue;
0019     end
0020
0021     fullFind = fullfile( fileparts(baseDir), dirFs(k).name );
0022     %% Faz a varredura recursiva ou não
0023     if length(pts) > 1 && any(baseDir == '*')
0024         childFinds = resolve_names( fullfile( fullFind, pts{2:end} ) );
0025         if ~islogical(childFinds) && ~isempty(childFinds)
0026             for n = 1:length( childFinds )
0027                 finds{end+1} = childFinds{n};
0028             end
0029         end
0030     else
0031         finds{end+1} = fullFind;
0032     end
0033 end
0034 out = finds;

<address>Generated on Thu 23-Feb-2017 17:54:44 by m2html © 2005</address>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Psiloglonium finkii Petr.

### Remarks
null


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Blätterpilze 1: 12 (1910)

#### Original name
Hygrophorus aureus Arrh., 1863

### Remarks
null


text:
<?php
namespace Phalcon\Assets
{

    class Exception extends \Phalcon\Exception
    {
    }
}