text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** Defines values for ServiceProviderProvisioningState. */
public final class ServiceProviderProvisioningState extends ExpandableStringEnum<ServiceProviderProvisioningState> {
    /** Static value NotProvisioned for ServiceProviderProvisioningState. */
    public static final ServiceProviderProvisioningState NOT_PROVISIONED = fromString("NotProvisioned");

    /** Static value Provisioning for ServiceProviderProvisioningState. */
    public static final ServiceProviderProvisioningState PROVISIONING = fromString("Provisioning");

    /** Static value Provisioned for ServiceProviderProvisioningState. */
    public static final ServiceProviderProvisioningState PROVISIONED = fromString("Provisioned");

    /** Static value Deprovisioning for ServiceProviderProvisioningState. */
    public static final ServiceProviderProvisioningState DEPROVISIONING = fromString("Deprovisioning");

    /**
     * Creates or finds a ServiceProviderProvisioningState from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding ServiceProviderProvisioningState.
     */
    @JsonCreator
    public static ServiceProviderProvisioningState fromString(String name) {
        return fromString(name, ServiceProviderProvisioningState.class);
    }

    /** @return known ServiceProviderProvisioningState values. */
    public static Collection<ServiceProviderProvisioningState> values() {
        return values(ServiceProviderProvisioningState.class);
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>

#include "debug.h"

#define PLUS 1
#define MINUS 0

// Simplified implementation - ignore the extra characters on a line longer
// than this
// 1024 characters + '\n' + '\0'
#define MAX_LINE 1026

typedef struct params {
    unsigned long lines;
    bool plus_minus;  // which mode is used
    char *filename;
} params_t;

params_t get_params(int argc, char *argv[]);

/* print last X lines */
int tail_minus(FILE *file, unsigned long int lines);

/* print lines starting from line number X */
void tail_plus(FILE *file, unsigned long int line);

void free_2d_array(char **array[], int size);

void print_help();

/*****************************************************************************/
int main(int argc, char *argv[]) {
    params_t params = get_params(argc, argv);
    FILE *input = NULL;
    if(params.filename == NULL) input = stdin;
    else {
        input = fopen(params.filename, "r");
        check(input, "Can't open file '%s'", params.filename);
    }
    if(params.plus_minus == MINUS) {
        int res = tail_minus(input, params.lines);
        if(res != 0) goto error;
    }
    else {
        tail_plus(input, params.lines);
    }

    fclose(input);
    return 0;
error:
    if(input) fclose(input);
    exit(EXIT_FAILURE);
}
/*****************************************************************************/

params_t get_params(int argc, char *argv[]) {
    params_t result = {
        .lines = 10,
        .plus_minus = MINUS,
        .filename = NULL
    };
    // used to test if some parameter wasn't given twice
    bool lines_set = false;
    bool filename_set = false;

    for(int i = 1; i < argc; i++) {
        if(strncmp(argv[i], "-h", 2) == 0) {
            print_help();
            exit(EXIT_SUCCESS);
        }
        else if(argv[i][0] == '-' || argv[i][0] == '+' ) {
            check(lines_set == false, "Too many parameters");
            // --5 or --b is invalid
            check(argv[i][1] != '-', "Invalid parameter %s", argv[i]);

            char *end_p;
            result.lines = strtoul(argv[i] + 1, &end_p, 10);
            check(errno == 0, "Invalid parameter %s", argv[i]);
            if(end_p == argv[i] + 1 || *end_p != '\0') {
                fail("Invalid parameter %s", argv[i]);
            }
            lines_set = true;
            result.plus_minus = (argv[i][0] == '+')? PLUS : MINUS;

            if(result.lines == 0) {
                if(result.plus_minus == PLUS) {
                    result.lines = 1;  // +0, special case, print all lines
                }
                else {
                    exit(EXIT_SUCCESS);  // -0, don't print anything
                }
            }
        }
        else {
            check(filename_set == false, "The FILE can be set only once");
            result.filename = argv[i];
            filename_set = true;
        }
    }
    return result;
error:
    print_help();
    exit(EXIT_FAILURE);
}

int tail_minus (FILE * file, unsigned long int lines_requested) {
    char s[MAX_LINE] = {'\0'};
    unsigned long int lines_saved = 0;
    char **line_buffer = (char **)calloc(lines_requested, sizeof(char *));
    check_mem(line_buffer);

    unsigned int i;
    for(i = 0; fgets(s, MAX_LINE, file) != NULL;
            i++, i = i % lines_requested) {
        if(strlen(s) >= (MAX_LINE-1) && s[MAX_LINE-2] != '\n') {
            fail("Line too long (longer lines not implemented)");
        }

        if(lines_requested > lines_saved) {
            // create new line in buffer, since we still read less lines than
            // we want to print
            assert(i <= lines_requested);
            line_buffer[i] = (char *)malloc(MAX_LINE * sizeof(char));
            check_mem(line_buffer[i]);
            strncpy(line_buffer[i], s, MAX_LINE);
            lines_saved++;
        }
        else { // overwrite older line, since we won't need it
            strncpy(line_buffer[i], s, MAX_LINE);
        }
    }
    // print the buffered lines.
    unsigned int j = 0;
    for( ; j < lines_saved; i++, j++) {
        i = i % lines_saved;
        printf("%s", line_buffer[i]);
    }
    free_2d_array(&line_buffer, lines_requested);
    return 0;
error:
    free_2d_array(&line_buffer, lines_requested);
    return -1;
}

void tail_plus(FILE *file, unsigned long int line) {
    char s[MAX_LINE+1];
    for(unsigned int i = 0; fgets(s, MAX_LINE, file) != NULL; i++) {
        // print forever if necessary (if stdio doesn't end)
        if(i >= line - 1) printf("%s", s);
    }
}

void free_2d_array(char **array_p[], int size) {
    // assumes that the array is initialized with zeros
    char **array = *array_p;
    if(array == NULL) return;
    for(int i = 0; i < size; i++) {
        if(array[i]) free(array[i]);
        array[i] = NULL;
    }
    free(array);
    *array_p = NULL;
}

void print_help() {
    puts("Usage: tail [OPTIONS] [FILE]\n"
         "Print the last 10 lines of FILE to standard output. "
         "If no FILE is given, read standard input.\n"
         "-h\tshow usage information\n"
         "-X\toutput the last X lines\n"
         "+X\toutput all the lines starting from the Xth line "
         "(`tail +1` will print everything)");
}

redpajama_set_name: RedPajamaGithub


text:
title: Videos del Spring I/O 2012
author: neodevelop
layout: post
date: 2012-06-08
url: /2012/06/08/videos-del-spring-io-2012/
categories:
  - Groovy
---
Hola!

Hace tiempo tuvimos la oportunidad de estar presentes en el Spring I/O, compartimos varias experiencias con algunos otros desarrolladores y las ponencias ofrecidas fueron de ayuda para nosotros, además de contribuir con algunas de ellas, aquí les dejo las que han sido publicadas:


text:
title: Chaijs Assertexpression Message
localeTitle: Mensaje de expresión de Chaijs
---
[@param](/users/param) {Mixed} expresión para probar la veracidad

*   [@param](/users/param) {String} mensaje para mostrar error

Escribe tus propias expresiones de prueba.
```
assert('foo' !== 'bar', 'foo is not bar');
 assert(Array.isArray(<a href='http://chaijs.com/api/assert/' target='_blank' rel='nofollow'>]), 'empty arrays are arrays');
```

detalles: \[http://chaijs.com/api/assert/


text:
package org.mule.module.hue;

import org.mule.api.ConnectionException;
import org.mule.api.ConnectionExceptionCode;
import org.mule.api.annotations.Category;
import org.mule.api.annotations.Configurable;
import org.mule.api.annotations.Connector;
import org.mule.api.annotations.Processor;
import org.mule.api.annotations.display.FriendlyName;
import org.mule.api.annotations.display.Placement;
import org.mule.api.annotations.lifecycle.Start;
import org.mule.api.annotations.param.ConnectionKey;
import org.mule.api.annotations.param.Optional;
import org.mule.module.hue.model.Command;
import org.mule.module.hue.model.GroupAttributes;
import org.mule.module.hue.model.LightAttributes;
import org.mule.module.hue.model.Schedule;
import org.mule.module.hue.model.State;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

import java.io.IOException;

import org.codehaus.jackson.map.ObjectMapper;

/**
 * Connects to the Philips Hue smart lighting system.
 * This connector does not cover the full API rather the more common things that
 * a developer would automate from Mule.
 *
 * {@sample.xml ../../../doc/hue-connector.xml.sample hue:config}
 *
 * @author ross@mulesoft.com
 */
@Connector(name = "hue", schemaVersion = "1.0", friendlyName = "Philips Hue", minMuleVersion = "3.4.0")
@Category(name = "org.mule.tooling.ui.modules.core.miscellaneous", description = "Miscellaneous")
public class HueConnector
{
    /**
     * The expected date format by this service - used to create scheduled commands
     */
    public static final String ISO86012004Format = "yyyy-MM-ddThh:mm:ss";

    /**
     * The local ip address for the hue base station
     */
    @Configurable
    private String ipAddress;

    /**
     * the username that has access to the hue base station
     */
    @Configurable
    @ConnectionKey
    private String username;

    private Client httpClient = Client.create();
    private ObjectMapper mapper = new ObjectMapper();

    /**
     * The local ip address for the hue base station
     *
     * @return The local ip address for the hue base station
     */
    public String getIpAddress()
    {
        return ipAddress;
    }

    /**
     * Sets the local ip address for the hue base station
     *
     * @param ipAddress the local ip address for the hue base station
     */
    public void setIpAddress(String ipAddress)
    {
        this.ipAddress = ipAddress;
    }

    /**
     * Gets the username that has access to the hue base station
     *
     * @return the username that has access to the hue base station
     */
    public String getUsername()
    {
        return username;
    }

    /**
     * Sets the username that has access to the hue base station
     *
     * @param userName the username that has access to the hue base station
     */
    public void setUsername(String username)
    {
        this.username = username;
    }

    /**
     * Connect
     *
     * @throws ConnectionException
     */
    @Start
    public void connect() throws ConnectionException
    {
        String res = httpClient.resource(getBaseUri()).get(String.class);
        if (res.contains("error"))
        {
            throw new ConnectionException(ConnectionExceptionCode.INCORRECT_CREDENTIALS, "unauthorized user", res);
        }
    }

    /**
     * Sets the state of an individual light
     *

     * {@sample.xml ../../../doc/Hue-connector.xml.sample hue:set-light-state}
     *
     * @param lightId the identifier for the light to change
     * @param state   the new state to apply to the light
     * @return The new state of the light
     * @throws IOException if there is a connection error or if the call returns an error response
     */
    @Processor
    public State setLightState(String lightId, State state) throws IOException
    {
        WebResource resource = httpClient.resource(getBaseUri() + "/lights/" + lightId + "/state");
        String st = mapper.writeValueAsString(state);
        String response = resource.put(String.class, st);
        if (response.contains("error"))
        {
            throw new IOException(response);
        }
        return state;
    }

    /**
     * Sets the state of a light group.  All lights in the group will be given the same state
     *

     * {@sample.xml ../../../doc/Hue-connector.xml.sample hue:set-group-state}
     *
     * @param groupId the identifier for the group to change. The bridge has a default group is 0 which includes all lights known by the bridge
     * @param state   the new state to apply to the group
     * @return The new state of the group
     * @throws IOException if there is a connection error or if the call returns an error response
     */
    @Processor
    public State setGroupState(String groupId,  @Placement(group = "State") State state) throws IOException
    {
        WebResource resource = httpClient.resource(getBaseUri() + "/groups/" + groupId + "/action");
        String response = resource.put(String.class, mapper.writeValueAsString(state));
        if (response.contains("error"))
        {
            throw new IOException(response);
        }
        return state;
    }

    /**
     * Gets a list of all lights that have been discovered by the bridge
     *

     * {@sample.xml ../../../doc/Hue-connector.xml.sample hue:get-lights}
     *
     * @return a list of all lights in the system, each light has a name and unique identification number.
     *         If there are no lights in the system then the bridge will return an empty object, {}.
     * @throws IOException if there is a connection error or if the call returns an error response
     */
    @Processor
    public String getLights() throws IOException
    {
        WebResource resource = httpClient.resource(getBaseUri() + "/lights");
        String response = resource.get(String.class);
        if (response.contains("error"))
        {
            throw new IOException(response);
        }
        return response;
    }

    /**
     * Creates a scheduled command tht will execute at a specific date and time
     *

     * {@sample.xml ../../../doc/Hue-connector.xml.sample hue:create-schedule}
     *
     * @param command     Representation of a command that that can be sent to the scheduling
     *                    API to execute the command at a specific time
     *                    i.e. 'turn the lights on in the morning at 7am'
     *                    A command represents a resource address, the HTTP verb and the body as the data to
     *                    send to the resource.
     * @param scheduleName for the new schedule. If a name is not specified then the default name, "schedule", is used.
     *                    If the name is already taken a space and number will be appended by the bridge, e.g. "schedule 1".
     * @param time        Time when the scheduled event will occur in ISO 8601:2004 format.
     *                    The bridge measures time in UTC and only accepts extended format, non-recurring, local time (YYYY-MM-DDThh:mm:ss).
     *                    Incorrectly formatted dates will raise an error of type 7. If the time is in the past an error 7 will also be raised.
     * @param description Description of the new schedule. If the description is not specified it will be empty.
     *
     * @return a string json response with either success message.  If there is an error returned then an IOExecption is thrown
     * @throws IOException if there is a connection error or if the call returns an error response
     */
    @Processor
    public String createSchedule(@Placement(group = "Schedule", order = 1) @FriendlyName("Name") String scheduleName,
                                 @Placement(group = "Schedule", order = 2) String time,
                                 @Placement(group = "Schedule", order = 3) @Optional String description,
                                 @Placement(group = "Command to Execute") Command command) throws IOException
    {
        Schedule s = new Schedule();
        s.setCommand(command);
        s.setName(scheduleName);
        s.setTime(time);
        s.setDescription(description);

        WebResource resource = httpClient.resource(getBaseUri() + "/schedules");
        String response = resource.post(String.class, mapper.writeValueAsString(s));
        if (response.contains("error"))
        {
            throw new IOException(response);
        }
        return response;

    }

    /**
     * Gets the current state of an individual light
     *

     * {@sample.xml ../../../doc/Hue-connector.xml.sample hue:get-light-state}
     *
     * @param lightId the identifier of the light to query state
     *
     * @return The complete state of the light
     * @throws IOException if there is a connection error or if the call returns an error response
     */
    @Processor
    public LightAttributes getLightState(String lightId) throws IOException
    {
        WebResource resource = httpClient.resource(getBaseUri() + "/lights/" + lightId);
        String response = resource.get(String.class);
        if (response.contains("error"))
        {
            throw new IOException(response);
        }
        System.out.println("This:" + response);
        return mapper.readValue(response, LightAttributes.class);
    }

    /**
     * Gets the current state of an individual light
     *

     * {@sample.xml ../../../doc/Hue-connector.xml.sample hue:get-group-state}
     *
     * @param groupId the identifier of the group to query state
     *
     * @return The complete state of a group
     * @throws IOException if there is a connection error or if the call returns an error response
     */
    @Processor
    public GroupAttributes getGroupState(String groupId) throws IOException
    {
        WebResource resource = httpClient.resource(getBaseUri() + "/groups/" + groupId);
        String response = resource.get(String.class);
        if (response.contains("error"))
        {
            throw new IOException(response);
        }
        return mapper.readValue(response, GroupAttributes.class);
    }

    public final String getBaseUri()
    {
        return "http://" + ipAddress + "/api/" + username;
    }
}


text:
var loadText = function(context){
	var selection = context.selection;

	for (var i = 0, l = [selection count]; i < l; i++) {
		var layer = selection[i];
		var randomNum = (Math.random() * (1500.00 - 10.00) + 10.00).toFixed(2);

		function numberWithCommas(randomNum) {
		    var parts = randomNum.toString().split(".");
		    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
		    return parts.join(".");
		}

		[layer setStringValue: "$" + numberWithCommas(randomNum)];
		[layer setName: "$" + randomNum];
		[layer adjustFrameToFit];
	}
	tools.checkPluginUpdate();
};


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('GNCApp', ['ngRoute'])
    .config(['$routeProvider', function($routeProvider) {
  $routeProvider
      .when('index.html', {
          templateUrl: 'views/home.html',
          controller: 'MainGNC'
      })
  .otherwise('/index');
}]);


text:
import { Font } from '../styling/font';
import { SegmentedBarItemBase, SegmentedBarBase, selectedIndexProperty, itemsProperty, selectedBackgroundColorProperty } from './segmented-bar-common';
import { isEnabledProperty } from '../core/view';
import { colorProperty, fontInternalProperty, fontSizeProperty } from '../styling/style-properties';
import { Color } from '../../color';
import { SDK_VERSION, layout } from '../../utils';

export * from './segmented-bar-common';

const R_ID_TABS = 0x01020013;
const R_ID_TABCONTENT = 0x01020011;
const R_ATTR_STATE_SELECTED = 0x010100a1;
const TITLE_TEXT_VIEW_ID = 16908310; // http://developer.android.com/reference/android/R.id.html#title

interface TabChangeListener {
	new (owner: SegmentedBar): android.widget.TabHost.OnTabChangeListener;
}

interface TabContentFactory {
	new (owner: SegmentedBar): android.widget.TabHost.TabContentFactory;
}

interface TabHost {
	new (context: android.content.Context, attrs: android.util.AttributeSet): android.widget.TabHost;
}

let selectedIndicatorThickness: number;

let TabHost: TabHost;
let TabChangeListener: TabChangeListener;
let TabContentFactory: TabContentFactory;

// TODO: All TabHost public methods become deprecated in API 30.
function initializeNativeClasses(): void {
	if (TabChangeListener) {
		return;
	}

	// Indicator thickness for material - 2dip. For pre-material - 5dip.
	selectedIndicatorThickness = layout.toDevicePixels(SDK_VERSION >= 21 ? 2 : 5);

	@NativeClass
	@Interfaces([android.widget.TabHost.OnTabChangeListener])
	class TabChangeListenerImpl extends java.lang.Object implements android.widget.TabHost.OnTabChangeListener {
		constructor(public owner: SegmentedBar) {
			super();

			return global.__native(this);
		}

		onTabChanged(id: string): void {
			const owner = this.owner;
			if (owner.shouldChangeSelectedIndex()) {
				owner.selectedIndex = parseInt(id);
			}
		}
	}

	@NativeClass
	@Interfaces([android.widget.TabHost.TabContentFactory])
	class TabContentFactoryImpl extends java.lang.Object implements android.widget.TabHost.TabContentFactory {
		constructor(public owner: SegmentedBar) {
			super();

			return global.__native(this);
		}

		createTabContent(tag: string): android.view.View {
			const tv = new android.widget.TextView(this.owner._context);
			// This is collapsed by default and made visible
			// by android when TabItem becomes visible/selected.
			// TODO: Try commenting visibility change.
			tv.setVisibility(android.view.View.GONE);
			tv.setMaxLines(1);
			tv.setEllipsize(android.text.TextUtils.TruncateAt.END);

			return tv;
		}
	}

	@NativeClass
	class TabHostImpl extends android.widget.TabHost {
		constructor(context: android.content.Context, attrs: android.util.AttributeSet) {
			super(context, attrs);

			return global.__native(this);
		}

		public onAttachedToWindow(): void {
			// overriden to remove the code that will steal the focus from edit fields.
		}
	}

	TabHost = TabHostImpl;
	TabChangeListener = TabChangeListenerImpl;
	TabContentFactory = TabContentFactoryImpl;
}

export class SegmentedBarItem extends SegmentedBarItemBase {
	nativeViewProtected: android.widget.TextView;

	public setupNativeView(tabIndex: number): void {
		// TabHost.TabSpec.setIndicator DOES NOT WORK once the title has been set.
		// http://stackoverflow.com/questions/2935781/modify-tab-indicator-dynamically-in-android
		const titleTextView = <android.widget.TextView>this.parent.nativeViewProtected.getTabWidget().getChildAt(tabIndex).findViewById(TITLE_TEXT_VIEW_ID);

		this.setNativeView(titleTextView);
		if (titleTextView) {
			if (this.titleDirty) {
				this._update();
			}
		}
	}

	private titleDirty: boolean;
	public _update(): void {
		const tv = this.nativeViewProtected;
		if (tv) {
			let title = this.title;
			title = title === null || title === undefined ? '' : title;
			tv.setText(title);
			this.titleDirty = false;
		} else {
			this.titleDirty = true;
		}
	}

	[colorProperty.getDefault](): number {
		return this.nativeViewProtected.getCurrentTextColor();
	}
	[colorProperty.setNative](value: Color | number) {
		const color = value instanceof Color ? value.android : value;
		this.nativeViewProtected.setTextColor(color);
	}

	[fontSizeProperty.getDefault](): { nativeSize: number } {
		return { nativeSize: this.nativeViewProtected.getTextSize() };
	}
	[fontSizeProperty.setNative](value: number | { nativeSize: number }) {
		if (typeof value === 'number') {
			this.nativeViewProtected.setTextSize(value);
		} else {
			this.nativeViewProtected.setTextSize(android.util.TypedValue.COMPLEX_UNIT_PX, value.nativeSize);
		}
	}

	[fontInternalProperty.getDefault](): android.graphics.Typeface {
		return this.nativeViewProtected.getTypeface();
	}
	[fontInternalProperty.setNative](value: Font | android.graphics.Typeface) {
		this.nativeViewProtected.setTypeface(value instanceof Font ? value.getAndroidTypeface() : value);
	}

	[selectedBackgroundColorProperty.getDefault](): android.graphics.drawable.Drawable {
		const viewGroup = <android.view.ViewGroup>this.nativeViewProtected.getParent();

		return viewGroup.getBackground();
	}
	[selectedBackgroundColorProperty.setNative](value: Color | android.graphics.drawable.Drawable) {
		const nativeView = this.nativeViewProtected;
		const viewGroup = <android.view.ViewGroup>nativeView.getParent();
		if (value instanceof Color) {
			const color = value.android;
			const backgroundDrawable = viewGroup.getBackground();
			if (SDK_VERSION > 21 && backgroundDrawable) {
				const newDrawable = tryCloneDrawable(backgroundDrawable, nativeView.getResources());
				newDrawable.setColorFilter(color, android.graphics.PorterDuff.Mode.SRC_IN);
				viewGroup.setBackground(newDrawable);
			} else {
				const stateDrawable = new android.graphics.drawable.StateListDrawable();
				const colorDrawable: android.graphics.drawable.ColorDrawable = new org.nativescript.widgets.SegmentedBarColorDrawable(color, selectedIndicatorThickness);
				const arr = Array.create('int', 1);
				arr[0] = R_ATTR_STATE_SELECTED;
				stateDrawable.addState(arr, colorDrawable);
				stateDrawable.setBounds(0, 15, viewGroup.getRight(), viewGroup.getBottom());
				viewGroup.setBackground(stateDrawable);
			}
		} else {
			const backgroundDrawable = tryCloneDrawable(value, nativeView.getResources());
			viewGroup.setBackground(backgroundDrawable);
		}
	}
}

function tryCloneDrawable(value: android.graphics.drawable.Drawable, resources: android.content.res.Resources): android.graphics.drawable.Drawable {
	if (value) {
		const constantState = value.getConstantState();
		if (constantState) {
			return constantState.newDrawable(resources);
		}
	}

	return value;
}

export class SegmentedBar extends SegmentedBarBase {
	nativeViewProtected: android.widget.TabHost;
	private _tabContentFactory: android.widget.TabHost.TabContentFactory;
	private _addingTab: boolean;

	public shouldChangeSelectedIndex(): boolean {
		return !this._addingTab;
	}

	public createNativeView() {
		initializeNativeClasses();

		const context: android.content.Context = this._context;
		const nativeView = new TabHost(context, null);

		const tabHostLayout = new android.widget.LinearLayout(context);
		tabHostLayout.setOrientation(android.widget.LinearLayout.VERTICAL);

		const tabWidget = new android.widget.TabWidget(context);
		tabWidget.setId(R_ID_TABS);
		tabHostLayout.addView(tabWidget);

		const frame = new android.widget.FrameLayout(context);
		frame.setId(R_ID_TABCONTENT);
		frame.setVisibility(android.view.View.GONE);
		tabHostLayout.addView(frame);

		nativeView.addView(tabHostLayout);

		return nativeView;
	}

	public initNativeView(): void {
		super.initNativeView();
		const nativeView = this.nativeViewProtected;
		const listener = new TabChangeListener(this);
		nativeView.setOnTabChangedListener(listener);
		(<any>nativeView).listener = listener;
		nativeView.setup();
		this._tabContentFactory = this._tabContentFactory || new TabContentFactory(this);
	}

	public disposeNativeView() {
		const nativeView: any = this.nativeViewProtected;
		nativeView.listener.owner = null;
		super.disposeNativeView();
	}

	public onLoaded() {
		super.onLoaded();

		// Can only be applied after view is loaded
		const tabWidget = this.nativeViewProtected.getTabWidget();
		if (tabWidget) {
			tabWidget.setEnabled(tabWidget.isEnabled());
		}
	}

	private insertTab(tabItem: SegmentedBarItem, index: number): void {
		const tabHost = this.nativeViewProtected;
		const tab = tabHost.newTabSpec(index + '');
		tab.setIndicator(tabItem.title + '');
		tab.setContent(this._tabContentFactory);

		this._addingTab = true;
		tabHost.addTab(tab);
		tabItem.setupNativeView(index);
		this._addingTab = false;
	}

	[selectedIndexProperty.getDefault](): number {
		return -1;
	}
	[selectedIndexProperty.setNative](value: number) {
		this.nativeViewProtected.setCurrentTab(value);
	}

	[itemsProperty.getDefault](): SegmentedBarItem[] {
		return null;
	}
	[itemsProperty.setNative](value: SegmentedBarItem[]) {
		this.nativeViewProtected.clearAllTabs();

		const newItems = value;
		if (newItems) {
			newItems.forEach((item, i, arr) => this.insertTab(item, i));
		}

		selectedIndexProperty.coerce(this);
	}
	[isEnabledProperty.setNative](value: boolean) {
		const tabWidget = this.nativeViewProtected.getTabWidget();
		if (tabWidget) {
			tabWidget.setEnabled(value);
		}
	}
}


text:
'use strict';
var yeoman = require('yeoman-generator');
var path = require('path');
var ejs = require('ejs');
var fs = require('fs');
var _ = require('case');

module.exports = yeoman.Base.extend({
  constructor: function() {
    yeoman.Base.apply(this, arguments);
    this.argument('moduleName', {type: String, required: true});
    this.argument('componentName', {type: String, required: true});
  },

  initializing: {
    paths: function() {
      fs.statSync(path.join(this.config.get('modulesPath'), this.moduleName), function(err) {
        if (err) throw err;
      })

      this.destinationRoot(path.join(this.config.get('modulesPath'), this.moduleName, 'components'));
    }
  },

  writing: {
    appendIndex: function() {
      var template = this.fs.read(this.templatePath('index.js.ejs'));
      var renderedTemplate = ejs.render(template, {'_': _, componentName: this.componentName})

      fs.appendFile(this.destinationPath('index.js'), renderedTemplate, function(err) {
        if (err) throw err;
      })

      this.log(_.pascal(this.componentName) + ' component successfully appended to ' + path.join(this.moduleName, 'components', 'index.js'));
    },

    containerJS: function() {
      this.fs.copyTpl(
        this.templatePath('Component.js.ejs'),
        this.destinationPath(_.pascal(this.componentName) + '.js'),
        { '_': _, componentName: this.componentName }
      )
    }
  }
});


text:
package io.crate.planner.node.dml;

import io.crate.analyze.where.DocKeys;
import io.crate.common.annotations.VisibleForTesting;
import io.crate.data.Row;
import io.crate.data.RowConsumer;
import io.crate.execution.dml.ShardRequestExecutor;
import io.crate.execution.dml.upsert.ShardUpsertRequest;
import io.crate.execution.engine.indexing.ShardingUpsertExecutor;
import io.crate.expression.symbol.Assignments;
import io.crate.expression.symbol.Symbol;
import io.crate.metadata.CoordinatorTxnCtx;
import io.crate.metadata.NodeContext;
import io.crate.metadata.Reference;
import io.crate.metadata.doc.DocTableInfo;
import io.crate.planner.DependencyCarrier;
import io.crate.planner.Plan;
import io.crate.planner.PlannerContext;
import io.crate.planner.operators.SubQueryResults;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.index.shard.ShardId;

import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

public final class UpdateById implements Plan {

    private final DocTableInfo table;
    private final Map<Reference, Symbol> assignmentByTargetCol;
    private final DocKeys docKeys;
    private final Assignments assignments;
    @Nullable
    private final Symbol[] returnValues;

    public UpdateById(DocTableInfo table,
                      Map<Reference, Symbol> assignmentByTargetCol,
                      DocKeys docKeys,
                      @Nullable List<Symbol> returnValues,
                      NodeContext nodeCtx) {
        this.table = table;
        this.assignments = Assignments.convert(assignmentByTargetCol, nodeCtx);
        this.assignmentByTargetCol = assignmentByTargetCol;
        this.docKeys = docKeys;
        this.returnValues = returnValues == null ? null : returnValues.toArray(new Symbol[0]);
    }

    @VisibleForTesting
    public Map<Reference, Symbol> assignmentByTargetCol() {
        return assignmentByTargetCol;
    }

    @VisibleForTesting
    public DocKeys docKeys() {
        return docKeys;
    }

    @Override
    public StatementType type() {
        return StatementType.UPDATE;
    }

    @Override
    public void executeOrFail(DependencyCarrier dependencies,
                              PlannerContext plannerContext,
                              RowConsumer consumer,
                              Row params,
                              SubQueryResults subQueryResults) {
        ShardRequestExecutor<ShardUpsertRequest> executor = createExecutor(dependencies, plannerContext);

        if (returnValues == null) {
            executor.execute(consumer, params, subQueryResults);
        } else {
            executor.executeCollectValues(consumer, params, subQueryResults);
        }
    }

    @Override
    public List<CompletableFuture<Long>> executeBulk(DependencyCarrier dependencies,
                                                     PlannerContext plannerContext,
                                                     List<Row> bulkParams,
                                                     SubQueryResults subQueryResults) {
        return createExecutor(dependencies, plannerContext)
            .executeBulk(bulkParams, subQueryResults);
    }

    private ShardRequestExecutor<ShardUpsertRequest> createExecutor(DependencyCarrier dependencies,
                                                                    PlannerContext plannerContext) {
        ClusterService clusterService = dependencies.clusterService();
        CoordinatorTxnCtx txnCtx = plannerContext.transactionContext();
        ShardUpsertRequest.Builder requestBuilder = new ShardUpsertRequest.Builder(
            txnCtx.sessionSettings(),
            ShardingUpsertExecutor.BULK_REQUEST_TIMEOUT_SETTING.setting().get(clusterService.state().metadata().settings()),
            ShardUpsertRequest.DuplicateKeyAction.UPDATE_OR_FAIL,
            true,
            assignments.targetNames(),
            null, // missing assignments are for INSERT .. ON DUPLICATE KEY UPDATE
            returnValues,
            plannerContext.jobId(),
            false
        );
        UpdateRequests updateRequests = new UpdateRequests(requestBuilder, table, assignments);
        return new ShardRequestExecutor<>(
            clusterService,
            txnCtx,
            dependencies.nodeContext(),
            table,
            updateRequests,
            dependencies.transportActionProvider().transportShardUpsertAction()::execute,
            docKeys
        );
    }

    private static class UpdateRequests implements ShardRequestExecutor.RequestGrouper<ShardUpsertRequest> {

        private final ShardUpsertRequest.Builder requestBuilder;
        private final DocTableInfo table;
        private final Assignments assignments;

        private Symbol[] assignmentSources;

        UpdateRequests(ShardUpsertRequest.Builder requestBuilder, DocTableInfo table, Assignments assignments) {
            this.requestBuilder = requestBuilder;
            this.table = table;
            this.assignments = assignments;
        }

        @Override
        public ShardUpsertRequest newRequest(ShardId shardId) {
            return requestBuilder.newRequest(shardId);
        }

        @Override
        public void bind(Row parameters, SubQueryResults subQueryResults) {
            assignmentSources = assignments.bindSources(table, parameters, subQueryResults);
        }

        @Override
        public void addItem(ShardUpsertRequest request,
                            int location,
                            String id,
                            Long version,
                            Long seqNo,
                            Long primaryTerm) {
            ShardUpsertRequest.Item item = new ShardUpsertRequest.Item(id,
                                                                       assignmentSources,
                                                                       null,
                                                                       version,
                                                                       seqNo,
                                                                       primaryTerm);
            request.add(location, item);
        }
    }
}


text:
require 'nokogiri'
require 'httparty'
require 'pry'

class CraigslistUrlGetter
  class << self

    CL_URL = "https://tampa.craigslist.org/search/cto"

    def get_links(url = CL_URL)
      response = HTTParty.get(CL_URL)
      rows = Nokogiri::HTML(response).css(".row")
      rows.map do |row|
        hdrlnk = row.css(".hdrlnk").first
        href = merge_base_url_with_car_href(hdrlnk.attributes["href"].value)
        title_text = hdrlnk.inner_text
        cl_price = row.css(".price").text.match(/\d+/).to_s.to_i
        cl_pid = row.attributes["data-pid"].value
        next if row.attributes["data-repost-of"]
        {href: href, title_text:title_text, cl_price: cl_price, cl_pid: cl_pid}
      end.reject(&:nil?)
    end

    def merge_base_url_with_car_href(car_href)
      car_href = car_href
      base_url = CL_URL.gsub("/cto", "").gsub("/search", "")
      base_url + car_href
    end

    def turn_links_into_cars(links_array)
      links_array.each do |link|
        begin
          if Car.where(cl_pid: link[:cl_pid]).empty?
            this_car = Car.new(link)
            this_scraper = CraigslistFieldScraper.new(this_car.href)
            scrape_this_car(car: this_car, scraper: this_scraper)
            this_car.save!
          end
        rescue NoMethodError => e
          Rails.logger.warn e.inspect
          if Car.where(cl_pid: link[:cl_pid]).empty?
            this_car = Car.new(link)
            this_car.hide
            this_car.save!
          end
        end
      end
    end

    def scrape_this_car(args)
      car = args[:car]
      scraper = args[:scraper]
      car.cl_ymm = scraper.scrape_ymm
      CraigslistCarProcessor.process_ymm(car) # car now has ed make, model, and year
      if (price = RushPricer.min_price(car))
        car.ed_price = price
      else
        car.hide
      end
    end
  end
end


text:
<?php

namespace MicheleAngioni\MessageBoard\Repos;

use MicheleAngioni\Support\Repos\AbstractEloquentRepository;
use MicheleAngioni\MessageBoard\Contracts\PermissionRepositoryInterface;
use MicheleAngioni\MessageBoard\Models\Permission;

class EloquentPermissionRepository extends AbstractEloquentRepository implements PermissionRepositoryInterface
{
    protected $model;

    public function __construct(Permission $model)
    {
        $this->model = $model;
    }
}


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

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.devtools.build.lib.actions.ActionContext;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionMetadata;
import com.google.devtools.build.lib.actions.ActionGraph;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.ArtifactFactory;
import com.google.devtools.build.lib.actions.ArtifactResolver;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.ExecutionStrategy;
import com.google.devtools.build.lib.actions.ExecutorInitException;
import com.google.devtools.build.lib.analysis.ArtifactsToOwnerLabels;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.buildtool.BuildRequest;
import com.google.devtools.build.lib.concurrent.ExecutorUtil;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadHostile;
import com.google.devtools.build.lib.exec.ActionContextProvider;
import com.google.devtools.build.lib.exec.ExecutorBuilder;
import com.google.devtools.build.lib.includescanning.IncludeParser.Inclusion;
import com.google.devtools.build.lib.rules.cpp.CppIncludeExtractionContext;
import com.google.devtools.build.lib.rules.cpp.CppIncludeScanningContext;
import com.google.devtools.build.lib.rules.cpp.IncludeScanner.IncludeScanningHeaderData;
import com.google.devtools.build.lib.rules.cpp.SwigIncludeScanningContext;
import com.google.devtools.build.lib.runtime.BlazeModule;
import com.google.devtools.build.lib.runtime.BlazeRuntime;
import com.google.devtools.build.lib.runtime.Command;
import com.google.devtools.build.lib.runtime.CommandEnvironment;
import com.google.devtools.build.lib.runtime.WorkspaceBuilder;
import com.google.devtools.build.lib.skyframe.MutableSupplier;
import com.google.devtools.build.lib.vfs.IORuntimeException;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunctionName;
import com.google.devtools.common.options.OptionsBase;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.logging.Logger;

/**
 * Module that provides implementations of {@link CppIncludeExtractionContext},
 * {@link CppIncludeScanningContext}, and {@link SwigIncludeScanningContext}.
 */
public class IncludeScanningModule extends BlazeModule {
  private static final Logger log = Logger.getLogger(IncludeScanningModule.class.getName());

  private static final PathFragment INCLUDE_HINTS_FILENAME =
      PathFragment.create("tools/cpp/INCLUDE_HINTS");

  private final MutableSupplier<SpawnIncludeScanner> spawnIncludeScannerSupplier =
      new MutableSupplier<>();
  private final MutableSupplier<ArtifactFactory> artifactFactory = new MutableSupplier<>();

  protected PathFragment getIncludeHintsFilename() {
    return INCLUDE_HINTS_FILENAME;
  }

  @Override
  @ThreadHostile
  public void executorInit(CommandEnvironment env, BuildRequest request, ExecutorBuilder builder) {
    builder.addActionContextProvider(
        new IncludeScanningActionContextProvider(env, request, spawnIncludeScannerSupplier));
    builder
        .addStrategyByContext(CppIncludeExtractionContext.class, "")
        .addStrategyByContext(SwigIncludeScanningContext.class, "")
        .addStrategyByContext(CppIncludeScanningContext.class, "");
  }

  @Override
  public Iterable<Class<? extends OptionsBase>> getCommandOptions(Command command) {
    return "build".equals(command.name())
        ? ImmutableList.of(IncludeScanningOptions.class)
        : ImmutableList.<Class<? extends OptionsBase>>of();
  }

  @Override
  public void beforeCommand(CommandEnvironment env) {
    artifactFactory.set(env.getSkyframeBuildView().getArtifactFactory());
  }

  @Override
  public void afterCommand() {
    spawnIncludeScannerSupplier.set(null);
    artifactFactory.set(null);
  }

  @Override
  public void workspaceInit(
      BlazeRuntime runtime, BlazeDirectories directories, WorkspaceBuilder builder) {
    builder.addSkyFunctions(getSkyFunctions(getIncludeHintsFilename()));
  }

  @VisibleForTesting
  public static ImmutableMap<SkyFunctionName, SkyFunction> getSkyFunctions(
      PathFragment includeHintsFile) {
    return ImmutableMap.of(
        IncludeScanningSkyFunctions.INCLUDE_HINTS,
        new IncludeHintsFunction(includeHintsFile));
  }

  /**
   * Implementation of {@link CppIncludeExtractionContext}.
   */
  @ExecutionStrategy(contextType = CppIncludeExtractionContext.class)
  public static final class CppIncludeExtractionContextImpl implements CppIncludeExtractionContext {
    private final CommandEnvironment env;

    CppIncludeExtractionContextImpl(CommandEnvironment env) {
      this.env = env;
    }

    @Override
    public ArtifactResolver getArtifactResolver() {
      return env.getSkyframeBuildView().getArtifactFactory();
    }
  }

  /**
   * SwigIncludeScanningContextImpl implements SwigIncludeScanningContext.
   */
  @ExecutionStrategy(contextType = SwigIncludeScanningContext.class)
  public static final class SwigIncludeScanningContextImpl implements SwigIncludeScanningContext {
    private final CommandEnvironment env;
    private final Supplier<SpawnIncludeScanner> spawnScannerSupplier;
    private final Supplier<ExecutorService> includePool;
    private final ConcurrentMap<Artifact, ListenableFuture<Collection<Inclusion>>> cache =
        new ConcurrentHashMap<>();
    private final boolean useAsyncIncludeScanner;

    SwigIncludeScanningContextImpl(
        CommandEnvironment env,
        Supplier<SpawnIncludeScanner> spawnScannerSupplier,
        Supplier<ExecutorService> includePool,
        boolean useAsyncIncludeScanner) {
      this.env = env;
      this.spawnScannerSupplier = spawnScannerSupplier;
      this.includePool = includePool;
      this.useAsyncIncludeScanner = useAsyncIncludeScanner;
    }

    @Override
    public void extractSwigIncludes(
        Set<Artifact> includes,
        ActionExecutionMetadata actionExecutionMetadata,
        ActionExecutionContext actionExecContext,
        Artifact source,
        ImmutableSet<Artifact> legalOutputPaths,
        ImmutableList<PathFragment> swigIncludePaths,
        Artifact grepIncludes)
        throws IOException, ExecException, InterruptedException {
      SwigIncludeScanner scanner =
          new SwigIncludeScanner(
              includePool.get(),
              spawnScannerSupplier.get(),
              cache,
              swigIncludePaths,
              env.getDirectories(),
              env.getSkyframeBuildView().getArtifactFactory(),
              env.getExecRoot(),
              useAsyncIncludeScanner);
      ImmutableMap.Builder<PathFragment, Artifact> pathToLegalOutputArtifact =
          ImmutableMap.builder();
      for (Artifact path : legalOutputPaths) {
        pathToLegalOutputArtifact.put(path.getExecPath(), path);
      }
      try {
        scanner
            .processAsync(
                source,
                ImmutableList.of(source),
                // For Swig include scanning just point to the output file in the map.
                new IncludeScanningHeaderData.Builder(
                        pathToLegalOutputArtifact.build(), /*modularHeaders=*/ ImmutableSet.of())
                    .build(),
                ImmutableList.of(),
                includes,
                actionExecutionMetadata,
                actionExecContext,
                grepIncludes)
            .get();
      } catch (ExecutionException e) {
        Throwables.throwIfInstanceOf(e.getCause(), ExecException.class);
        Throwables.throwIfInstanceOf(e.getCause(), InterruptedException.class);
        if (e.getCause() instanceof IORuntimeException) {
          throw ((IORuntimeException) e.getCause()).getCauseIOException();
        }
        Throwables.throwIfUnchecked(e.getCause());
        throw new IllegalStateException(e.getCause());
      }
    }
  }

  /**
   * Factory for execution strategies related to include scanning.
   */
  public static class IncludeScanningActionContextProvider extends ActionContextProvider {
    private final CommandEnvironment env;
    private final ImmutableList<ActionContext> strategies;
    private final BuildRequest buildRequest;

    private final Supplier<SpawnIncludeScanner> spawnScannerSupplier;
    private IncludeScannerSupplierImpl includeScannerSupplier;
    private ExecutorService includePool;

    public IncludeScanningActionContextProvider(
        CommandEnvironment env,
        BuildRequest buildRequest,
        MutableSupplier<SpawnIncludeScanner> spawnScannerSupplier) {
      this.env = env;
      this.buildRequest = buildRequest;

      IncludeScanningOptions options = buildRequest.getOptions(IncludeScanningOptions.class);
      spawnScannerSupplier.set(
          new SpawnIncludeScanner(
              env.getExecRoot(),
              options.experimentalRemoteExtractionThreshold));
      this.spawnScannerSupplier = spawnScannerSupplier;
      this.strategies =
          ImmutableList.of(
              new CppIncludeExtractionContextImpl(env),
              new SwigIncludeScanningContextImpl(
                  env, spawnScannerSupplier, () -> includePool, options.useAsyncIncludeScanner),
              new CppIncludeScanningContextImpl(() -> includeScannerSupplier));

      env.getEventBus().register(this);
    }

    @Override
    public Iterable<ActionContext> getActionContexts() {
      return strategies;
    }

    @Override
    public void executionPhaseStarting(
        ActionGraph actionGraph,
        Supplier<ArtifactsToOwnerLabels> topLevelArtifactsToAccountingGroups)
        throws ExecutorInitException, InterruptedException {
      try {
        includeScannerSupplier.init(
            new IncludeParser(
                new IncludeParser.Hints(
                    (IncludeParser.HintsRules)
                        env.getSkyframeExecutor()
                            .evaluateSkyKeyForExecutionSetup(
                                env.getReporter(), IncludeHintsFunction.INCLUDE_HINTS_KEY),
                    env.getSkyframeBuildView().getArtifactFactory())));
      } catch (ExecException e) {
        throw new ExecutorInitException("could not initialize include hints", e);
      }
    }

    @Override
    public void executorCreated(Iterable<ActionContext> usedContexts) throws ExecutorInitException {
      IncludeScanningOptions options = buildRequest.getOptions(IncludeScanningOptions.class);
      int threads = options.includeScanningParallelism;
      if (threads > 0) {
        log.info(
            String.format("Include scanning configured to use a pool with %d threads", threads));
        includePool = ExecutorUtil.newSlackPool(threads, "Include scanner");
      } else {
        log.info("Include scanning configured to use a direct executor");
        includePool = MoreExecutors.newDirectExecutorService();
      }
      includeScannerSupplier =
          new IncludeScannerSupplierImpl(
              env.getDirectories(),
              includePool,
              env.getSkyframeBuildView().getArtifactFactory(),
              spawnScannerSupplier,
              env.getExecRoot(),
              options.useAsyncIncludeScanner);

      spawnScannerSupplier.get().setOutputService(env.getOutputService());
      spawnScannerSupplier.get().setInMemoryOutput(options.inMemoryIncludesFiles);
    }
  }
}


text:
"""
Helper script for starting up bolts and spouts.
"""

import argparse
import importlib
import os
import sys

from pystorm.component import _SERIALIZERS

RESOURCES_PATH = 'resources'

def main():
    """main entry point for Python bolts and spouts"""
    parser = argparse.ArgumentParser(description='Run a bolt/spout class',
                                     epilog='This is internal to streamparse '
                                            'and is used to run spout and bolt '
                                            'classes via ``python -m '
                                            'streamparse.run <class name>``.')
    parser.add_argument('target_class', help='The bolt/spout class to start.')
    parser.add_argument('-s', '--serializer',
                        help='The serialization protocol to use to talk to '
                             'Storm.',
                        choices=_SERIALIZERS.keys(),
                        default='json')
    # Storm sends everything as one string, which is not great
    if len(sys.argv) == 2:
        sys.argv = [sys.argv[0]] + sys.argv[1].split()
    args = parser.parse_args()
    mod_name, cls_name = args.target_class.rsplit('.', 1)
    # Add current directory to sys.path so imports will work
    import_path = os.getcwd()  # Storm <= 1.0.2
    if RESOURCES_PATH in next(os.walk(import_path))[1] and \
       os.path.isfile(os.path.join(import_path,
                                   RESOURCES_PATH,
                                   mod_name.replace('.', os.path.sep) + '.py')):
        import_path = os.path.join(import_path,
                                   RESOURCES_PATH)  # Storm >= 1.0.3
    sys.path.append(import_path)
    # Import module
    mod = importlib.import_module(mod_name)
    # Get class from module and run it
    cls = getattr(mod, cls_name)
    cls(serializer=args.serializer).run()

if __name__ == '__main__':
    main()


text:
<resources>
    <string name="app_name">Kotlin Kōans</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>

    <string name="koan">Challenge</string>
    <string name="koan_progress">Challenges completed</string>

    <string name="status_none">Run code to see results</string>
    <string name="status_running">Running</string>
    <string name="last_run_status">Last run status</string>
    <string name="results_none">Results will appear here</string>
    <string name="no_koans_left">You\'re on the last kōan, little grasshopper. One step to nirvana!</string>

    <string name="code_copy">Copy code</string>
    <string name="code_copied">Code copied</string>
    <string name="code_copy_clipboard_label">Kotlin kōan code</string>

    <string name="next">Next</string>
    <string name="show_answer">Show answer</string>
    <string name="answer">Answer</string>
    <string name="error_generic">An error occurred</string>
    <string name="intent_no_apps">There are no apps that can handle this action</string>

    <string name="action_revert">Revert code</string>
    <string name="revert">Revert</string>
    <string name="revert_prompt_title">Revert code?</string>
    <string name="revert_prompt_message">Doing so will overwrite your saved code for this kōan, if any. Continue?</string>
    <string name="action_docs">Link to Kotlin docs</string>
    <string name="action_send_feedack">Send feedback…</string>

    <!-- intro tour -->
    <string name="tour_step1_title">Hi there! (1/6)</string>
    <string name="tour_step1_desc">Kotlin Kōans is a series of short coding challenges for learning Kotlin quickly.</string>
    <string name="tour_step2_title">Type your code in this tab (2/6)</string>
    <string name="tour_step2_desc">The other tabs have tests and supporting code which can\'t be modified</string>
    <string name="tour_step3_title">Run it (3/6)</string>
    <string name="tour_step3_desc">Tap here to run your Kotlin code at any time. The code is saved on each run.</string>
    <string name="tour_step4_title">See your test results (4/6)</string>
    <string name="tour_step4_desc">When you solve a challenge, it\'ll be saved to your overall progress!</string>
    <string name="tour_step5_title">If you get stuck… (5/6)</string>
    <string name="tour_step5_desc">Try debugging with println(\"hello\"), or sneak a peek at the answer!</string>
    <string name="tour_step6_title">Most importantly… have fun! (6/6)</string>
    <string name="tour_step6_desc">Tap here to see your progress</string>

    <!-- settings -->
    <string name="settings">Settings</string>
    <string name="pref_auto_pair_title">Auto-pair brackets</string>
    <string name="pref_auto_pair_summary">Insert closing brackets, parens, and braces automatically</string>
    <string name="pref_auto_indent_title">Auto-indent</string>
    <string name="pref_auto_indent_summary">Automatically indent lines based on preceding characters</string>
    <string name="pref_indent_size_title">Indent size</string>
    <string name="pref_indent_size_summary">Number of spaces</string>

    <!-- about screen -->
    <string name="action_about">About…</string>
    <string name="about">About</string>

    <string name="version">Version</string>
    <string name="version_unknown" translatable="false">Unknown</string>
    <string name="open_source_libs" translatable="false">Open-source libraries</string>
    <string name="kotlin_koans_jetbrains" translatable="false">Kotlin koans by Jetbrains</string>
    <string name="kotlin_resources">More Kotlin resources</string>

    <string name="category_support_development">Support development</string>
    <string name="report_bugs" translatable="false">Report bugs</string>
    <string name="report_bugs_subtitle" translatable="false">Report bugs or propose new features</string>
    <string name="play_store">Rate on Play Store</string>
    <string name="play_store_subtitle">Thanks for your support!</string>
    <string name="email_developer" translatable="false">Email the developer</string>
    <string name="email_developer_subtitle" translatable="false">Contact the developer directly</string>
    <string name="email_subject" translatable="false">%s - Feedback</string>

    <string name="category_developer" translatable="false">Developer</string>
    <string name="vicky_chijwani" translatable="false">Vicky Chijwani</string>
    <string name="fork_on_github" translatable="false">Fork on Github</string>
    <string name="follow_on_twitter" translatable="false">Follow on Twitter</string>
    <string name="visit_website" translatable="false">Visit website</string>

</resources>


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

<configuration scan="true">
	<property name="app_name" value="server"></property>
    <property name="log_path" value="../log/${app_name}"/>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} - %m%n</pattern>
        </encoder>
    </appender>
    <appender name="DETAIL" class="ch.qos.logback.core.rolling.RollingFileAppender" additivity="false">
        <File>${log_path}/${app_name}_detail.log</File>
        <encoder>
            <pattern>%d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} - %m%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${APP}_detail.log.%d{yyyyMMdd}</fileNamePattern>
        </rollingPolicy>
    </appender>
    <logger name="org.springframework" level="WARN"/>
    <logger class="org.apache.zookeeper" level="warn" />
    <root level="DEBUG">
        <appender-ref ref="DETAIL"/>
        <appender-ref ref="CONSOLE"/>
    </root>
</configuration>


text:
module StashDatacite
  class Language < ActiveRecord::Base
    self.table_name = 'dcs_languages'
    belongs_to :resource, class_name: StashEngine::Resource.to_s
    include StashEngine::Concerns::ResourceUpdated
  end
end


text:
import Ember from 'ember';

const { Component, observer, merge, testing } = Ember;

export default Component.extend({
  tagName           : 'div',
  classNames        : ['ui', 'modal'],
  classNameBindings : ['isFullScreen:fullscreen', 'isSmall:small', 'isLarge:large'],

  openObserver: observer('isOpen', function() {
    if (this.get('isOpen')) {
      this.$().modal('show');
    } else {
      this.$().modal('hide');
    }
  }),

  close() {
    this.set('isOpen', false);
  },

  open() {
    this.set('isOpen', true);
  },

  actions: {
    close() {
      this.close();
    }
  },

  didRender()  {
    this._super(...arguments);
    try {
      this.$().modal('refresh');
    } catch (ignored) { /* ignored exception */ }
  },

  didInsertElement() {
    this._super(...arguments);
    const defaultOptions = {
      detachable     : false,
      duration       : testing ? 0 : 200,
      dimmerSettings : {
        dimmerName : `${this.get('elementId')}-modal-dimmer`,
        variation  : 'inverted'
      },
      onHide: () => {
        this.set('isOpen', false);
        if (this.get('onHide')) {
          this.onHide();
        }
      },
      onDeny: () => {
        if (this.get('onDeny')) {
          this.onDeny();
        }
        return true;
      },
      onApprove: () => {
        if (this.get('onApprove')) {
          this.onApprove();
        }
        return true;
      },

      onVisible: () => {
        this.set('isOpen', true);
        this.$().modal('refresh');
        this.$('[data-content]').popup({
          inline: true
        });
        if (this.get('onVisible')) {
          this.onVisible();
        }
      }
    };

    const options = this.get('options') ? merge(defaultOptions, this.get('options')) : defaultOptions;

    this.$().modal(options);

    if (this.get('isOpen')) {
      this.$().modal('show');
    }
  }
});


text:
package say

import (
	"crypto/rand"
	"database/sql"
	"errors"
	"fmt"
	"io"
	"math"
	"math/big"
	"strconv"
	"strings"

	"github.com/jmoiron/sqlx"
	"github.com/lib/pq"
)

const (
	maxInsertRetries = 16
	convoIDPrefix    = "cv_"
	lineIDPrefix     = "ln_"
	dbErrDupUnique   = "23505"
	dbErrFKViolation = "23503"

	listMoods = `
SELECT id as int_id, name, eyes, tongue
FROM moods
WHERE user_id = :user_id AND
  (:cursor_id < 0 OR id %s :cursor_id)
ORDER BY 1 %s
LIMIT :limit + 1
`
	findMood = `
SELECT id as int_id, eyes, tongue, name
FROM moods
WHERE user_id = :user_id AND lower(name) = lower(:name)
`
	deleteMood = `
DELETE FROM moods
WHERE user_id = :user_id AND lower(name) = lower(:name)
`
	// TODO: Racy upsert
	setMood = `
WITH
updated as (
  UPDATE moods SET eyes = :eyes, tongue = :tongue
  WHERE user_id = :user_id AND lower(name) = lower(:name)
  RETURNING id
),
inserted as (
  INSERT INTO moods (user_id, name, eyes, tongue)
  SELECT :user_id, lower(:name), :eyes, :tongue
  WHERE NOT EXISTS (SELECT * FROM updated)
  RETURNING id
)
SELECT id FROM updated UNION ALL SELECT id FROM inserted
`

	listConvos = `
SELECT id as int_id, public_id as id, heading
FROM conversations
WHERE user_id = :user_id AND
  (:cursor_id < 0 OR id %s :cursor_id)
ORDER BY 1 %s
LIMIT :limit
`
	insertConvo = `
INSERT INTO conversations (public_id, user_id, heading)
SELECT :public_id, :user_id, :heading
RETURNING id
`
	getConvo = `
SELECT id as int_id, public_id as id, heading FROM conversations
WHERE user_id = :user_id AND public_id = :public_id
`
	deleteConvo = `
DELETE FROM conversations
WHERE user_id = :user_id AND public_id = :public_id
`

	findConvoLines = `
SELECT public_id as id, animal, think, text, mood_name, eyes, tongue
FROM lines
LEFT JOIN moods ON lines.mood_id = moods.id
WHERE conversation_id = :id
ORDER BY lines.id ASC
`
	findMoodLines = `
SELECT public_id as id
FROM lines
LEFT JOIN moods ON lines.mood_id = moods.id
WHERE user_id = :user_id AND mood_name = :name
ORDER BY lines.id ASC
`
	insertLine = `
INSERT INTO LINES (public_id, animal, think, text, mood_name, mood_id, conversation_id)
SELECT :public_id, :animal, :think, :text, :mood_name, :mood_id, :conversation_id
`
	getLine = `
SELECT lines.public_id as id, animal, think, text, mood_name, eyes, tongue
FROM lines
LEFT JOIN moods ON lines.mood_id = moods.id
INNER JOIN conversations ON lines.conversation_id = conversations.id
WHERE
  conversations.public_id = :convo_id AND
  conversations.user_id = :user_id AND
  lines.public_id = :line_id
`
	deleteLine = `
DELETE FROM lines
USING conversations
WHERE
  lines.conversation_id = conversations.id AND
  conversations.public_id = :convo_id AND
  conversations.user_id = :user_id AND
  lines.public_id = :line_id
`
)

var errCursorNotFound = errors.New("Invalid cursor")
var errBuiltinMood = errors.New("Cannot modify built-in moods")
var errRecordNotFound = errors.New("Requested record was not found")

type conflictErr struct {
	IDs []string
}

func (e conflictErr) Error() string {
	return fmt.Sprintf("Operation failed due to conflicts with: %s", e.IDs)
}

type repository struct {
	db      *sqlx.DB
	closers []io.Closer

	listMoodsAsc, listMoodsDesc, findMood, deleteMood, setMood        *sqlx.NamedStmt
	listConvosAsc, listConvosDesc, insertConvo, getConvo, deleteConvo *sqlx.NamedStmt
	findConvoLines, findMoodLines, insertLine, getLine, deleteLine    *sqlx.NamedStmt
}

type listArgs struct {
	Before, After string
	Limit         int
}

var builtinMoods = []*Mood{
	{"default", "oo", "  ", false, 0},
	{"borg", "==", "  ", false, 0},
	{"dead", "xx", "U ", false, 0},
	{"greedy", "$$", "  ", false, 0},
	{"stoned", "**", "U ", false, 0},
	{"tired", "--", "  ", false, 0},
	{"wired", "OO", "  ", false, 0},
	{"young", "..", "  ", false, 0},
}

type moodRec struct {
	IntID int
	Mood
}

type lineRec struct {
	Eyes, Tongue sql.NullString
	Line
}

type convoRec struct {
	IntID int

	Conversation
}

func newRepository(db *sqlx.DB) (*repository, error) {
	r := repository{db: db}

	stmts := map[string]**sqlx.NamedStmt{
		findMood:       &r.findMood,
		setMood:        &r.setMood,
		deleteMood:     &r.deleteMood,
		insertConvo:    &r.insertConvo,
		getConvo:       &r.getConvo,
		deleteConvo:    &r.deleteConvo,
		findConvoLines: &r.findConvoLines,
		findMoodLines:  &r.findMoodLines,
		insertLine:     &r.insertLine,
		getLine:        &r.getLine,
		deleteLine:     &r.deleteLine,

		fmt.Sprintf(listConvos, ">", "ASC"):  &r.listConvosAsc,
		fmt.Sprintf(listConvos, "<", "DESC"): &r.listConvosDesc,
		fmt.Sprintf(listMoods, ">", "ASC"):   &r.listMoodsAsc,
		fmt.Sprintf(listMoods, "<", "DESC"):  &r.listMoodsDesc,
	}

	for sqlStr, stmt := range stmts {
		prepped, err := db.PrepareNamed(sqlStr)
		*stmt = prepped
		if err != nil {
			return nil, fmt.Errorf("preparing statement %q: %v", sqlStr, err)
		}
		r.closers = append(r.closers, prepped)
	}

	return &r, nil
}

func (r *repository) Close() error {
	for _, closer := range r.closers {
		if err := closer.Close(); err != nil {
			return fmt.Errorf("closing %s: %v", closer, err)
		}
	}

	return nil
}

func (r *repository) ListMoods(userID string, args listArgs) ([]Mood, bool, error) {
	sources := make([]func(bool, listArgs) ([]Mood, bool, error), 2)
	var sourceNames []string

	userSrc := func(asc bool, args listArgs) ([]Mood, bool, error) {
		return r.listUserMoods(userID, asc, args)
	}

	var asc bool
	if sortAsc(args) {
		asc = true
		sources[0] = userSrc
		sources[1] = r.listBuiltinMoods
		sourceNames = []string{"user", "built-in"}
	} else {
		asc = false
		sources[1] = userSrc
		sources[0] = r.listBuiltinMoods
		sourceNames = []string{"built-in", "user"}
	}

	moods, _, err := sources[0](asc, args)
	if err != nil {
		if err != errCursorNotFound {
			return nil, false, fmt.Errorf("listing %s moods %v", sourceNames[0], err)
		}
	} else {
		args.Limit = args.Limit - len(moods)
		args.Before = ""
		args.After = ""

		if len(moods) == args.Limit {
			return moods, true, nil
		}
	}

	moreMoods, hasMore, err := sources[1](asc, args)
	if err != nil {
		if err != errCursorNotFound {
			err = fmt.Errorf("listing %s moods %v", sourceNames[1], err)
		}
		return nil, false, err
	}

	for _, mood := range moreMoods {
		moods = append(moods, mood)
	}

	return moods, hasMore, nil
}

func (r *repository) listBuiltinMoods(asc bool, args listArgs) ([]Mood, bool, error) {
	var moods []Mood

	cursor := args.After
	if !asc {
		cursor = args.Before
	}

	limit := args.Limit + 1

	found := args.After == "" && args.Before == ""
	for i := 0; i < len(builtinMoods); i++ {
		var mood *Mood
		if asc {
			mood = builtinMoods[i]
		} else {
			mood = builtinMoods[len(builtinMoods)-1-i]
		}

		if found {
			moods = append(moods, *mood)
			if len(moods) == limit {
				break
			}
		} else if mood.Name == cursor {
			found = true
		}
	}

	if !found {
		return nil, false, errCursorNotFound
	}

	hasMore := len(moods) > args.Limit
	if hasMore {
		moods = moods[:args.Limit]
	}

	return moods, hasMore, nil
}

func (r *repository) listUserMoods(userID string, asc bool, args listArgs) ([]Mood, bool, error) {
	var moods []Mood

	cursor := args.After
	query := r.listMoodsAsc
	if !asc {
		cursor = args.Before
		query = r.listMoodsDesc
	}

	cursorID := -1
	if cursor != "" {
		var mood moodRec

		err := r.findMood.Get(&mood, struct{ UserID, Name string }{userID, cursor})
		if err == sql.ErrNoRows {
			return nil, false, errCursorNotFound
		} else if err != nil {
			return nil, false, fmt.Errorf("finding mood cursor %q for user %q: %v", cursor, userID, err)
		} else {
			cursorID = mood.IntID
		}
	}

	rows, err := query.Queryx(struct {
		UserID          string
		CursorID, Limit int
	}{userID, cursorID, args.Limit + 1})
	if err != nil {
		return nil, false, fmt.Errorf("listing user moods: %v", err)
	}
	defer rows.Close()

	for rows.Next() {
		var rec moodRec
		if err := rows.StructScan(&rec); err != nil {
			return nil, false, fmt.Errorf("scanning user mood: %v", err)
		}

		rec.UserDefined = true
		rec.id = rec.IntID
		moods = append(moods, rec.Mood)
	}

	hasMore := len(moods) > args.Limit
	if hasMore {
		moods = moods[:args.Limit]
	}

	return moods, hasMore, nil
}

func (r *repository) GetMood(userID, name string) (*Mood, error) {
	for _, builtin := range builtinMoods {
		if builtin.Name == name {
			// Copy to prevent modifying builtins by the caller
			mood := *builtin
			return &mood, nil
		}
	}

	var rec moodRec
	err := r.findMood.Get(&rec, struct{ UserID, Name string }{userID, name})
	if err == sql.ErrNoRows {
		return nil, nil
	} else if err != nil {
		return nil, fmt.Errorf("getting user mood: %v", err)
	}
	rec.UserDefined = true
	rec.id = rec.IntID

	return &rec.Mood, nil
}

func (r *repository) SetMood(userID string, mood *Mood) error {
	if isBuiltin(mood.Name) {
		return errBuiltinMood
	}

	var id int
	err := r.setMood.QueryRow(struct {
		UserID, Name, Eyes, Tongue string
	}{
		userID, mood.Name, mood.Eyes, mood.Tongue,
	}).Scan(&id)
	if err != nil {
		return fmt.Errorf("upserting user mood: %v", err)
	}
	if id == 0 {
		return fmt.Errorf("unable to update mood %q", mood.Name)
	}

	mood.id = id

	return nil
}

func (r *repository) DeleteMood(userID, name string) error {
	if isBuiltin(name) {
		return errBuiltinMood
	}

	queryArgs := struct{ UserID, Name string }{userID, name}
	if err := doDelete(r.deleteMood, queryArgs); err != nil {
		if dbErr, ok := err.(*pq.Error); !ok || dbErr.Code != dbErrFKViolation {
			return err
		}

		// List the lines that are preventing us from deleting the mood.
		// There's a per-user race condition here but since this is mostly
		// meant to provide informative help, it's probably not worth
		// wrapping the entire thing in a transaction.
		var lineIDs []string
		if err := r.findMoodLines.Select(&lineIDs, queryArgs); err != nil {
			return fmt.Errorf("listing lines for mood %q and user %q: %v", name, userID, err)
		}

		return conflictErr{lineIDs}
	}

	return nil
}

func (r *repository) ListConversations(userID string, args listArgs) ([]Conversation, bool, error) {
	var convos []Conversation

	cursor := args.After
	query := r.listConvosAsc
	if !sortAsc(args) {
		cursor = args.Before
		query = r.listConvosDesc
	}

	cursorID := -1
	if cursor != "" {
		var convo convoRec

		err := r.getConvo.Get(&convo, struct{ UserID, PublicID string }{userID, cursor})
		if err == sql.ErrNoRows {
			return nil, false, errCursorNotFound
		} else if err != nil {
			return nil, false, fmt.Errorf("finding conversation cursor %q for user %q: %v", cursor, userID, err)
		} else {
			cursorID = convo.IntID
		}
	}

	rows, err := query.Queryx(struct {
		UserID          string
		CursorID, Limit int
	}{userID, cursorID, args.Limit + 1})
	if err != nil {
		return nil, false, fmt.Errorf("listing conversations for user %s: %v", userID, err)
	}
	defer rows.Close()

	for rows.Next() {
		var rec convoRec
		if err := rows.StructScan(&rec); err != nil {
			return nil, false, fmt.Errorf("scanning conversation: %v", err)
		}

		rec.id = rec.IntID
		convos = append(convos, rec.Conversation)
	}

	hasMore := len(convos) > args.Limit
	if hasMore {
		convos = convos[:args.Limit]
	}

	return convos, hasMore, nil
}

func (r *repository) NewConversation(userID, heading string) (*Conversation, error) {
	var publicID string

	for i := 0; i < maxInsertRetries; i++ {
		rv, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
		if err != nil {
			return nil, fmt.Errorf("generating random ID: %v", err)
		}
		publicID = convoIDPrefix + strconv.FormatUint(rv.Uint64(), 36)

		var id int
		err = r.insertConvo.QueryRow(struct {
			PublicID, UserID, Heading string
		}{publicID, userID, heading}).Scan(&id)
		if err == nil {
			return &Conversation{
				ID:      publicID,
				Heading: heading,
				id:      id,
			}, nil
		}

		dbErr, ok := err.(*pq.Error)
		if !ok || dbErr.Code != dbErrDupUnique {
			return nil, fmt.Errorf("inserting conversation: %v", err)
		}
	}

	return nil, errors.New("Unable to insert a new, unique conversation")
}

func (r *repository) GetConversation(userID, convoID string) (*Conversation, error) {
	var convo convoRec

	err := r.getConvo.Get(&convo, struct{ UserID, PublicID string }{userID, convoID})
	if err == sql.ErrNoRows {
		return nil, nil
	} else if err != nil {
		return nil, fmt.Errorf("finding conversation %q for user %q: %v", convoID, userID, err)
	}

	rows, err := r.findConvoLines.Queryx(struct{ ID int }{convo.IntID})
	if err != nil {
		return nil, fmt.Errorf("retrieving lines for %q: %v", convoID, err)
	}
	defer rows.Close()

	convo.Lines = make([]Line, 0)
	for rows.Next() {
		var rec lineRec
		if err := rows.StructScan(&rec); err != nil {
			return nil, fmt.Errorf("scanning line for %q: %v", convoID, err)
		}

		setLineMood(&rec)
		if rec.mood == nil {
			return nil, fmt.Errorf("line %s does not have a valid mood", rec.ID)
		}

		convo.Lines = append(convo.Lines, rec.Line)
	}

	convo.Conversation.id = convo.IntID

	return &convo.Conversation, nil
}

func (r *repository) DeleteConversation(userID, convoID string) error {
	if err := doDelete(r.deleteConvo, struct{ UserID, PublicID string }{userID, convoID}); err != nil {
		return err
	}

	return nil
}

func (r *repository) InsertLine(userID, convoID string, line *Line) error {
	var publicID string

	var convo convoRec
	err := r.getConvo.Get(&convo, struct{ UserID, PublicID string }{userID, convoID})
	if err != nil {
		return fmt.Errorf("finding conversation %s for user %s: %v", convoID, userID, err)
	}

	for i := 0; i < maxInsertRetries; i++ {
		rv, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
		if err != nil {
			return fmt.Errorf("generating random ID: %v", err)
		}
		publicID = lineIDPrefix + strconv.FormatUint(rv.Uint64(), 36)

		var moodID sql.NullInt64
		if line.mood.id != 0 {
			moodID.Int64 = int64(line.mood.id)
			moodID.Valid = true
		}

		_, err = r.insertLine.Exec(struct {
			PublicID, Animal, Text, MoodName string
			Think                            bool
			MoodID                           sql.NullInt64
			ConversationID                   int
		}{
			publicID, line.Animal, line.Text, line.MoodName,
			line.Think,
			moodID,
			convo.IntID,
		})
		if err == nil {
			line.ID = publicID
			return nil
		}

		dbErr, ok := err.(*pq.Error)
		if !ok || dbErr.Code != dbErrDupUnique {
			return fmt.Errorf("inserting line: %v", err)
		}
	}

	return errors.New("unable to insert a new, unique line")
}

func (r *repository) GetLine(userID, convoID, lineID string) (*Line, error) {
	var rec lineRec

	err := r.getLine.Get(&rec, struct{ UserID, ConvoID, LineID string }{userID, convoID, lineID})
	if err == sql.ErrNoRows {
		return nil, nil
	} else if err != nil {
		return nil, fmt.Errorf("getting line: %v", err)
	}

	setLineMood(&rec)
	if rec.mood == nil {
		return nil, fmt.Errorf("Line %s does not have a valid mood", rec.ID)
	}

	return &rec.Line, nil
}

func (r *repository) DeleteLine(userID, convoID, lineID string) error {
	if err := doDelete(r.deleteLine, struct{ UserID, ConvoID, LineID string }{userID, convoID, lineID}); err != nil {
		return err
	}

	return nil
}

func setLineMood(rec *lineRec) {
	if rec.Eyes.Valid {
		rec.mood = &Mood{
			Name:        rec.MoodName,
			Eyes:        rec.Eyes.String,
			Tongue:      rec.Tongue.String,
			UserDefined: true,
		}
		return
	}

	for _, mood := range builtinMoods {
		if strings.EqualFold(mood.Name, rec.MoodName) {
			m := *mood
			rec.mood = &m
			return
		}
	}
}

func isBuiltin(name string) bool {
	for _, builtin := range builtinMoods {
		if strings.EqualFold(builtin.Name, name) {
			return true
		}
	}
	return false
}

func sortAsc(args listArgs) bool {
	return args.After != "" || args.Before == ""
}

func doDelete(stmt *sqlx.NamedStmt, args interface{}) error {
	res, err := stmt.Exec(args)
	if err != nil {
		return err
	}

	cnt, err := res.RowsAffected()
	if err != nil {
		return err
	}
	if cnt == 0 {
		return errRecordNotFound
	}

	return nil
}


text:
<?php

/**
 * ezcConfigurationIniReader provides functionality for reading INI files into
 * ezcConfiguration objects.
 *
 * Typical usage is to create the reader object and pass the filepath in the
 * constructor:
 *
 * $reader = new ezcConfigurationIniReader( "settings/site.ini" );
 * $reader->load();
 *
 * That makes the class figure out the location and name values automatically.
 *
 * Or generally use the init() function:
 *
 * $reader = new ezcConfigurationIniReader();
 * $reader->init( "settings", "site" );
 * $reader->load();
 *
 *
 * Accessing the configuration object is done by the getConfig() method or by
 * using the return value of load():
 *
 * $conf1 = $reader->load();
 * $conf2 = $reader->getConfig();
 * // $conf1 and $conf2 points to the same object
 *
 *
 * If caching is employed the getTimestamp() method can be used to find the last
 * modification time of the file.
 *
 * $time = $reader->getTimestamp();
 * if ( $time > $cachedTime )
 * {
 *    $reader->load();
 * }
 *
 *
 * Options can be set with the setOptions() method. The only option that this
 * reader supports is the "useComments" option:
 *
 * $reader->setOptions( array( 'useComments' => true ) );
 *
 *
 * Instead of loading the INI file it can be validated with validate(), this will
 * return an ezcConfigurationValidationResult which can be inspected and
 * presented to the end user.
 *
 * $result = $reader->validate();
 * if ( !$result->isValid )
 * {
 *    foreach ( $result->getResultList() as $resultItem )
 *    {
 *        print $resultItem->file . ":" . $resultItem->line . ":" .
 *            $resultItem->column. ":";
 *        print " " . $resultItem->details . "\n";
 *    }
 * }
 *
 *
 * For more information on file based configurations see {@link
 * ezcConfigurationFileReader}.
 *
 * This class uses exceptions and will throw them when the conditions for the
 * operation fails somehow.
 *
 * @package Configuration
 * @version //autogen//
 * @mainclass
 */
class ezcConfigurationIniReader extends ezcConfigurationFileReader
{
    /**
     * Returns 'ini'. The suffix used in the storage filename.
     *
     * @return string
     */
    protected function getSuffix()
    {
        return 'ini';
    }

    /**
     * Loads a configuration object
     *
     * Loads the current config object from a give location which can later be stored
     * with a ezcConfigurationWriter.
     *
     * @see config()
     * @throws ezcConfigurationNoConfigException if there is no config
     *         object to be read from the location.
     * @throws ezcConfigurationInvalidSuffixException if the current
     *         location values cannot be used for reading.
     * @throws ezcConfigurationReadFailureException if the configuration
     *         could not be read from the given location.
     *
     * @return ezcConfiguration
     */
    public function load()
    {
        $parser = new ezcConfigurationIniParser( ezcConfigurationIniParser::PARSE, $this->path );
        $settings = array();
        $comments = array();

        foreach ( new NoRewindIterator( $parser ) as $element )
        {
            if ( $element instanceof ezcConfigurationIniItem )
            {
                switch ( $element->type )
                {
                    case ezcConfigurationIniItem::GROUP_HEADER:
                        $settings[$element->group] = array();
                        if ( !is_null( $element->comments ) )
                        {
                            $comments[$element->group]['#'] = $element->comments;
                        }
                        break;

                    case ezcConfigurationIniItem::SETTING:
                        eval( '$settings[$element->group][$element->setting]'. $element->dimensions. ' = $element->value;' );
                        if ( !is_null( $element->comments ) )
                        {
                            eval( '$comments[$element->group][$element->setting]'. $element->dimensions. ' = $element->comments;' );
                        }
                        break;
                }
            }
            if ( $element instanceof ezcConfigurationValidationItem )
            {
                throw new ezcConfigurationParseErrorException( $element->file, $element->line, $element->description );
            }
        }

        $this->config = new ezcConfiguration( $settings, $comments );
        return $this->config;
    }

    /**
     * Validates the configuration.
     *
     * Validates the configuration at the given location and returns the
     * validation result.
     *
     * If $strict is set it will not validate the file if it contains any
     * errors or warnings. If false it will allow warnings but not errors.
     *
     * @param bool $strict
     * @return ezcConfigurationValidationResult
     */
    public function validate( $strict = false )
    {
        $parserType = $strict ? ezcConfigurationIniParser::VALIDATE_STRICT : ezcConfigurationIniParser::VALIDATE;
        $parser = new ezcConfigurationIniParser( $parserType, $this->path );

        $validationResult = new ezcConfigurationValidationResult( $this->location, $this->name, $this->path );

        foreach ( new NoRewindIterator( $parser ) as $element )
        {
            if ( $element instanceof ezcConfigurationIniItem )
            {
                throw new Exception( "A validating parser emitted a configuration item, which should never happen" );
            }
            if ( $element instanceof ezcConfigurationValidationItem )
            {
                $validationResult->appendItem( $element );
                if ( $element->type == ezcConfigurationValidationItem::ERROR )
                {
                    $validationResult->isValid = false;
                }
                else if ( $element->type == ezcConfigurationValidationItem::WARNING && $parserType == ezcConfigurationIniItem::VALIDATE_STRICT )
                {
                    $validationResult->isValid = false;
                }
            }
        }
        return $validationResult;
    }
}
?>


text:
import { createDir, rimraf, writeMultipleFiles } from '../../utils/fs';
import { execAndWaitForOutputToMatch } from '../../utils/process';
import { updateJsonFile } from '../../utils/project';

export default async function () {
  await createDir('example-builder');
  await writeMultipleFiles({
    'example-builder/package.json': '{ "builders": "./builders.json" }',
    'example-builder/schema.json':
      '{ "$schema": "http://json-schema.org/draft-07/schema", "type": "object", "additionalProperties": true }',
    'example-builder/builders.json':
      '{ "$schema": "@angular-devkit/architect/src/builders-schema.json", "builders": { "example": { "implementation": "./example", "schema": "./schema.json" } } }',
    'example-builder/example.js':
      'module.exports.default = require("@angular-devkit/architect").createBuilder((options) => { console.log(options); return { success: true }; });',
  });

  await updateJsonFile('angular.json', (json) => {
    const appArchitect = json.projects['test-project'].architect;
    appArchitect.example = {
      builder: './example-builder:example',
    };
  });

  await execAndWaitForOutputToMatch(
    'ng',
    ['run', 'test-project:example', '--additional', 'property'],
    /Unknown argument: additional/,
  );

  await rimraf('example-builder');
}


text:
module Mozenda::Response
  class CollectionPublish < Mozenda::Response::Base

    def job_id
      body_hash["JobID"]
    end

    private

    NAME = "CollectionPublishResponse"

  end
end


text:
/**
 * @component ImgRollView
 * @version 0.13.0
 * @description 图片多选组件
 *
 * @instructions {instruInfo: ./ImgRollView.md}
 */
import React, { Component, PropTypes } from 'react';
import {
  Text,
  Image,
  View,
  CameraRoll,
  ListView,
  TouchableWithoutFeedback,
  Dimensions,
} from 'react-native';

import style from './styles';
import { groupByEveryN, SelectTick } from './utils';

const { height, width } = Dimensions.get('window');

class ImgRollView extends Component {
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => {
        if (r1 && r2) {
          return r1.some((v, i) => r2[i] !== v);
        }
        return r1 !== r2;
      },
    });
    const { imagesPerRow, gap } = props;
    /**
     * @description 根据屏幕宽度与每行图片树计算图片宽
     */
    this.sideLength = ((width + gap) / imagesPerRow) - gap;
    /**
     * @description 根据屏幕高度获取首屏要加载的图片数量
     */
    this.pageSize = Math.ceil((height + gap) / (this.sideLength + gap)) * imagesPerRow;
    /**
     * @description 记录已经选择的 uri
     */
    this.uriSelected = props.uriList;

    this.state = {
      assets: [],
      dataSource: ds.cloneWithRows([]),
    };

    /**
     * @description autobind
     */
    this.onEndReached = this.onEndReached.bind(this);
    this.onSelectImage = this.onSelectImage.bind(this);
    this.renderRow = this.renderRow.bind(this);
  }

  componentWillMount() {
    this.fetch();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.uriList !== this.props.uriList) {
      this.uriSelected = nextProps.uriList;
      const assets = this.setSelectedAsset(this.state.assets, this.uriSelected);
      this.updateAssets({ assets });
    }
  }

  onEndReached() {
    if (!this.noMore) this.fetch();
  }

  onSelectImage(params) {
    return () => {
      const overflow = this.uriSelected.length >= this.props.maxSelected;
      this.toggleSelected({ ...params, overflow });
    };
  }

  setSelectedAsset(assets, uriList) {
    return assets.map((data) => {
      const item = { ...data };
      if (uriList.indexOf(item.node.image.uri) > -1) {
        item.selected = true;
      }
      return item;
    });
  }

  handleItemSelect(data, overflow) {
    const item = data;
    const { uri } = item.node.image;

    if (!overflow || item.selected) {
      const selected = !item.selected;
      if (selected) {
        this.uriSelected.push(uri);
      } else {
        this.uriSelected = this.uriSelected.filter(v => v !== uri);
      }
      return { ...item, selected };
    }

    return item;
  }

  toggleSelected({ uri, rowId, colId, overflow }) {
    const { assets } = this.state;
    const { onSelect, imagesPerRow } = this.props;
    let index;

    if (typeof +rowId === 'number' && typeof +colId === 'number') {
      index = (rowId * imagesPerRow) + colId;
      const item = assets[index];
      assets[index] = this.handleItemSelect(item, overflow);
    } else {
      let it;
      assets.some((data, i) => {
        const item = data;
        if (item.node.image.uri === uri) {
          index = i;
          it = this.handleItemSelect(item, overflow);
          return true;
        }
        return false;
      });
      assets[index] = it;
    }

    this.updateAssets({ assets: [].concat(assets) });
    onSelect({
      selected: assets[index] ? !!assets[index].selected : null,
      node: assets[index],
      uri,
      uriSelected: this.uriSelected,
    });
  }

  updateAssets({ assets, batchUpdate }) {
    const { dataSource } = this.state;
    const { imagesPerRow } = this.props;

    const nextState = {
      assets,
      dataSource: dataSource.cloneWithRows(
        groupByEveryN(assets, imagesPerRow)
      ),
    };

    if (batchUpdate) return nextState;
    this.setState(nextState);
    return false;
  }

  appendAssets(data) {
    const nextAssets = data.edges;
    const nextState = { loadingMore: false };
    const { assets } = this.state;
    const hasNextPage = data.page_info.has_next_page;

    this.endCursor = data.page_info.end_cursor;

    if (!hasNextPage) {
      this.noMore = true;
    }

    if (nextAssets.length > 0) {
      nextState.lastCursor = data.page_info.end_cursor;
      Object.assign(nextState, this.updateAssets({
        assets: this.setSelectedAsset(assets.concat(nextAssets), this.uriSelected),
        batchUpdate: true,
      }));
    }

    this.setState(nextState);
  }

  fetch() {
    const { assetType } = this.props;
    const fetchParams = {
      first: this.pageSize,
      assetType,
    };

    if (this.endCursor) {
      fetchParams.after = this.endCursor;
    }

    CameraRoll.getPhotos(fetchParams)
      .then(d => this.appendAssets(d))
      /* eslint-disable no-console */
      .catch(e => console.log(e.stack));
      /* eslint-enable no-console */
  }

  renderItem(item, rowId, i) {
    if (!item) return null;
    const { gap } = this.props;
    const { uri } = item.node.image;
    const side = this.sideLength;
    const itemParams = { uri, rowId, colId: i };
    const {
      iconSelected,
      iconUnSelected,
      iconSelectedStyle,
      iconUnSelectedStyle,
    } = this.props;
    const selectProps = {
      selected: item.selected,
      iconSelected,
      iconUnSelected,
      iconSelectedStyle,
      iconUnSelectedStyle,
    };

    const itemStyle = {
      marginTop: +rowId ? gap : 0,
      marginLeft: i ? gap : 0,
      marginRight: 0,
      marginBottom: 0,
      position: 'relative',
    };

    return (
      <TouchableWithoutFeedback
        key={uri}
        onPress={this.onSelectImage(itemParams)}
      >
        <View style={itemStyle}>
          <Image source={{ uri }} style={{ width: side, height: side }} />
          <SelectTick {...selectProps} />
        </View>
      </TouchableWithoutFeedback>
    );
  }

  renderRow(rowData, sectionId, rowId) {
    return (
      <View style={style.row}>
        {rowData.map((d, i) => this.renderItem(d, rowId, i))}
      </View>
    );
  }

  render() {
    return (
      <ListView
        style={this.props.style}
        enableEmptySections
        dataSource={this.state.dataSource}
        renderRow={this.renderRow}
        onEndReached={this.onEndReached}
        onEndReachedThreshold={this.sideLength}
      />
    );
  }
}

const styleShape = PropTypes.oneOfType([
  PropTypes.array,
  PropTypes.object,
  PropTypes.number,
]);

ImgRollView.propTypes = {
  /**
   * @property maxSelected
   * @type Number
   * @default 10
   * @description 最大照片选择条数
   */
  maxSelected: PropTypes.number,
  /**
   * @property gap
   * @type Number
   * @default 8
   * @description 图片间像素间隔
   */
  gap: PropTypes.number,
  /**
   * @property imagesPerRow
   * @type Number
   * @default 4
   * @description 每行显示的图片数量
   */
  imagesPerRow: PropTypes.number,
  /**
   * @property assetType
   * @type String
   * @default 'Photos'
   * @param {String} 'Photos' 图片资源
   * @param {String} 'Videos'  视频资源
   * @param {String} 'All'
   * @description 静态资源类型
   */
  assetType: PropTypes.oneOf([
    'Photos',
    'Videos',
    'All',
  ]),
  /**
   * @property onSelect
   * @type Function
   * @default () => {}
   * @description 用户选择图片时触发的回调,返回参数为 node/uri/selected/uriSelected
   */
  onSelect: PropTypes.func,
  /**
   * @property iconSelected
   * @type Element
   * @default  <Text style={style.tickInner}>v</Text>
   * @description  选中图标
   */
  iconSelected: PropTypes.element,
  /**
   * @property iconUnSelected
   * @type Element
   * @default  <Text style={style.tickInner}>x</Text>
   * @description  未选中图标
   */
  iconUnSelected: PropTypes.element,
  /**
   * @property uriList
   * @type Array
   * @default  []
   * @description  初始选中 uri
   */
  uriList: PropTypes.arrayOf(PropTypes.string),
  /**
   * @property style
   * @type Object
   * @default  null
   * @description  外层容器样式
   */
  style: styleShape,
  /**
   * @property iconSelectedStyle
   * @type Object
   * @default  null
   * @description  选中图标外框样式
   */
  iconSelectedStyle: styleShape,
  /**
   * @property iconUnSelectedStyle
   * @type Object
   * @default  null
   * @description  未选中图标外框样式
   */
  iconUnSelectedStyle: styleShape,
};

ImgRollView.defaultProps = {
  maxSelected: 10,
  gap: 8,
  imagesPerRow: 4,
  assetType: 'Photos',
  iconSelected: <Text style={style.tickInner}>v</Text>,
  iconUnSelected: <Text style={style.tickInner}>x</Text>,
  onSelect: () => {},
  uriList: [],
};

export default ImgRollView;


text:
using namespace llvm;

namespace {

class WebAssemblyAsmBackend final : public MCAsmBackend {
  bool Is64Bit;
  bool IsEmscripten;

public:
  explicit WebAssemblyAsmBackend(bool Is64Bit, bool IsEmscripten)
      : MCAsmBackend(support::little), Is64Bit(Is64Bit),
        IsEmscripten(IsEmscripten) {}

  unsigned getNumFixupKinds() const override {
    return WebAssembly::NumTargetFixupKinds;
  }

  const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const override;

  void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
                  const MCValue &Target, MutableArrayRef<char> Data,
                  uint64_t Value, bool IsPCRel,
                  const MCSubtargetInfo *STI) const override;

  std::unique_ptr<MCObjectTargetWriter>
  createObjectTargetWriter() const override;

  // No instruction requires relaxation
  bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
                            const MCRelaxableFragment *DF,
                            const MCAsmLayout &Layout) const override {
    return false;
  }

  bool mayNeedRelaxation(const MCInst &Inst,
                         const MCSubtargetInfo &STI) const override {
    return false;
  }

  bool writeNopData(raw_ostream &OS, uint64_t Count) const override;
};

const MCFixupKindInfo &
WebAssemblyAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
  const static MCFixupKindInfo Infos[WebAssembly::NumTargetFixupKinds] = {
      // This table *must* be in the order that the fixup_* kinds are defined in
      // WebAssemblyFixupKinds.h.
      //
      // Name                     Offset (bits) Size (bits)     Flags
      {"fixup_sleb128_i32", 0, 5 * 8, 0},
      {"fixup_sleb128_i64", 0, 10 * 8, 0},
      {"fixup_uleb128_i32", 0, 5 * 8, 0},
  };

  if (Kind < FirstTargetFixupKind)
    return MCAsmBackend::getFixupKindInfo(Kind);

  assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
         "Invalid kind!");
  return Infos[Kind - FirstTargetFixupKind];
}

bool WebAssemblyAsmBackend::writeNopData(raw_ostream &OS,
                                         uint64_t Count) const {
  for (uint64_t I = 0; I < Count; ++I)
    OS << char(WebAssembly::Nop);

  return true;
}

void WebAssemblyAsmBackend::applyFixup(const MCAssembler &Asm,
                                       const MCFixup &Fixup,
                                       const MCValue &Target,
                                       MutableArrayRef<char> Data,
                                       uint64_t Value, bool IsPCRel,
                                       const MCSubtargetInfo *STI) const {
  const MCFixupKindInfo &Info = getFixupKindInfo(Fixup.getKind());
  assert(Info.Flags == 0 && "WebAssembly does not use MCFixupKindInfo flags");

  unsigned NumBytes = alignTo(Info.TargetSize, 8) / 8;
  if (Value == 0)
    return; // Doesn't change encoding.

  // Shift the value into position.
  Value <<= Info.TargetOffset;

  unsigned Offset = Fixup.getOffset();
  assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");

  // For each byte of the fragment that the fixup touches, mask in the
  // bits from the fixup value.
  for (unsigned I = 0; I != NumBytes; ++I)
    Data[Offset + I] |= uint8_t((Value >> (I * 8)) & 0xff);
}

std::unique_ptr<MCObjectTargetWriter>
WebAssemblyAsmBackend::createObjectTargetWriter() const {
  return createWebAssemblyWasmObjectWriter(Is64Bit, IsEmscripten);
}

} // end anonymous namespace

MCAsmBackend *llvm::createWebAssemblyAsmBackend(const Triple &TT) {
  return new WebAssemblyAsmBackend(TT.isArch64Bit(), TT.isOSEmscripten());
}


text:
package net.java.sip.communicator.impl.protocol.jabber.extensions.jingle;

import net.java.sip.communicator.impl.protocol.jabber.extensions.*;

/**
 * Represents the content <tt>inputevt</tt> element that may be find in
 * <tt>content</tt> part of a Jingle media negociation.
 *
 * @author Sebastien Vincent
 */
public class InputEvtPacketExtension extends AbstractPacketExtension
{
    /**
     * Name of the XML element representing the extension.
     */
    public final static String ELEMENT_NAME = "inputevt";

    /**
     * Namespace..
     */
    public final static String NAMESPACE =
        "http://jitsi.org/protocol/inputevt";

    /**
     * Constructs a new <tt>inputevt</tt> extension.
     */
    public InputEvtPacketExtension()
    {
        super(NAMESPACE, ELEMENT_NAME);
    }
}