text:
<link rel="import" href="/icons.html">
<link rel="import" href="/shared_styles.html">
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">

<dom-module id="supervised-user-learn-more">
  <template>

        $i18n{supervisedUserLearnMoreTitle}
        <iron-icon icon="user-manager:supervisor-account"></iron-icon>

$i18nRaw{supervisedUserLearnMoreText}

        <paper-button id="done" class="action primary" on-tap="onDoneTap_">
          $i18n{supervisedUserLearnMoreDone}
        </paper-button>

  </template>

</dom-module>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package erp.cfd;

import cfd.DAttributeOptionImpuestoRetencion;
import cfd.DAttributeOptionImpuestoTraslado;
import cfd.ver33.DElementConceptoImpuestos;
import erp.data.SDataConstantsSys;
import erp.mod.SModSysConsts;
import erp.mtrn.data.SDataDpsEntryTax;
import java.util.ArrayList;
import sa.lib.SLibUtils;

/**
 *
 * @author Juan Barajas, Sergio Flores
 */
public class SCfdDataConcepto {

    public static final int LEN_DESCRIPCION = 1000;
    private static final int INT_COMMERCE_DECS = 2;

    protected int mnCfdType;
    protected boolean mbHasIntCommerceComplement;
    protected String msClaveProdServ;
    protected String msNoIdentificacion;
    protected double mdCantidad;
    protected String msClaveUnidad;
    protected String msUnidad;
    protected String msDescripcion;
    protected double mdValorUnitario;
    protected double mdImporte;
    protected double mdDescuento;
    protected ArrayList<SCfdDataImpuesto> maImpuestosXml;
    protected String msPredial;

    /**
     * Creates a CFD Concepto XML node.
     * @param cfdType CFD type. Supported options any constant in SDataConstantsSys.TRNS_TP_CFD_...
     * Helps formatting some of the attributes of the Concepto XML node, according of the type of CFD provided.
     */
    public SCfdDataConcepto(final int cfdType) {
        mnCfdType = cfdType;
        mbHasIntCommerceComplement = false;
        msClaveProdServ = "";
        msNoIdentificacion = "";
        mdCantidad = 0;
        msClaveUnidad = "";
        msUnidad = "";
        msDescripcion = "";
        mdValorUnitario = 0;
        mdImporte = 0;
        mdDescuento = 0;
        maImpuestosXml = new ArrayList<>();
        msPredial = "";
    }

    /*
     * Private methods
     */

    /**
     * Remove trailing zeros from decimal part.
     * @param decValue Decimal value as text.
     * @param requiredDecs Minimum required decimals.
     * @return
     */
    private String removeTrailingZeros(final String decValue, final int requiredDecs) {
        int pointIndex = decValue.lastIndexOf('.');
        String newDecValue = decValue;

        /*
        Decimal value as text: 15042.150000
        Minimum required decimals: 2

        value: 15042.1500
        index: 0123456789
        */

        if (pointIndex != -1) {
            int trailingZeros = 0;

            for (int index = decValue.length() - 1; index > (pointIndex + requiredDecs); index--) {
                if (decValue.charAt(index) == '0') {
                    trailingZeros++;
                }
                else {
                    break;
                }
            }

            if (trailingZeros > 0) {
                newDecValue = newDecValue.substring(0, decValue.length() - trailingZeros);
            }
        }

        return newDecValue;
    }

    /*
     * Public methods
     */

    public void setHasIntCommerceComplement(boolean b) { mbHasIntCommerceComplement = b; }
    public void setClaveProdServ(String s) { msClaveProdServ = s; }
    public void setNoIdentificacion(String s) { msNoIdentificacion = s; }
    public void setCantidad(double d) { mdCantidad = d; }
    public void setClaveUnidad(String s) { msClaveUnidad = s; }
    public void setUnidad(String s) { msUnidad = s; }
    public void setDescripcion(String s) { String descripcion = s.replaceAll("\n", " "); if (descripcion.length() > LEN_DESCRIPCION) { descripcion = descripcion.substring(0, LEN_DESCRIPCION); } msDescripcion = descripcion; }
    public void setValorUnitario(double d) { mdValorUnitario = d; }
    public void setImporte(double d) { mdImporte = d; }
    public void setDescuento(double d) { mdDescuento = d; }
    public void setPredial(String s) { msPredial = s; }

    public boolean hasIntCommerceComplement() { return mbHasIntCommerceComplement; }
    public int getCfdType() { return mnCfdType; }
    public String getClaveProdServ() { return msClaveProdServ; }
    public String getNoIdentificacion() { return msNoIdentificacion; }
    public double getCantidad() { return mdCantidad; }
    public String getClaveUnidad() { return msClaveUnidad; }
    public String getUnidad() { return msUnidad; }
    public String getDescripcion() { return msDescripcion; }
    public double getValorUnitario() { return mdValorUnitario; }
    public double getImporte() { return mdImporte; }
    public double getDescuento() { return mdDescuento; }
    public String getPredial() { return msPredial; }

    public ArrayList<SCfdDataImpuesto> getCfdDataImpuestos() { return maImpuestosXml; }

    /**
     * Computed values for taxes.
     * @param entry
     */
    public void computeCfdImpuestosConceptos(final erp.mtrn.data.SDataDpsEntry entry) {
        SCfdDataImpuesto impuestoXml = null;

        try {
            for (SDataDpsEntryTax tax : entry.getDbmsEntryTaxes()) {
                if (!SLibUtils.belongsTo(tax.getFkTaxCalculationTypeId(), new int[] { SModSysConsts.FINS_TP_TAX_CAL_RATE, SModSysConsts.FINS_TP_TAX_CAL_EXEMPT })) {
                    throw new Exception("El tipo de cálculo '" + tax.getDbmsTaxCalculationType() + "' del impuesto '" + tax.getDbmsTax() + "' no está soportado.");
                }
                else if (entry.getSubtotalCy_r() > 0) {
                    impuestoXml = new SCfdDataImpuesto();

                    switch (tax.getFkTaxTypeId()) {
                        case SModSysConsts.FINS_TP_TAX_RETAINED:
                            switch (tax.getDbmsCfdTaxId()) {
                                case SModSysConsts.FINS_CFD_TAX_IVA:
                                    impuestoXml.setImpuestoTipo(SModSysConsts.FINS_TP_TAX_RETAINED);
                                    impuestoXml.setImpuesto(DAttributeOptionImpuestoRetencion.CFD_IVA);
                                    break;
                                case SModSysConsts.FINS_CFD_TAX_ISR:
                                    impuestoXml.setImpuestoTipo(SModSysConsts.FINS_TP_TAX_RETAINED);
                                    impuestoXml.setImpuesto(DAttributeOptionImpuestoRetencion.CFD_ISR);
                                    break;
                                default:
                                    throw new Exception("Todos los impuestos retenidos deben ser conocidos (" + tax.getDbmsCfdTaxId() + ").");
                            }
                            break;

                        case SModSysConsts.FINS_TP_TAX_CHARGED:
                            switch (tax.getDbmsCfdTaxId()) {
                                case SModSysConsts.FINS_CFD_TAX_IVA:
                                    impuestoXml.setImpuestoTipo(SModSysConsts.FINS_TP_TAX_CHARGED);
                                    impuestoXml.setImpuesto(DAttributeOptionImpuestoTraslado.CFD_IVA);
                                    break;
                                case SModSysConsts.FINS_CFD_TAX_IEPS:
                                    impuestoXml.setImpuestoTipo(SModSysConsts.FINS_TP_TAX_CHARGED);
                                    impuestoXml.setImpuesto(DAttributeOptionImpuestoTraslado.CFD_IEPS);
                                    break;
                                default:
                                    throw new Exception("Todos los impuestos trasladados deben ser conocidos (" + tax.getDbmsCfdTaxId() + ").");
                            }
                            break;

                        default:
                            throw new Exception("Todos los tipos de impuestos deben ser conocidos (" + tax.getFkTaxTypeId() + ").");
                    }

                    impuestoXml.setBase(entry.getSubtotalCy_r());
                    impuestoXml.setImpuestoClave(tax.getDbmsCfdTax());
                    impuestoXml.setTasa(tax.getPercentage());
                    impuestoXml.setImporte(tax.getTaxCy());
                    impuestoXml.setTipoFactor(tax.getDbmsTaxCalculationType());

                    maImpuestosXml.add(impuestoXml);
                }
            }
        }
        catch (Exception e) {
            SLibUtils.showException(this, e);
        }
    }

    /**
     * Create node for concept version 3.3.
     * @return XML node of class cfd.ver33.DElementConcepto.
     * @throws Exception
     */
    public cfd.ver33.DElementConcepto createRootElementConcept33() throws Exception {
        cfd.ver33.DElementConcepto concepto = new cfd.ver33.DElementConcepto();

        concepto.getAttClaveProdServ().setString(msClaveProdServ);
        concepto.getAttNoIdentificacion().setString(msNoIdentificacion);
        concepto.getAttCantidad().setDouble(mdCantidad);
        concepto.getAttClaveUnidad().setString(msClaveUnidad);
        concepto.getAttUnidad().setString(msUnidad);
        concepto.getAttDescripcion().setString(msDescripcion);
        concepto.getAttValorUnitario().setDouble(mdValorUnitario);
        concepto.getAttImporte().setDouble(mdImporte);
        concepto.getAttDescuento().setDouble(mdDescuento);

        if (mbHasIntCommerceComplement) {
            String valorOriginal;
            String valorIntCommerce;

            valorOriginal = concepto.getAttValorUnitario().getAttributeForOriginalString();
            valorOriginal = valorOriginal.substring(0, valorOriginal.length() - 1);
            valorIntCommerce = removeTrailingZeros(valorOriginal, INT_COMMERCE_DECS);

            if (valorIntCommerce.length() < valorOriginal.length()) {
                concepto.getAttValorUnitario().setDecimals(concepto.getAttValorUnitario().getDecimals() - (valorOriginal.length() - valorIntCommerce.length()));
            }
        }
        else {
            switch (mnCfdType) {
                case SDataConstantsSys.TRNS_TP_CFD_INV:
                    break;
                case SDataConstantsSys.TRNS_TP_CFD_PAY_REC:
                    concepto.getAttCantidad().setDecimals(0);
                    concepto.getAttValorUnitario().setDecimals(0);
                    concepto.getAttImporte().setDecimals(0);
                    break;
                case SDataConstantsSys.TRNS_TP_CFD_PAYROLL:
                    concepto.getAttCantidad().setDecimals(0);
                    break;
                default:
            }
        }

        // Taxes:

        cfd.ver33.DElementConceptoImpuestosRetenciones impuestosRetenciones = new cfd.ver33.DElementConceptoImpuestosRetenciones();
        cfd.ver33.DElementConceptoImpuestosTraslados impuestosTrasladados = new cfd.ver33.DElementConceptoImpuestosTraslados();

        for (SCfdDataImpuesto impuesto : maImpuestosXml) {
            switch (impuesto.getImpuestoTipo()) {
                case SModSysConsts.FINS_TP_TAX_RETAINED:
                    impuestosRetenciones.getEltImpuestoRetenciones().add((cfd.ver33.DElementConceptoImpuestoRetencion) impuesto.createRootElementConceptoImpuesto33());
                    break;
                case SModSysConsts.FINS_TP_TAX_CHARGED:
                    impuestosTrasladados.getEltImpuestoTrasladados().add((cfd.ver33.DElementConceptoImpuestoTraslado) impuesto.createRootElementConceptoImpuesto33());
                    break;
                default:
            }
        }

        if (!impuestosTrasladados.getEltImpuestoTrasladados().isEmpty() || !impuestosRetenciones.getEltImpuestoRetenciones().isEmpty()) {
            concepto.setEltOpcConceptoImpuestos(new DElementConceptoImpuestos());
        }

        if (!impuestosTrasladados.getEltImpuestoTrasladados().isEmpty()) {
            concepto.getEltOpcConceptoImpuestos().setEltOpcImpuestosTrasladados(impuestosTrasladados);
        }

        if (!impuestosRetenciones.getEltImpuestoRetenciones().isEmpty()) {
            concepto.getEltOpcConceptoImpuestos().setEltOpcImpuestosRetenciones(impuestosRetenciones);
        }

        // Predial account:

        if (!msPredial.isEmpty()) {
            cfd.ver33.DElementConceptoCuentaPredial cuentaPredial = new cfd.ver33.DElementConceptoCuentaPredial();
            cuentaPredial.getAttNumero().setString(msPredial);
            concepto.setEltOpcConceptoCuentaPredial(cuentaPredial);
        }

        return concepto;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#import "SSESysExSpeedController.h"
#import "SSECombinationOutputStream.h"
#import "SSEMIDIController.h"

#import <SnoizeMIDI/SnoizeMIDI.h>

@interface  SSESysExSpeedController (Private)

- (void)captureEndpointsAndExternalDevices;
- (void)releaseEndpointsAndExternalDevices;
- (void)midiSetupChanged:(NSNotification *)notification;
- (void)midiObjectChanged:(NSNotification *)notification;

- (int)effectiveSpeedForItem:(SMMIDIObject*)item;

- (void)invalidateRowAndParent:(NSInteger)row;

@end

@implementation SSESysExSpeedController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [endpoints release];
    [externalDevices release];

    [super dealloc];
}

- (void) awakeFromNib
{
    [outlineView setAutoresizesOutlineColumn:NO];

    // Workaround to get continuous updates from the sliders in the table view.
    // You can't just set it, or its cell, to be continuous -- that still doesn't
    // give you continuous updates through the normal table view interface.
    // What DOES work is to have the cell message us directly.
    NSTableColumn* col = [outlineView tableColumnWithIdentifier:@"speed"];
    [[col dataCell] setTarget:self];
    [[col dataCell] setAction:@selector(takeSpeedFromSelectedCellInTableView:)];
}

- (void)willShow
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(midiSetupChanged:) name:SMClientSetupChangedNotification object:[SMClient sharedClient]];

    [self captureEndpointsAndExternalDevices];

    [outlineView reloadData];

    NSInteger customBufferSize = [[NSUserDefaults standardUserDefaults] integerForKey:SSECustomSysexBufferSizePreferenceKey];
    [bufferSizePopUpButton selectItemWithTag:customBufferSize];
    if ([bufferSizePopUpButton selectedTag] != customBufferSize) {
        [bufferSizePopUpButton selectItemWithTag:0];
    }
}

- (void)willHide
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SMClientSetupChangedNotification object:[SMClient sharedClient]];

    [self releaseEndpointsAndExternalDevices];

    [outlineView reloadData];
}

//
// Actions
//

- (void)takeSpeedFromSelectedCellInTableView:(id)sender
{
    // sender is the outline view; get the selected cell to find its new value.
    NSCell* cell = [outlineView selectedCell];
    int newValue = [cell intValue];

    // Don't actually set the value while we're tracking -- no need to update CoreMIDI
    // continuously.  Instead, remember which item is getting tracked and what its value
    // is "supposed" to be.  When tracking finishes, the new value comes through
    // -outlineView:setObjectValue:..., and we'll set it for real.
    NSInteger row = [outlineView clickedRow];
    SMMIDIObject* item = (SMMIDIObject*)[outlineView itemAtRow:row];
    trackingMIDIObject = item;
    speedOfTrackingMIDIObject = newValue;

    // update the slider value based on the effective speed (which may be different than the tracking value)
    int effectiveValue = [self effectiveSpeedForItem:item];
    if (newValue != effectiveValue) {
        [cell setIntValue:effectiveValue];
    }

    // redisplay
    [self invalidateRowAndParent:row];
}

- (IBAction)changeBufferSize:(id)sender
{
    NSInteger customBufferSize = [bufferSizePopUpButton selectedTag];
    if (customBufferSize == 0) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:SSECustomSysexBufferSizePreferenceKey];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setInteger:customBufferSize forKey:SSECustomSysexBufferSizePreferenceKey];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:SSECustomSysexBufferSizePreferenceChangedNotification object:nil];
}

@end

@implementation SSESysExSpeedController (DelegatesNotificationsDataSources)

- (id)outlineView:(NSOutlineView *)anOutlineView child:(int)index ofItem:(id)item
{
    id child = nil;

    if (item == nil) {
        if (index < [endpoints count]) {
            child = [endpoints objectAtIndex:index];
        }
    } else {
        SMDestinationEndpoint* endpoint = (SMDestinationEndpoint*)item;
        NSArray* connectedExternalDevices = [endpoint connectedExternalDevices];
        if (index < [connectedExternalDevices count]) {
            child = [[endpoint connectedExternalDevices] objectAtIndex:index];
        }
    }

    return child;
}

- (BOOL)outlineView:(NSOutlineView *)anOutlineView isItemExpandable:(id)item
{
    BOOL isItemExpandable = NO;

    if (item == nil) {
        isItemExpandable = YES;
    } else if ([item isKindOfClass:[SMDestinationEndpoint class]]) {
        SMDestinationEndpoint* endpoint = (SMDestinationEndpoint*)item;
        isItemExpandable = ([[endpoint connectedExternalDevices] count] > 0);
    }

    return isItemExpandable;
}

- (NSInteger)outlineView:(NSOutlineView *)anOutlineView numberOfChildrenOfItem:(id)item
{
    NSInteger childCount = 0;

    if (item == nil) {
        childCount = [endpoints count];
    } else if ([item isKindOfClass:[SMDestinationEndpoint class]]) {
        SMDestinationEndpoint* endpoint = (SMDestinationEndpoint*)item;
        childCount = [[endpoint connectedExternalDevices] count];
    }

    return childCount;
}

- (id)outlineView:(NSOutlineView *)anOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
    id objectValue = nil;

    if (item && tableColumn) {
        NSString *identifier = [tableColumn identifier];

        if ([identifier isEqualToString:@"name"]) {
            objectValue = [item name];
        } else if ([identifier isEqualToString:@"speed"] || [identifier isEqualToString:@"bytesPerSecond"]) {
            int speed = [self effectiveSpeedForItem:(SMMIDIObject*)item];
            objectValue = [NSNumber numberWithInt:speed];
        } else if ([identifier isEqualToString:@"percent"]) {
            int speed = [self effectiveSpeedForItem:(SMMIDIObject*)item];
            float percent = (speed / 3125.0) * 100.0;
            objectValue = [NSNumber numberWithFloat:percent];
        }
    }

    return objectValue;
}

- (void)outlineView:(NSOutlineView *)anOutlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
    if (item && tableColumn) {
        NSString *identifier = [tableColumn identifier];

        if ([identifier isEqualToString:@"speed"]) {
            int newValue = [object intValue];
            SMMIDIObject* midiObject = (SMMIDIObject*)item;
            if (newValue > 0 && newValue != [midiObject maxSysExSpeed]) {
                [midiObject setMaxSysExSpeed:newValue];

                // Work around bug where CoreMIDI doesn't pay attention to the new speed
                [[SMClient sharedClient] forceCoreMIDIToUseNewSysExSpeed];
            }

            trackingMIDIObject = nil;
        }
    }
}

@end

@implementation SSESysExSpeedController (Private)

- (void)captureEndpointsAndExternalDevices
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    NSEnumerator *enumerator;
    id midiObject;

    enumerator = [endpoints objectEnumerator];
    while ((midiObject = [enumerator nextObject])) {
        [center removeObserver:self name:SMMIDIObjectPropertyChangedNotification object:midiObject];
    }

    enumerator = [externalDevices objectEnumerator];
    while ((midiObject = [enumerator nextObject])) {
        [center removeObserver:self name:SMMIDIObjectPropertyChangedNotification object:midiObject];
    }

    endpoints = [[SSECombinationOutputStream destinationEndpoints] retain];
    externalDevices = [[SMExternalDevice externalDevices] retain];

    enumerator = [endpoints objectEnumerator];
    while ((midiObject = [enumerator nextObject])) {
        [center addObserver:self selector:@selector(midiObjectChanged:) name:SMMIDIObjectPropertyChangedNotification object:midiObject];
    }

    enumerator = [externalDevices objectEnumerator];
    while ((midiObject = [enumerator nextObject])) {
        [center addObserver:self selector:@selector(midiObjectChanged:) name:SMMIDIObjectPropertyChangedNotification object:midiObject];
    }
}

- (void)releaseEndpointsAndExternalDevices
{
    [endpoints release];
    endpoints = nil;
    [externalDevices release];
    externalDevices = nil;
}

- (void)midiSetupChanged:(NSNotification *)notification
{
    [self captureEndpointsAndExternalDevices];

    if ([[outlineView window] isVisible]) {
        [outlineView reloadData];
    }
}

- (void)midiObjectChanged:(NSNotification *)notification
{
    NSString* propertyName = [[notification userInfo] objectForKey:SMMIDIObjectChangedPropertyName];
    if ([propertyName isEqualToString:(NSString *)kMIDIPropertyName]) {
        // invalidate only the row for this object
        NSInteger row = [outlineView rowForItem:[notification object]];
        [outlineView setNeedsDisplayInRect:[outlineView rectOfRow:row]];
    } else if ([propertyName isEqualToString:(NSString *)kMIDIPropertyMaxSysExSpeed]) {
        // invalidate this row and the parent (if any)
        NSInteger row = [outlineView rowForItem:[notification object]];
        [self invalidateRowAndParent:row];
    }
}

- (int)effectiveSpeedForItem:(SMMIDIObject*)item
{
    int effectiveSpeed = (item == trackingMIDIObject) ? speedOfTrackingMIDIObject : [item maxSysExSpeed];

    if ([item isKindOfClass:[SMDestinationEndpoint class]]) {
        // Return the minimum of this endpoint's speed and all of its external devices' speeds
        NSEnumerator* oe = [[(SMDestinationEndpoint*)item connectedExternalDevices] objectEnumerator];
        SMMIDIObject* extDevice;
        while ((extDevice = [oe nextObject])) {
            int extDeviceSpeed = (extDevice == trackingMIDIObject) ? speedOfTrackingMIDIObject : [extDevice maxSysExSpeed];
            effectiveSpeed = MIN(effectiveSpeed, extDeviceSpeed);
        }
    }

    return effectiveSpeed;
}

- (void)invalidateRowAndParent:(NSInteger)row
{
    if (row >= 0) {
        [outlineView setNeedsDisplayInRect:[outlineView rectOfRow:row]];

        NSInteger level = [outlineView levelForRow:row];
        if (level > 0) {
            // walk up rows until we hit one at a higher level -- that will be our parent
            while (row > 0 && [outlineView levelForRow:--row] == level)
                ;   // nothing needs doing
            [outlineView setNeedsDisplayInRect:[outlineView rectOfRow:row]];
        }
    }
}

@end


text:
- infos = Information about the profile plugin is in keys below
- infos/author = Thomas Waser <thomas.waser@libelektra.org>
- infos/licence = BSD
- infos/needs =
- infos/provides =
- infos/recommends =
- infos/placements = postgetstorage presetstorage
- infos/status = maintained libc nodep global preview unfinished
- infos/metadata =
- infos/description = helps switching between configuration profiles

## Usage

Following the elektra keyname convention application configurations are stored under `/sw/org/myapp/#` and `/sw/org/myapp/#0/current`is the profile to be used.
The `profile` plugin provides an easy way to switch configuration profiles.

The key `/sw/org/myapp/#0/profile` defines what profile should be used as `current`, e.g. `/sw/org/myapp/#0/profile = myprofile`.
If a key `/sw/org/myapp/#0/myprofile/key` is found and no key `/sw/org/myapp/#0/current/key` exists an override key will be created linking `/sw/org/myapp/#0/currrent/key` to `/sw/org/myapp/#0/myapp/key`
If neither `/sw/org/myapp/#0/current/key` nor `/sw/org/myapp/#0/myprofile/key` is found, but `/sw/org/myapp/#0/%/key`, `/sw/org/myapp/#0/current/key` will be linked to `/sw/org/myapp/#0/%/key`.

So a cascading lookup will automatically implement following
preferences (next to the namespace preferences):

1. Usage of key in `current`
2. Usage of key in the profile set with `profile`
3. Usage of key in the `%` fallback profile

## Example

Suppose we have the configuration file `profile.ini` in `~/.config`:

    % cat profile.ini
    []
    profile = myprofile

    [current]
    key2 = will win

    [myprofile]
    key1 = test1
    key2 = test2

    [%]
    key2 = failed?
    key3 = test3

Then we simply mount it *without* the profile plugin:

    % kdb mount profile.ini /sw/org/myapp/#0 ini

But we have to make sure that the profile plugin is mounted globally:

    % kdb global-mount profile

Then we can access `/sw/org/myapp/#0` in a profile-aware way:

    % kdb ls /sw
    spec/sw/org/myapp/#0/current/key1
    spec/sw/org/myapp/#0/current/key3
    user/sw/org/myapp/#0
    user/sw/org/myapp/#0/%
    user/sw/org/myapp/#0/%/key2
    user/sw/org/myapp/#0/%/key3
    user/sw/org/myapp/#0/current
    user/sw/org/myapp/#0/current/key2
    user/sw/org/myapp/#0/profile
    user/sw/org/myapp/#0/myprofile
    user/sw/org/myapp/#0/myprofile/key1
    user/sw/org/myapp/#0/myprofile/key2

As we can see with the `-v` option, we will fetch keys from our `myprofile` even though we request `current`:

    % kdb get -v /sw/org/myapp/#0/current/key1
    got 25 keys
    searching spec/sw/org/myapp/#0/current/key1, found: spec/sw/org/myapp/#0/current/key1, options: KDB_O_CALLBACK
    The resulting keyname is user/sw/org/myapp/#0/myprofile/key1
    test1

To switch profile we simply have to set one key:

    kdb set user/sw/org/myapp/#0/profile newprofile

Usually, this will be done via commandline by setting `proc/sw/org/myapp/#0/profile`.


text:
@extends('layouts.standard')

@section('content')

{{ trans('users.dashboard.title') }}

{{ count($clientWithoutComments) }}

{{ trans('users.dashboard.alerts.client-without-comments') }}

                                {{ trans('users.dashboard.alerts.view-more') }}

{{ count($clientWithoutMailings) }}

{{ trans('users.dashboard.alerts.client-without-mailing') }}

                                {{ trans('users.dashboard.alerts.view-more') }}

{{ count($activeBuyers) }}

{{ trans('users.dashboard.alerts.active-buyers') }}

                                {{ trans('users.dashboard.alerts.view-more') }}

{{ count($activeSellers) }}

{{ trans('users.dashboard.alerts.active-sellers') }}

                                {{ trans('users.dashboard.alerts.view-more') }}

@stop

@section('modals')

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

{{ trans('users.dashboard.modal.client-without-comments.title') }}

        @if (count($clientWithoutComments) == 0)
            {{ trans('users.dashboard.modal.no-result') }}
        @else

           @foreach($clientWithoutComments as $result)

                id }}" target="_blank">

                    {{ $result->firstname }}, {{ $result->lastname }} ({{ $result->last_comment }})

           @endforeach

        @endif

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

{{ trans('users.dashboard.modal.client-without-mailing.title') }}

        @if (count($clientWithoutMailings) == 0)
            {{ trans('users.dashboard.modal.no-result') }}
        @else

           @foreach($clientWithoutMailings as $result)

                id }}" target="_blank">

                    {{ $result->firstname }}, {{ $result->lastname }} ({{ $result->last_comment }})

           @endforeach

        @endif

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

{{ trans('users.dashboard.modal.active-buyers.title') }}

        @if (count($activeBuyers) == 0)
            {{ trans('users.dashboard.modal.no-result') }}
        @else

           @foreach($activeBuyers as $result)

                id }}" target="_blank">

                    {{ $result->firstname }}, {{ $result->lastname }}

           @endforeach

        @endif

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

{{ trans('users.dashboard.modal.active-sellers.title') }}

        @if (count($activeSellers) == 0)
            {{ trans('users.dashboard.modal.no-result') }}
        @else

           @foreach($activeSellers as $result)

                id }}" target="_blank">

                    {{ $result->firstname }}, {{ $result->lastname }}

           @endforeach

        @endif

@stop


text:
#include <ros/ros.h>
#include <myworkcell_core/LocalizePart.h>
#include <myworkcell_core/PlanCartesianPath.h>
#include <moveit/move_group_interface/move_group.h>
#include <myworkcell_core/myworkcell_node.h>>
/**
* @brief The ScanNPlan class is a client of the vision and path plan servers.  The ScanNPLan class takes
* these services, computes transforms and published commands to the robot.
*/
class ScanNPlan
{
public:
  ScanNPlan(ros::NodeHandle& nh_in) : group_("manipulator")
  {
    group_.setPlannerId("RRTConnectkConfigDefault");
    nh = nh_in;
    vision_client_ = nh.serviceClient<myworkcell_core::LocalizePart>("localize_part");
    cartesian_client_ = nh.serviceClient<myworkcell_core::PlanCartesianPath>("plan_path");
    pub_ = nh.advertise<trajectory_msgs::JointTrajectory>("/joint_path_command", 1);

    nh.param<std::string>("ref_frame_param", ref_frame, "world");
  }
/**
* @brief transformPose performs simple coordinate transformation of a Pose from the reference frame to the world frame
* @param in is the Pose of the object with respect to the base frame
* @return transformed pose with respect to the world frame in geometry_msgs::Pose message format
*/
geometry_msgs::Pose transformPose(const geometry_msgs::Pose& in) const
{
    tf::Transform in_world;
    tf::poseMsgToTF(in, in_world);

    tf::Quaternion flip_z (tf::Vector3(1, 0, 0), M_PI);
    tf::Transform flip (flip_z);

    in_world = in_world * flip;

    geometry_msgs::Pose msg;
    tf::poseTFToMsg(in_world, msg);
    return msg;
}
/**
 * @brief start performs the functionality of the node.  First, start transforms the pose from the reference frame
 * into the world frame.  Second, start sends the new pose to the planner to generate a trajectory.  Lastly, start
 * recieves the trajectory and sends it to the robot for execution.
 */
void start()
{
    ROS_INFO("Attempting to localize part");
    // Localize the part
    myworkcell_core::LocalizePart srv;
    if (nh.getParam("ref_frame_param", ref_frame));
    srv.request.base_frame = ref_frame;

    if (!vision_client_.call(srv))
    {
      ROS_ERROR("Could not localize part");
      return;
    }
    ROS_INFO_STREAM("part localized: " << srv.response);

    srv.response.pose = transformPose(srv.response.pose);

    // Plan for robot to move to part
    group_.setPoseTarget(srv.response.pose);
    group_.move();
    ROS_INFO("Done moving, planning cart path");

    // Now let's plan a motion to
    // Plan cartesian path
    myworkcell_core::PlanCartesianPath cartesian_srv;
    cartesian_srv.request.pose = srv.response.pose;
    if (!cartesian_client_.call(cartesian_srv))
    {
      ROS_ERROR("Could not plan for path");
      return;
    }

    //     Execute path
    ROS_INFO("Got cart path, executing");
    pub_.publish(cartesian_srv.response.trajectory);
    ROS_INFO("Done");
}

private:
  // Planning components

  ros::ServiceClient vision_client_;
  ros::ServiceClient cartesian_client_;
  ros::Publisher pub_;

  std::string ref_frame;
  ros::NodeHandle nh;
  moveit::planning_interface::MoveGroup group_;
};
/**
 * @brief main sets up the node, ScanNPlan class and starts the spinner
 * @param argc ROS uses this to parse remapping arguments from the command line.
 * @param argv ROS uses this to parse remapping arguments from the command line.
 * @TODO add return
 * @return no return
 */
int main(int argc, char** argv)
{
  ros::init(argc, argv, "myworkcell_node");
  ros::NodeHandle nh;
  ros::AsyncSpinner async_spinner (1);

  // Hello World
  ROS_INFO("Hello, World from a ROS Node");

  ScanNPlan app (nh);

  ros::Duration(.5).sleep();

  async_spinner.start();
  app.start();

  ros::spin();

}


text:
layout: post
unique_id: plants_vs_zombies
title: Plants vs Zombies
categories: []
locations:
---

YESTERDAY:
* Jackie had toastmaster's meetings!
* then she had sea of thieves event
* sausage and corn for dinner

TODAY:
* started playing plants vs zombies, garden warfare 2!
* Jackie's DnD night
* ordered vitality bowl's for dinner, but never arrived
  * switched to Asian Box instead
* started reading

LEARNINGS:
* need to eat healthier q.q


text:
Archive Spider is a customizable web crawler that
archives the pulled data into a tarball.

Currently the spider goes to a target index and
pulls what it reads as links. At this point it
will ask if you want to spider the links. You can
spider the links which will return a new list of links.
You then have the option to spider those as well.
Then the script archives the session.

Version 1.1 was entirely shell with a nasty regular expression for link extraction. Version 1.1 may have been very portable, but 1.2 has much better link extraction using python BeautifulSoup. Version 1.2 uses a code snippet I call netstew.py to pull the links. Here is the snippet:

#################################################

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("index.html"))

for link in soup.find_all('a'):
    print(link.get('href'))

#################################################

Link to git repo of netstew.py:
https://github.com/jpegleg/netstew

Archive Spider 1.2 iterates through the web content with the above and downloads those links, then iterates through the those links. It is not set to go infinite, nobody wants that. Instead it has a max 3 depth, controlled interactively.

Alright, lets get things setup. Get your BeautifulSoup installed where your /usr/local/scripts/netstew.py can find it.
Then place your files, including the netstew.py you want to deploy in your pwd and set up your work directory:

sudo bash ./setup.sh

Use the spider:

archive-spider

If wget hangs on a request, you can kill off the hung wget and Archive Spider
will continue on.

kill -9 wgetpidgoeshere

You can also edit the target link files while Archive Spider is running to
add, delete, or change links.

vim /home/yourusernamehere/archive-spider/runnamehere/spidered-urls.out

#################################################

archive-tick.sh

This script is for targets that have directory browsing enabled. If a site has Index of thing and you can browse the file system, archive-tick.sh can download it all!

./archive-tick.sh https://someplace/somedirectorylisting/


text:
module AdsCommon
  module Errors

    # Generic error class for non-specific errors.
    class Error < ::StandardError
    end

    # Raised if an attempt is made to authenticate with missing or wrong
    # information.
    class AuthError < Error
    end

    # Raised when OAuth access token is required.
    class OAuthVerificationRequired < AuthError
      attr_reader :oauth_url
      def initialize(oauth_url)
        @oauth_url = oauth_url
      end
    end

    # Raised if setting a non-existant property on an object
    class MissingPropertyError < Error
      attr_reader :property, :object_type
      def initialize(property, object_type)
        @property = property
        @object_type = object_type
      end
    end

    # Raised if an attempt is made to connect to the sandbox with production
    # credentials or vice-versa
    class EnvironmentMismatchError < Error
    end

    # Raised if a HTTP error like 403 or 404 has happened.
    class HttpError < Error
    end

    # Raised if an error has occured during code generation.
    class BuildError < Error
    end

    # Superclass for API exceptions. Each client library should implement its
    # own subclass with extra fields.
    class ApiException < Error
      attr_reader :message
      def initialize(message = nil)
        @message = message
      end
    end
  end
end


text:
/**
 * Created by a on 1/11/2016.
 */

/**
 * Created by a on 12/10/2015.
 */

var taskModule = angular.module("conferenceService", []);

taskModule.factory("conference", function($http){

  var authToken = 'bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJkaW51c2hhZGNrIiwianRpIjoiMjViZjZmZTItZjZjNC00ZWJhLWFmODgtNmMxNjIxOTU4OGRiIiwic3ViIjoiNTZhOWU3NTlmYjA3MTkwN2EwMDAwMDAxMjVkOWU4MGI1YzdjNGY5ODQ2NmY5MjExNzk2ZWJmNDMiLCJleHAiOjE4OTI0NDE2NzIsInRlbmFudCI6MSwiY29tcGFueSI6Mywic2NvcGUiOlt7InJlc291cmNlIjoiYWxsIiwiYWN0aW9ucyI6ImFsbCJ9XSwiaWF0IjoxNDYwNDM4MDcyfQ.aPoVPiTtoGFgnKmhdLBTzwTrQRTGWWliYujHP5NONqU';

  var getConferences = function(){

    return $http({
      method: 'GET',
      url: "http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRooms",
      headers: {
        'authorization': authToken
      }
    }).then(function(response)
    {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });

    /*return $http.get("http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRooms").then(function(response){

      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });*/
  };

  var getConference = function(name){

    return $http({
      method: 'GET',
      url: "http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom/" + name,
      headers: {
        'authorization': authToken
      }
    }).then(function(response)
    {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return undefined;
      }

    });

   /* return $http.get("http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom/" + name).then(function(response) {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return undefined;
      }

    });*/

  }

  var deleteConference = function(name){

    return $http({
      method: 'DELETE',
      url: "http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom/" + name,
      headers: {
        'authorization': authToken
      }
    }).then(function(response)
    {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });

    /*return $http.delete("http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom/" + name).then(function(response) {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });*/

  }

  var updateConference = function(conference){

    return $http({
      method: 'PUT',
      url: "http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom/" + conference.ConferenceName,
      headers: {
        'authorization': authToken
      },
      data:conference
    }).then(function(response)
    {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return null;
      }

    });

      /*return $http.put("http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom/" + conference.ConferenceName,conference).then(function(response) {
        if(response.data && response.data.IsSuccess) {

          return response.data.Result;

        }else{

          return null;
        }

      });*/

  };

  var createConference = function(conference){

    return $http({
      method: 'PUT',
      url: "http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom",
      headers: {
        'authorization': authToken
      },
      data:conference
    }).then(function(response)
    {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return undefined;
      }

    });

    /*return $http.post("http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom",conference).then(function(response) {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return undefined;
      }

    });*/

  };

  var addUserToConference = function(conferenceName,user){

    return $http({
      method: 'POST',
      url: "http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom/"+conferenceName+"/user",
      headers: {
        'authorization': authToken
      },
      data:user
    }).then(function(response)
    {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return undefined;
      }

    });

   /* return $http.post("http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom/"+conferenceName+"/user",user).then(function(response) {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return undefined;
      }

    });*/

  };

  var getConferenceUsers = function(name){

    return $http({
      method: 'GET',
      url: "http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom/" + name+"/users",
      headers: {
        'authorization': authToken
      }
    }).then(function(response)
    {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });

   /* return $http.get("http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceRoom/" + name+"/users").then(function(response) {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });*/

  };

  var deleteConferenceUser = function(userID){

    ///ConferenceConfiguration/ConferenceUser/:UserId

    return $http({
      method: 'DELETE',
      url: "http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceUser/" + userID,
      headers: {
        'authorization': authToken
      }
    }).then(function(response)
    {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });

   /* return $http.delete("http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceUser/" + userID).then(function(response) {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });*/

  };

  var updateConferenceUser = function(userID, user){

    ///ConferenceConfiguration/ConferenceUser/:UserId

    return $http({
      method: 'PUT',
      url: "http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceUser/" + userID,
      headers: {
        'authorization': authToken
      },
      data:user
    }).then(function(response)
    {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });

    /*return $http.put("http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceUser/" + userID, user).then(function(response) {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });*/

  };

  var updateConferenceUserModes = function(userID, user){

    ///ConferenceConfiguration/ConferenceUser/:UserId

    return $http({
      method: 'POST',
      url: "http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceUser/" + userID+"/Mode",
      headers: {
        'authorization': authToken
      },
      data:user
    }).then(function(response)
    {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });

    /*return $http.post("http://conference.104.131.67.21.xip.io/DVP/API/1.0.0.0/ConferenceConfiguration/ConferenceUser/" + userID+"/Mode", user).then(function(response) {
      if(response.data && response.data.IsSuccess) {

        return response.data.Result;

      }else{

        return {};
      }

    });*/

  };

  return{

    GetConferences : getConferences,
    GetConference: getConference,
    DeleteConference: deleteConference,
    CreateConference: createConference,
    UpdateConference: updateConference,
    AddUserToConference: addUserToConference,
    GetConferenceUsers: getConferenceUsers,
    DeleteConferenceUser: deleteConferenceUser,
    UpdateConferenceUser: updateConferenceUser,
    UpdateConferenceUserModes: updateConferenceUserModes,
    Conference: {}

  }

});


text:
namespace BTCTrader.APIClient.Models
{
    public class UserTransInput
    {
        public string Sort { get; set; } // sorting by desc, asc
        public int Offset { get; set; } // number of skiping records
        public int Limit { get; set; } // number of limit query
    }
}


text:
using AppShell.Desktop;

namespace AppShell.Samples.Navigation.Desktop
{
    public class NavigationApp : ShellApplication<NavigationShellCore>
    {
    }
}


text:
import itk
from sys import argv
itk.auto_progress(2)

dim = 2
IType = itk.Image[itk.US, dim]
OIType = itk.Image[itk.UC, dim]

reader = itk.ImageFileReader[IType].New( FileName=argv[1] )
kernel = itk.FlatStructuringElement[dim].Box(5)
filter  = itk.GrayscaleDilateImageFilter[IType, IType, kernel].New( reader,
                Kernel=kernel )
cast = itk.CastImageFilter[IType, OIType].New(filter)
writer = itk.ImageFileWriter[OIType].New( cast, FileName=argv[2] )

writer.Update()


text:
from tempest_lib import exceptions as lib_exc

from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest import config
from tempest import test

CONF = config.CONF

class LiveBlockMigrationNegativeTestJSON(base.BaseV2ComputeAdminTest):
    _host_key = 'OS-EXT-SRV-ATTR:host'

    @classmethod
    def resource_setup(cls):
        super(LiveBlockMigrationNegativeTestJSON, cls).resource_setup()
        if not CONF.compute_feature_enabled.live_migration:
            raise cls.skipException("Live migration is not enabled")
        cls.admin_hosts_client = cls.os_adm.hosts_client
        cls.admin_servers_client = cls.os_adm.servers_client

    def _migrate_server_to(self, server_id, dest_host):
        _resp, body = self.admin_servers_client.live_migrate_server(
            server_id, dest_host,
            CONF.compute_feature_enabled.
            block_migration_for_live_migration)
        return body

    @test.attr(type=['negative', 'gate'])
    def test_invalid_host_for_migration(self):
        # Migrating to an invalid host should not change the status
        target_host = data_utils.rand_name('host-')
        server = self.create_test_server(wait_until="ACTIVE")
        server_id = server['id']

        self.assertRaises(lib_exc.BadRequest, self._migrate_server_to,
                          server_id, target_host)
        self.servers_client.wait_for_server_status(server_id, 'ACTIVE')


text:
title: layout.form-elements.fieldsets.title
help: layout.form-elements.fieldsets.help
label: flex
---

<form action="" role="form">
  <fieldset>
    <legend>Legend of fieldset</legend>

      Name

        <input type="text" class="form-control" id="inputText" placeholder="Name">

  </fieldset>
</form>


text:
import { DDPClient } from "../ddp-client";
import { IDDPClient, IDDPMessage } from "../ddp-client/models";
import { ObjectId } from "../object-id";

import {
  IDDPMessageMethodCall,
  IDDPMessageMethodResult,
  IDDPMessageMethodUpdated,
  IMethodCallStore,
} from "./models";

import { Observable } from "rxjs/Observable";

export class Methods {
  public static instance: Methods = new Methods(); // Singleton

  public resultMessageSubscription: Observable<IDDPMessageMethodResult>;
  public updatedMessageSubscription: Observable<IDDPMessageMethodUpdated>;

  public ddpClient: IDDPClient;

  private resultCallbacks: Map<string, IMethodCallStore> = new Map<string, IMethodCallStore>();
  private updatedCallbacks: Map<string, IMethodCallStore> = new Map<string, IMethodCallStore>();

  constructor(ddpClient?: IDDPClient) {
    // This bit of code allows us to mock DDPClient with a alternate class or a localized instance of DDPClient
    if (ddpClient) {
      this.ddpClient = ddpClient;
    } else {
      this.ddpClient = DDPClient.instance;
    }

    // Create observables for method related messages
    this.resultMessageSubscription = this.ddpClient.ddpSubscription.filter(
      (msgObj: IDDPMessage) => {
        return msgObj.msg === "result";
      }
    );
    this.updatedMessageSubscription = this.ddpClient.ddpSubscription.filter(
      (msgObj: IDDPMessage) => {
        return msgObj.msg === "updated";
      }
    );

    // Dispatch observable subscriptions to their handlers
    this.resultMessageSubscription.subscribe(this.handleResult.bind(this));
    this.updatedMessageSubscription.subscribe(this.handleUpdated.bind(this));
  }

  public call(
    method: string,
    params?: any[],
    resultCallback?: Function,
    updatedCallback?: Function
  ): string {
    let methodId: ObjectId = new ObjectId();
    let methodIdStr: string = methodId.toHexString();
    let methodCallMessage: IDDPMessageMethodCall = {
      id: methodId.toHexString(),
      method,
      msg: "method",
      params,
    };

    if (resultCallback) {
      this.resultCallbacks.set(methodId.toHexString(), {
        id: methodId.toHexString(),
        method,
        params,
        resultCallback,
      });
    }

    if (updatedCallback) {
      this.updatedCallbacks.set(methodId.toHexString(), {
        id: methodId.toHexString(),
        method,
        params,
        updatedCallback,
      });
    }

    this.ddpClient.send(methodCallMessage);
    return methodIdStr;
  }

  public handleResult(msgObj: IDDPMessageMethodResult) {
    if (this.resultCallbacks.has(msgObj.id)) {
      let methodStoreItem = this.resultCallbacks.get(msgObj.id);
      methodStoreItem.resultCallback(msgObj.result, msgObj.error);
      this.resultCallbacks.delete(msgObj.id);
    }
  }

  public handleUpdated(msgObj: IDDPMessageMethodUpdated) {
    msgObj.methods.forEach(methodId => {
      if (this.updatedCallbacks.has(methodId)) {
        let methodStoreItem = this.updatedCallbacks.get(methodId);
        methodStoreItem.updatedCallback();
        this.updatedCallbacks.delete(methodId);
      }
    });
  }
}


text:
#ifndef COCOTB_EMBED_H_
#define COCOTB_EMBED_H_

#include <gpi.h>
#include <gpi_logging.h>
#include <vpi_user.h>

#ifdef __cplusplus
extern "C" {
#endif

extern void embed_init_python(void);
extern int embed_sim_init(gpi_sim_info_t *info);
extern void embed_sim_event(gpi_event_t level, const char *msg);

#ifdef __cplusplus
}
#endif

#endif /* COCOTB_EMBED_H_ */


text:
Introduction

This is the source code of two papers:

(1) Weifeng Liu and Brian Vinter, "An Efficient GPU General Sparse Matrix-Matrix Multiplication for Irregular Data".
Parallel and Distributed Processing Symposium, 2014 IEEE 28th International (IPDPS '14), pp.370-381, 19-23 May 2014. [pdf][slides].

(2) Weifeng Liu and Brian Vinter, "A Framework for General Sparse Matrix-Matrix Multiplication on GPUs and Heterogeneous Processors". Journal of Parallel and Distributed Computing (JPDC), pp.47-61, Volume 85, November 2015. (Extended version of the IPDPS '14 paper) [pdf][slides].

Contact: Weifeng Liu and Brian Vinter (vinter _at_ nbi.ku.dk).

Versions

Now this work has two separate branches: CUDA and OpenCL. The CUDA version requires an nVidia GPU, CUDA SDK and CUSP library. The OpenCL version only needs an OpenCL-enabled GPU and OpenCL compiling environment.

Update (April 2016): fixed a bug of processing long rows.

Preparation

To use this SpGEMM program, the first thing you need to do is to change the 'Makefile' with correct CUDA installation path and OpenCL libs path. Further, if you are using a CUDA device, check its compute capability (e.g., 3.5, 5.0 or above) and change item like '-arch=sm_35' if needed. Then you can build the code.

Execution

This program executes C=AB operation, where A, B and C are all sparse matrices.

You can either (1) use bhSPARSE class and call its SpGEMM method in your own code, or (2) load an off-line square matrix file (*.mtx in matrix market format) as input matrix A, then benchmark C=A^2 operation. In 'main.cpp' file, see function 'test_small_spgemm()' or 'benchmark_spgemm()' for details.

Here are some command-line execution examples using CUDA version:

(1) run SpGEMM on a small matrix

`./spgemm -cuda -spgemm 0`

(2) run SpGEMM on poisson5pt matrices generated by CUSP

`./spgemm -cuda -spgemm 1`

(3) run SpGEMM on poisson9pt matrices generated by CUSP

`./spgemm -cuda -spgemm 2`

(4) run SpGEMM on poisson7pt matrices generated by CUSP

`./spgemm -cuda -spgemm 3`

(5) run SpGEMM on poisson27pt matrices generated by CUSP

`./spgemm -cuda -spgemm 4`

(6) run SpGEMM on a matrix loaded from a matrix market file

`./spgemm -cuda -spgemm cage4.mtx`

(7) run SpGEMM on a matrix loaded from a matrix market file

`./spgemm -cuda -spgemm /home/username/matrices/cage4.mtx`

Here are some command-line execution examples using OpenCL version:

(1) run SpGEMM on a small matrix

`./spgemm -cuda -spgemm 0`

(2) run SpGEMM on a matrix loaded from a matrix market file

`./spgemm -opencl -spgemm cage4.mtx`

(3) run SpGEMM on a matrix loaded from a matrix market file

`./spgemm -opencl -spgemm /home/username/matrices/cage4.mtx`

(4) run SpGEMM (using re-allocatable system memory of AMD APU) on a matrix loaded from a matrix market file

`./spgemm -opencl-hcmp -spgemm /home/username/matrices/cage4.mtx`

Precision of value data type

The SpGEMM supports single precision and double precision floating-point numbers. The default data type is 64-bit double precision. If 32-bit single precision is required, change `typedef value_type` in 'common.h' in the CUDA version. For the OpenCL version, change `typedef value_type` in 'common.h' and `typedef vT` in files 'SpGEMM_EM_kernels.cl', 'SpGEMM_ESC_0_1_kernels.cl', 'SpGEMM_ESC_2heap_kernels.cl', 'SpGEMM_ESC_bitonic_kernels.cl' and 'SpGEMM_copyCt2C_kernels.cl'.

Tested environments

The CUDA version has been tested on nVidia GeForce GT 650M, GTX 680, GTX Titan, GTX Titan Black and GTX 980 with CUDA SDK v6.0/v6.5, CUSP v0.4.0 and multiple operating systems (Mac OS X v10.9 and Ubuntu v12.04/v14.04).

The OpenCL version has been tested on AMD Radeon HD 7970, R9 290X and A10-7850k APU with OpenCL v1.2/v2.0 and Ubuntu v12.04/v14.04.


text:
<?php

namespace Flarum\Core\Command;

use Flarum\Core\Access\AssertPermissionTrait;
use Flarum\Core\Exception\PermissionDeniedException;
use Flarum\Core\Repository\UserRepository;
use Flarum\Event\UserWillBeDeleted;
use Flarum\Core\Support\DispatchEventsTrait;
use Illuminate\Contracts\Events\Dispatcher;

class DeleteUserHandler
{
    use DispatchEventsTrait;
    use AssertPermissionTrait;

    /**
     * @var UserRepository
     */
    protected $users;

    /**
     * @param Dispatcher $events
     * @param UserRepository $users
     */
    public function __construct(Dispatcher $events, UserRepository $users)
    {
        $this->events = $events;
        $this->users = $users;
    }

    /**
     * @param DeleteUser $command
     * @return \Flarum\Core\User
     * @throws PermissionDeniedException
     */
    public function handle(DeleteUser $command)
    {
        $actor = $command->actor;
        $user = $this->users->findOrFail($command->userId, $actor);

        $this->assertCan($actor, 'delete', $user);

        $this->events->fire(
            new UserWillBeDeleted($user, $actor, $command->data)
        );

        $user->delete();

        $this->dispatchEventsFor($user, $actor);

        return $user;
    }
}


text:
"""Integers Come In All Sizes: Jerod Gawne, 2019.02.19 <https://github.com/jerodg>"""
from sys import exc_info
from traceback import print_exception
from typing import NoReturn

def main() -> NoReturn:
    a, b, c, d = (int(input()) for _ in range(4))
    print(a ** b + c ** d)

if __name__ == '__main__':
    try:
        main()
    except Exception as excp:
        print(print_exception(*exc_info()))


text:
var bowser = require('bowser');

module.exports = (function () {
    function Device() {
    }

    /**
     * Mobile devices
     * @returns {boolean}
     */
    Device.prototype.isMobile = function() {
        return bowser.mobile || bowser.tablet;
    };

    return Device;
})();


text:
XIBDocument::XIBDocument(pugi::xml_node node) {
    ScanStoryObjects(node);
}

XIBArray* XIBDocument::Objects() {
    //  Find the objects array
    for (auto curMember : _members) {
        if (strcmp(curMember->_obj->_node.name(), "objects") == 0) {
            return (XIBArray*)curMember->_obj;
        }
    }

    return NULL;
}


text:
#if TARGET_OS_IPHONE
#import "NXOAuth2.h"
#else
#import <OAuth2Client/NXOAuth2.h>
#import <Cocoa/Cocoa.h>
#endif

#import "SCConstants.h"

#import "SCSoundCloud+Private.h"

@implementation SCSoundCloud (Private)

+ (id)shared;
{
    static SCSoundCloud *shared;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [SCSoundCloud new];
    });
    return shared;
}

#pragma mark Configuration

+ (NSDictionary *)configuration;
{
    NSDictionary *configuration = [[NXOAuth2AccountStore sharedStore] configurationForAccountType:kSCAccountType];

    NSMutableDictionary *config = [NSMutableDictionary dictionary];

    [config setObject:[configuration objectForKey:kNXOAuth2AccountStoreConfigurationClientID] forKey:kSCConfigurationClientID];
    [config setObject:[configuration objectForKey:kNXOAuth2AccountStoreConfigurationSecret] forKey:kSCConfigurationSecret];
    [config setObject:[configuration objectForKey:kNXOAuth2AccountStoreConfigurationRedirectURL] forKey:kSCConfigurationRedirectURL];

    [config setObject:[configuration objectForKey:kNXOAuth2AccountStoreConfigurationAuthorizeURL] forKey:kSCConfigurationAuthorizeURL];

    if ([[configuration objectForKey:kNXOAuth2AccountStoreConfigurationTokenURL] isEqual:[NSURL URLWithString:kSCSoundCloudSandboxAccessTokenURL]]) {
        [config setObject:[NSNumber numberWithBool:YES] forKey:kSCConfigurationSandbox];
    } else {
        [config setObject:[NSNumber numberWithBool:NO] forKey:kSCConfigurationSandbox];
    }

    [config setObject:[configuration objectForKey:kSCConfigurationAPIURL] forKey:kSCConfigurationAPIURL];

    return config;
}

#pragma mark Manage Accounts

- (void)requestAccessWithUsername:(NSString *)username password:(NSString *)password;
{
    [[NXOAuth2AccountStore sharedStore] requestAccessToAccountWithType:kSCAccountType username:username password:password];
}

@end


text:
class CookieGenException(Exception):
    """
    Failed to gen sub and subp cookies without login
    """

class Timeout(Exception):
    """
    Function run timeout
    """

class LoginException(Exception):
    """
    Login error for weibo login
    """


text: <f:render section="content" />


text:
var Action = require('./action');
var messageService = require('../messageService');
var util = require('util');

var Revive = function(opts){
	opts.type = 'revive';
	opts.id = opts.entity.entityId;
	opts.singleton = true;

	Action.call(this, opts);
	this.entity = opts.entity;
	this.area = this.entity.area;
	this.map = opts.map;
	this.time = opts.reviveTime;
	this.now = Date.now();
};

util.inherits(Revive, Action);

/**
 * Update revive time
 * @api public
 */
Revive.prototype.update = function(){
	var time = Date.now();

	this.time -= time - this.now;
	if(this.time <= 10){
		this.entity.died = false;
		this.entity.hp = this.entity.maxHp/2;

		var bornPlace = this.map.getBornPlace();

		var oldPos = {x : this.entity.x, y : this.entity.y};

		var newPos = {
			x : bornPlace.x + Math.floor(Math.random() * bornPlace.width),
			y : bornPlace.y + Math.floor(Math.random() * bornPlace.height)
		};

		var watcher = {id : this.entity.entityId, type : this.entity.type};
		this.area.timer.updateObject(watcher, oldPos, newPos);
		this.area.timer.updateWatcher(watcher, oldPos, newPos, this.entity.range, this.entity.range);

		this.entity.x = newPos.x;
		this.entity.y = newPos.y;

		messageService.pushMessageByAOI(
			this.area,
			{
				route: 'onRevive',
				entityId : this.entity.entityId,
				x: this.entity.x,
				y: this.entity.y,
				hp: this.entity.hp
			},
			{x : this.entity.x, y : this.entity.y});
		this.finished = true;
		this.entity.updateTeamMemberInfo();
	}
	this.now = time;
};

module.exports = Revive;


text:
<?php

namespace OroCRM\Bundle\TaskBundle\Migrations\Schema\v1_0;

use Doctrine\DBAL\Schema\Schema;

use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;

class OroCRMTaskBundle implements Migration
{
    /**
     * @var string
     */
    protected $taskTableName = 'orocrm_task';

    /**
     * @var string
     */
    protected $taskPriorityTableName = 'orocrm_task_priority';

    /**
     * {@inheritdoc}
     */
    public function up(Schema $schema, QueryBag $queries)
    {
        $this->oroCrmCreateTaskPriorityTable($schema);
        $this->oroCrmCreateTaskTable($schema);
    }

    /**
     * @param Schema $schema
     */
    protected function oroCrmCreateTaskPriorityTable(Schema $schema)
    {
        if ($schema->hasTable($this->taskPriorityTableName)) {
            $schema->dropTable($this->taskPriorityTableName);
        }

        $table = $schema->createTable($this->taskPriorityTableName);

        $table->addColumn('name', 'string', ['notnull' => true, 'length' => 32]);
        $table->addColumn('label', 'string', ['notnull' => true, 'length' => 255]);
        $table->addColumn('`order`', 'integer', ['notnull' => true]);

        $table->setPrimaryKey(['name']);
        $table->addUniqueIndex(['label'], 'UNIQ_DB8472D3EA750E8');
    }

    /**
     * @param Schema $schema
     */
    protected function oroCrmCreateTaskTable(Schema $schema)
    {
        if ($schema->hasTable($this->taskTableName)) {
            $schema->dropTable($this->taskTableName);
        }

        $table = $schema->createTable($this->taskTableName);

        $table->addColumn('id', 'integer', ['autoincrement' => true]);
        $table->addColumn('subject', 'string', ['notnull' => false, 'length' => 255]);
        $table->addColumn('description', 'string', ['notnull' => false, 'length' => 255]);
        $table->addColumn('due_date', 'datetime');
        $table->addColumn('task_priority_name', 'string', ['notnull' => false, 'length' => 32]);
        $table->addColumn('owner_id', 'integer', ['notnull' => false]);
        $table->addColumn('related_account_id', 'integer', ['notnull' => false]);
        $table->addColumn('related_contact_id', 'integer', ['notnull' => false]);
        $table->addColumn('reporter_id', 'integer', ['notnull' => false]);
        $table->addColumn('workflow_item_id', 'integer', ['notnull' => false]);
        $table->addColumn('workflow_step_id', 'integer', ['notnull' => false]);
        $table->addColumn('createdAt', 'datetime');
        $table->addColumn('updatedAt', 'datetime', ['notnull' => false]);

        $table->setPrimaryKey(['id']);
        $table->addIndex(['task_priority_name'], 'IDX_814DEE3FD34C1E8E', []);
        $table->addIndex(['owner_id'], 'IDX_814DEE3F7E3C61F9', []);
        $table->addIndex(['related_account_id'], 'IDX_814DEE3FE774F01D', []);
        $table->addIndex(['related_contact_id'], 'IDX_814DEE3FD6204081', []);
        $table->addIndex(['reporter_id'], 'IDX_814DEE3FE1CFE6F5', []);
        $table->addIndex(['due_date'], 'task_due_date_idx');
        $table->addUniqueIndex(['workflow_item_id'], 'UNIQ_814DEE3F1023C4EE');
        $table->addIndex(['workflow_step_id'], 'IDX_814DEE3F71FE882C', []);

        $this->oroCrmCreateTaskTableForeignKeys($schema);
    }

    /**
     * @param Schema $schema
     */
    protected function oroCrmCreateTaskTableForeignKeys(Schema $schema)
    {
        $table = $schema->getTable($this->taskTableName);

        $table->addForeignKeyConstraint(
            $schema->getTable($this->taskPriorityTableName),
            ['task_priority_name'],
            ['name'],
            ['onDelete' => 'SET NULL']
        );

        $table->addForeignKeyConstraint(
            $schema->getTable('oro_user'),
            ['owner_id'],
            ['id'],
            ['onDelete' => 'SET NULL']
        );

        $table->addForeignKeyConstraint(
            $schema->getTable('orocrm_account'),
            ['related_account_id'],
            ['id'],
            ['onDelete' => 'SET NULL']
        );

        $table->addForeignKeyConstraint(
            $schema->getTable('orocrm_contact'),
            ['related_contact_id'],
            ['id'],
            ['onDelete' => 'SET NULL']
        );

        $table->addForeignKeyConstraint(
            $schema->getTable('oro_user'),
            ['reporter_id'],
            ['id'],
            ['onDelete' => 'SET NULL']
        );

        $table->addForeignKeyConstraint(
            $schema->getTable('oro_workflow_item'),
            ['workflow_item_id'],
            ['id'],
            ['onDelete' => 'SET NULL']
        );

        $table->addForeignKeyConstraint(
            $schema->getTable('oro_workflow_step'),
            ['workflow_step_id'],
            ['id'],
            ['onDelete' => 'SET NULL']
        );
    }
}


text:
class CategoryHashtagsController < ApplicationController
  before_filter :ensure_logged_in

  def check
    category_slugs = params[:category_slugs]

    ids = category_slugs.map { |category_slug| Category.query_from_hashtag_slug(category_slug).try(:id) }

    valid_categories = Category.secured(guardian).where(id: ids).map do |category|
      { slug: category.hashtag_slug, url: category.url_with_id }
    end.compact

    render json: { valid: valid_categories }
  end
end


text:
package org.apache.hadoop.hive.llap.daemon.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

import org.junit.Test;

public class TestQueryIdentifier {

  @Test (timeout = 5000)
  public void testEquality() {

    String appIdString1 = "app1";
    String appIdString2 = "app2";

    int dagId1 = 1;
    int dagId2 = 2;

    QueryIdentifier[] queryIdentifiers = new QueryIdentifier[4];

    queryIdentifiers[0] = new QueryIdentifier(appIdString1, dagId1);
    queryIdentifiers[1] = new QueryIdentifier(appIdString1, dagId2);
    queryIdentifiers[2] = new QueryIdentifier(appIdString2, dagId1);
    queryIdentifiers[3] = new QueryIdentifier(appIdString2, dagId2);

    for (int i = 0 ; i < 4 ; i++) {
      for (int j = 0 ; j < 4 ; j++) {
        if (i == j) {
          assertEquals(queryIdentifiers[i], queryIdentifiers[j]);
        } else {
          assertNotEquals(queryIdentifiers[i], queryIdentifiers[j]);
        }
      }
    }

    QueryIdentifier q11 = new QueryIdentifier(appIdString1, dagId1);
    QueryIdentifier q12 = new QueryIdentifier(appIdString1, dagId2);
    QueryIdentifier q21 = new QueryIdentifier(appIdString2, dagId1);
    QueryIdentifier q22 = new QueryIdentifier(appIdString2, dagId2);

    assertEquals(queryIdentifiers[0], q11);
    assertEquals(queryIdentifiers[1], q12);
    assertEquals(queryIdentifiers[2], q21);
    assertEquals(queryIdentifiers[3], q22);

  }
}


text:
package org.elacin.pdfextract.geom;

import org.elacin.pdfextract.content.PhysicalContent;
import org.elacin.pdfextract.content.PhysicalText;
import org.elacin.pdfextract.style.Style;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

/**
 * Created by IntelliJ IDEA. User: elacin Date: 08.12.10 Time: 03.40 To change this template use
 * File | Settings | File Templates.
 */
public class Sorting {

// ------------------------------ FIELDS ------------------------------
    @NotNull
    public static final Comparator<HasPosition> sortByLowerY = new Comparator<HasPosition>() {

        public int compare(@Nullable final HasPosition o1, @Nullable final HasPosition o2) {

            if (o1 == null) {
                return 1;
            }

            if (o2 == null) {
                return -1;
            }

            return Float.compare(o1.getPos().y, o2.getPos().y);
        }
    };
    @NotNull
    public static final Comparator<HasPosition> sortByHigherX = new Comparator<HasPosition>() {

        public int compare(@NotNull final HasPosition o1, @NotNull final HasPosition o2) {
            return Float.compare(o2.getPos().x, o1.getPos().x);
        }
    };
    @NotNull
    public static final Comparator<HasPosition> sortByLowerYThenLowerX = new Comparator<HasPosition>() {

        public int compare(@NotNull final HasPosition o1, @NotNull final HasPosition o2) {

            final int compare = Float.compare(o1.getPos().y, o2.getPos().y);

            if (compare != 0) {
                return compare;
            }

            return Float.compare(o1.getPos().x, o2.getPos().x);
        }
    };
    @NotNull
    public static final Comparator<HasPosition> sortByLowerX = new Comparator<HasPosition>() {

        public int compare(@NotNull final HasPosition o1, @NotNull final HasPosition o2) {
            return Float.compare(o1.getPos().x, o2.getPos().x);
        }
    };
    @NotNull
    public static final Comparator<HasPosition> sortBySmallestArea = new Comparator<HasPosition>() {

        public int compare(@NotNull final HasPosition o1, @NotNull final HasPosition o2) {
            return Float.compare(o1.getPos().area(), o2.getPos().area());
        }
    };
    @NotNull
    public static final Comparator<Style> sortStylesById = new Comparator<Style>() {

        public int compare(@NotNull final Style o1, @NotNull final Style o2) {
            return o1.id.compareTo(o2.id);
        }
    };
    @NotNull
    public static final Comparator<PhysicalText> sortTextByBaseLine = new Comparator<PhysicalText>() {

        public int compare(@NotNull final PhysicalText o1, @NotNull final PhysicalText o2) {
            return Float.compare(o1.getBaseLine(), o2.getBaseLine());
        }
    };
    @NotNull
    public static final Comparator<HasPosition> regionComparator = new Comparator<HasPosition>() {

        public int compare(@NotNull final HasPosition o1, @NotNull final HasPosition o2) {

            if (o1.getPos().endY < o2.getPos().y) {
                return -1;
            }

            if (o1.getPos().y > o2.getPos().endY) {
                return 1;
            }

            if (o1.getPos().endX < o2.getPos().x) {
                return -1;
            }

            if (o1.getPos().x > o2.getPos().endX) {
                return 1;
            }

            if (!MathUtils.isWithinPercent(o1.getPos().y, o2.getPos().y, 4)) {
                return Float.compare(o1.getPos().y, o2.getPos().y);
            }

            return Float.compare(o1.getPos().x, o2.getPos().x);
        }
    };

// -------------------------- PUBLIC STATIC METHODS --------------------------
    @NotNull
    public static <T extends PhysicalContent> PriorityQueue<T> createSmallestFirstQueue(
            @NotNull final List<T> graphicalRegions) {

        final int        capacity = Math.max(1, graphicalRegions.size());
        PriorityQueue<T> queue    = new PriorityQueue<T>(capacity, sortBySmallestArea);

        queue.addAll(graphicalRegions);

        return queue;
    }
}


text:
package wykopml.flows

import akka.actor.ActorSystem
import akka.http.scaladsl._
import akka.http.scaladsl.model._
import akka.http.scaladsl.unmarshalling.{Unmarshal, Unmarshaller}
import akka.stream.scaladsl._
import akka.stream.{Materializer, ThrottleMode}
import org.slf4j.LoggerFactory

import scala.concurrent.duration._
import scala.concurrent.{ExecutionContextExecutor, Future}
import scala.util.{Failure, Success}

trait FetcherFlow {

  private val logger = LoggerFactory.getLogger(getClass)

  implicit def system: ActorSystem

  implicit def executor: ExecutionContextExecutor

  implicit def materializer: Materializer

  private def wykopConnectionFlow[T] = Http().cachedHostConnectionPool[T]("www.wykop.pl", 80)

  val safeStringToUri: (String) => Uri = (str) => {
    val parts = str.split('/')
    val path = parts.foldLeft[Uri.Path](Uri.Path.Empty)(_ / _)
    Uri(path./("").toString().stripPrefix("/"))
  }

  def contentFetcherFlow = Flow[HttpRequest]
    .map { r => (r, ()) }.via(fetcherFlow[String, Unit]()).map(_._1)

  def stringToGetRequestFlow = Flow[String].map {
    url =>
      (HttpRequest(HttpMethods.GET, safeStringToUri(url)), url)
  }

  def objToGetRequestFlow[T](fn: (T) => Uri) = Flow[T].map {
    obj: T =>
      (HttpRequest(HttpMethods.GET, fn(obj)), obj)
  }

  def fetcherFlow[Output, T]()(implicit um: Unmarshaller[HttpResponse, Output]) = Flow[(HttpRequest, T)]
    .throttle(5, 1.second, 2, ThrottleMode.Shaping)
    .map {
      req =>
        {
          logger.info(s"Will retrieve ${req._1.uri}")
          req
        }
    }
    .via(wykopConnectionFlow)
    .mapAsync(8) {
      case (resTry, t) =>
        resTry match {
          case Success(response) =>
            Unmarshal(response).to[Output].map((_, t))
          case Failure(ex) => {
            logger.error("Unable to retrieve", ex)
            Future.failed(ex)
          }
        }
    }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>se.atg</groupId>
	<artifactId>catchcrud</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Catch CRUD</name>
	<description>Catch CRUD sample server application</description>
	<dependencies>
		<dependency>
			<groupId>com.yammer.dropwizard</groupId>
			<artifactId>dropwizard-core</artifactId>
			<version>0.6.2</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
		</dependency>
		<dependency>
			<groupId>com.yammer.dropwizard</groupId>
			<artifactId>dropwizard-testing</artifactId>
			<version>0.6.2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-library</artifactId>
			<version>1.3</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-core</artifactId>
			<version>1.9.5</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<archive>
						<manifest>
							<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>1.6</version>
				<configuration>
					<createDependencyReducedPom>true</createDependencyReducedPom>
					<filters>
						<filter>
							<artifact>*:*</artifact>
							<excludes>
								<exclude>META-INF/*.SF</exclude>
								<exclude>META-INF/*.DSA</exclude>
								<exclude>META-INF/*.RSA</exclude>
							</excludes>
						</filter>
					</filters>
				</configuration>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
						<configuration>
							<transformers>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<mainClass>se.atg.catchcrud.FishCatchService</mainClass>
								</transformer>
							</transformers>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
namespace blink {

// Stuff in blink:: should be renamed.
void Foo();

// Stuff in nested namespaces should be renamed.
namespace nested {
void Foo();
}  // namespace nested

// blink::protocol namespace is blacklisted.
namespace protocol {
void foo();
}  // namespace protocol

}  // namespace blink

namespace WTF {

// Stuff in WTF:: should be renamed.
void Foo();

// Stuff in nested namespaces should be renamed.
namespace nested {
void Foo();
}  // namespace nested

}  // namespace WTF

// Stuff outside blink:: and WTF:: should not be.
namespace other {
void foo();
namespace blink {
void foo();
}  // namespace blink
namespace WTF {
void foo();
}  // namespace WTF
}  // namespace other
void foo();

void G() {
  blink::Foo();
  blink::nested::Foo();
  WTF::Foo();
  WTF::nested::Foo();
  other::foo();
  foo();
  other::blink::foo();
  other::WTF::foo();
}