text:
#include "response.h"

#include <err.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/sendfile.h>
#include <sys/socket.h>
#include <unistd.h>

void response_init(Response *response) {
	memset(response, 0, sizeof(Response));
	response->body_fd = -1;
}

void response_destroy(Response *response) {
	free(response->body_buffer);
	if (response->body_fd >= 0) {
		close(response->body_fd);
	}
}

static const char *reason_phrase(int status) {
	switch (status) {
		case STATUS_OK: return "OK";
		case STATUS_BAD_REQUEST: return "Bad Request";
		case STATUS_FORBIDDEN: return "Forbidden";
		case STATUS_NOT_FOUND: return "Not Found";
		case STATUS_METHOD_NOT_ALLOWED: return "Method Not Allowed";
		case STATUS_REQUEST_ENTITY_TOO_LARGE: return "Request Entity Too Large";
		case STATUS_INTERNAL_SERVER_ERROR: return "Internal Server Error";
		case STATUS_HTTP_VERSION_NOT_SUPPORTED: return "HTTP Version Not Supported";
		default: return "";
	}
}

static bool response_printf(Response *response, const char *format, ...) {
	int remaining_space = MAX_RESPONSE_HEADERS_SIZE - response->headers_size;
	va_list ap;
	va_start(ap, format);
	int bytes_written = vsnprintf(&response->headers[response->headers_size], remaining_space, format, ap);
	va_end(ap);
	if (bytes_written > remaining_space) {
		warnx("response header buffer overflow");
		return false;
	}
	response->headers_size += bytes_written;
	return true;
}

bool response_set_status(Response *response, int status) {
	if (response->status) {
		warnx("response status already set to %d, tried to set to %d", response->status, status);
		return false;
	}
	if (response->headers_size > 0) {
		warnx("tried to set response status to %d after headers added", status);
		return false;
	}
	response->status = status;
	return response_printf(response, "HTTP/" HTTP_VERSION " %d %s\r\n", response->status, reason_phrase(response->status));
}

bool response_set_failure(Response *response, int status) {
	if (!response_set_status(response, status)) return false;
	response->body_buffer = malloc(1024);
	response->body_size = snprintf(response->body_buffer, 1024, "%d %s\n", status, reason_phrase(status));
	return true;
}

bool response_set_header(Response *response, char *key, char *value) {
	return response_printf(response, "%s: %s\r\n", key, value);
}

static bool write_all(int fd, const char *buffer, int size, bool more_coming) {
	while (size > 0) {
		int bytes_written = send(fd, buffer, size, more_coming ? MSG_MORE : 0);
		if (bytes_written < 0) {
			warn("send failed");
			return false;
		}
		buffer += bytes_written;
		size -= bytes_written;
	}
	return true;
}

bool response_send_headers(Response *response, int fd) {
	if (!response_printf(response, "\r\n")) return false;
	write_all(fd, response->headers, response->headers_size, true);
	return true;
}

static bool response_send_from_fd(Response *response, int fd) {
	int result = sendfile(fd, response->body_fd, NULL, response->body_size);
	if (result < 0) {
		warn("sendfile failed");
		return false;
	} else if (result < response->body_size) {
		warnx("sendfile did not send enough data");
		return false;
	}
	return true;
	/*
	char buffer[READ_BUFFER_SIZE];
	int bytes_read;
	while ((bytes_read = read(response->body_fd, buffer, READ_BUFFER_SIZE)) != 0) {
		if (bytes_read < 0) {
			warn("read failed");
			return false;
		}
		write_all(fd, buffer, bytes_read);
	}
	return true;
	*/
}

bool response_send_body(Response *response, int fd) {
	if (response->body_buffer) {
		return write_all(fd, response->body_buffer, response->body_size, false);
	} else if (response->body_fd) {
		return response_send_from_fd(response, fd);
	}
	return true;
}


text:
package com.google.android.apps.forscience.whistlepunk.opensource.modules;

import com.google.android.apps.forscience.whistlepunk.performance.PerfTrackerProvider;
import dagger.Module;
import dagger.Provides;

@Module
public class PerfTrackerModule {
  @Provides
  public PerfTrackerProvider providesPerfTracker() {
    return PerfTrackerProvider.STUB;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.example.android.sunshine.app;

import android.graphics.Color;
import android.net.Uri;
import android.util.Log;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.Wearable;

public final class DigitalWatchFaceUtil {
    private static final String TAG = "DigitalWatchFaceUtil";

    /**
     * The {@link DataMap} key for {@link SunshineWatchFaceService} background color name.
     * The color name must be a {@link String} recognized by {@link Color#parseColor}.
     */
    public static final String KEY_BACKGROUND_COLOR = "BACKGROUND_COLOR";

    /**
     * The {@link DataMap} key for {@link SunshineWatchFaceService} hour digits color name.
     * The color name must be a {@link String} recognized by {@link Color#parseColor}.
     */
    public static final String KEY_HOURS_COLOR = "HOURS_COLOR";

    /**
     * The {@link DataMap} key for {@link SunshineWatchFaceService} minute digits color name.
     * The color name must be a {@link String} recognized by {@link Color#parseColor}.
     */
    public static final String KEY_MINUTES_COLOR = "MINUTES_COLOR";

    /**
     * The {@link DataMap} key for {@link SunshineWatchFaceService} second digits color name.
     * The color name must be a {@link String} recognized by {@link Color#parseColor}.
     */
    public static final String KEY_SECONDS_COLOR = "SECONDS_COLOR";

    /**
     * The path for the {@link DataItem} containing {@link SunshineWatchFaceService} configuration.
     */
    public static final String PATH_WITH_FEATURE = "/watch_face_config/Digital";

    /**
     * Name of the default interactive mode background color and the ambient mode background color.
     */
    public static final String COLOR_NAME_DEFAULT_AND_AMBIENT_BACKGROUND = "#1CA8F4";
    public static final int COLOR_VALUE_DEFAULT_AND_AMBIENT_BACKGROUND =
            parseColor(COLOR_NAME_DEFAULT_AND_AMBIENT_BACKGROUND);

    /**
     * Name of the default interactive mode hour digits color and the ambient mode hour digits
     * color.
     */
    public static final String COLOR_NAME_DEFAULT_AND_AMBIENT_HOUR_DIGITS = "White";
    public static final int COLOR_VALUE_DEFAULT_AND_AMBIENT_HOUR_DIGITS =
            parseColor(COLOR_NAME_DEFAULT_AND_AMBIENT_HOUR_DIGITS);

    /**
     * Name of the default interactive mode minute digits color and the ambient mode minute digits
     * color.
     */
    public static final String COLOR_NAME_DEFAULT_AND_AMBIENT_MINUTE_DIGITS = "White";
    public static final int COLOR_VALUE_DEFAULT_AND_AMBIENT_MINUTE_DIGITS =
            parseColor(COLOR_NAME_DEFAULT_AND_AMBIENT_MINUTE_DIGITS);

    /**
     * Callback interface to perform an action with the current config {@link DataMap} for
     * {@link SunshineWatchFaceService}.
     */
    public interface FetchConfigDataMapCallback {
        /**
         * Callback invoked with the current config {@link DataMap} for
         * {@link SunshineWatchFaceService}.
         */
        void onConfigDataMapFetched(DataMap config);
    }

    private static int parseColor(String colorName) {
        return Color.parseColor(colorName.toLowerCase());
    }

    /**
     * Helper method to provide the art resource id according to the weather condition id returned
     * by the OpenWeatherMap call.
     * @param weatherId from OpenWeatherMap API response
     * @return resource id for the corresponding icon. -1 if no relation is found.
     */
    public static int getArtResourceForWeatherCondition(int weatherId) {
        // Based on weather code data found at:
        // http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
        if (weatherId >= 200 && weatherId <= 232) {
            return R.mipmap.ic_storm;
        } else if (weatherId >= 300 && weatherId <= 321) {
            return R.mipmap.ic_light_rain;
        } else if (weatherId >= 500 && weatherId <= 504) {
            return R.mipmap.ic_rain;
        } else if (weatherId == 511) {
            return R.mipmap.ic_snow;
        } else if (weatherId >= 520 && weatherId <= 531) {
            return R.mipmap.ic_rain;
        } else if (weatherId >= 600 && weatherId <= 622) {
            return R.mipmap.ic_snow;
        } else if (weatherId >= 701 && weatherId <= 761) {
            return R.mipmap.ic_fog;
        } else if (weatherId == 761 || weatherId == 781) {
            return R.mipmap.ic_storm;
        } else if (weatherId == 800) {
            return R.mipmap.ic_clear;
        } else if (weatherId == 801) {
            return R.mipmap.ic_light_clouds;
        } else if (weatherId >= 802 && weatherId <= 804) {
            return R.mipmap.ic_cloudy;
        }
        return -1;
    }

    /**
     * Asynchronously fetches the current config {@link DataMap} for {@link SunshineWatchFaceService}
     * and passes it to the given callback.
     *

     * If the current config {@link DataItem} doesn't exist, it isn't created and the callback
     * receives an empty DataMap.
     */
    public static void fetchConfigDataMap(final GoogleApiClient client,
            final FetchConfigDataMapCallback callback) {
        Wearable.NodeApi.getLocalNode(client).setResultCallback(
                new ResultCallback<NodeApi.GetLocalNodeResult>() {
                    @Override
                    public void onResult(NodeApi.GetLocalNodeResult getLocalNodeResult) {
                        String localNode = getLocalNodeResult.getNode().getId();
                        Uri uri = new Uri.Builder()
                                .scheme("wear")
                                .path(DigitalWatchFaceUtil.PATH_WITH_FEATURE)
                                .authority(localNode)
                                .build();
                        Wearable.DataApi.getDataItem(client, uri)
                                .setResultCallback(new DataItemResultCallback(callback));
                    }
                }
        );
    }

    /**
     * Overwrites (or sets, if not present) the keys in the current config {@link DataItem} with
     * the ones appearing in the given {@link DataMap}. If the config DataItem doesn't exist,
     * it's created.
     *

     * It is allowed that only some of the keys used in the config DataItem appear in
     * {@code configKeysToOverwrite}. The rest of the keys remains unmodified in this case.
     */
    public static void overwriteKeysInConfigDataMap(final GoogleApiClient googleApiClient,
            final DataMap configKeysToOverwrite) {

       DigitalWatchFaceUtil.fetchConfigDataMap(googleApiClient,
                new FetchConfigDataMapCallback() {
                    @Override
                    public void onConfigDataMapFetched(DataMap currentConfig) {
                        DataMap overwrittenConfig = new DataMap();
                        overwrittenConfig.putAll(currentConfig);
                        overwrittenConfig.putAll(configKeysToOverwrite);
                       DigitalWatchFaceUtil.putConfigDataItem(googleApiClient, overwrittenConfig);
                    }
                }
        );
    }

    /**
     * Overwrites the current config {@link DataItem}'s {@link DataMap} with {@code newConfig}.
     * If the config DataItem doesn't exist, it's created.
     */
    public static void putConfigDataItem(GoogleApiClient googleApiClient, DataMap newConfig) {
        PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(PATH_WITH_FEATURE);
        DataMap configToPut = putDataMapRequest.getDataMap();
        configToPut.putAll(newConfig);
        Wearable.DataApi.putDataItem(googleApiClient, putDataMapRequest.asPutDataRequest())
                .setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
                    @Override
                    public void onResult(DataApi.DataItemResult dataItemResult) {
                        if (Log.isLoggable(TAG, Log.DEBUG)) {
                            Log.d(TAG, "putDataItem result status: " + dataItemResult.getStatus());
                        }
                    }
                });
    }

    private static class DataItemResultCallback implements ResultCallback<DataApi.DataItemResult> {

        private final FetchConfigDataMapCallback mCallback;

        public DataItemResultCallback(FetchConfigDataMapCallback callback) {
            mCallback = callback;
        }

        @Override
        public void onResult(DataApi.DataItemResult dataItemResult) {
            if (dataItemResult.getStatus().isSuccess()) {
                if (dataItemResult.getDataItem() != null) {
                    DataItem configDataItem = dataItemResult.getDataItem();
                    DataMapItem dataMapItem = DataMapItem.fromDataItem(configDataItem);
                    DataMap config = dataMapItem.getDataMap();
                    mCallback.onConfigDataMapFetched(config);
                } else {
                    mCallback.onConfigDataMapFetched(new DataMap());
                }
            }
        }
    }

    private DigitalWatchFaceUtil() { }
}


text:
@interface PPJEmailPickerDemoTests : XCTestCase
@property (strong, nonatomic) PPJEmailPicker *email;
@end

@implementation PPJEmailPickerDemoTests

- (void)setUp {
    [super setUp];
	self.email = [[PPJEmailPicker alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0f, 30.0f)];
}

- (void) tearDown {
	[super tearDown];
	self.email = nil;
}

- (void)testCreation {
	XCTAssert(self.email != nil, @"Check creation");
}

- (void) testInitialSize {
	XCTAssert(self.email.frame.size.width == 320.0f, @"Width");
	XCTAssert(self.email.frame.size.height == 30.0f, @"Height");
}

- (void) testAccessibility {
	self.email.text = @"Hello";
	XCTAssert([self.email.accessibilityLabel isEqualToString:@"Hello"]);
}

- (void) testStringSanitation
{
    NSString * sanitize = @"John Rambo<jrr@army.mil>";
    XCTAssert([[sanitize sanitizeString] isEqualToString:@"jrr@army.mil"]);
}

- (void) testStringPartialSanitation
{
    NSString * sanitize = @"John Rambo<jrr@army.mil";
    XCTAssert([[sanitize sanitizeString] isEqualToString:@"jrr@army.mil"]);
}

@end


text:
function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

function loadReusableComponents() {
  //insert elements, even before Polymer is loaded

  //first element of the original document
  var firstElement = document.body.children[0];

  //insert alerts before header
  var alerts = document.querySelector('uqlibrary-alerts');
  if (!alerts) {
    //as a back up insert header if it's not defined already
    alerts = document.createElement('uqlibrary-alerts');
    document.body.insertBefore(alerts, firstElement);
  }

  // insert header after body-tag
  var header = document.createElement('uq-minimal-header');
  document.body.insertBefore(header, firstElement);

  // insert mega menus after minimal header
  var menu = document.createElement('uql-menu');
  document.body.insertBefore(menu, firstElement);

  // insert sub footer before body-tag
  var subFooter = document.createElement('uql-connect-footer');
  document.body.appendChild(subFooter);

  // insert footer before body-tag
  var footer = document.createElement('uq-minimal-footer');
  document.body.appendChild(footer);

  window.addEventListener('WebComponentsReady', function() {
    // when polymer is ready - configure elements

    header.showLoginButton = false;
    //display hamburger button on mobile view
    header.showMenuButton = true;

    header.addEventListener("menu-clicked", function(event) {
      menu.toggleMenu();
    });

  });
}

ready(loadReusableComponents);


text:
$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"

Describe "Confirm-DownloadChoice" {
    It "requires the VideoName parameter" -Skip {
        Confirm-DownloadChoice -Confirm:$false |
            Should Throw
    }

    It "requires a value for the VideoName parameter" {
        { Confirm-DownloadChoice -VideoName } |
            Should Throw
    }

    It "returns false when SkipConfirm is set" {
        $SkipConfirm = $true
        Confirm-DownloadChoice -VideoName "random name" |
            Should Be $false
    }

    It "returns true when AlwaysConfirm is set" {
        $AlwaysConfirm = $true
        Confirm-DownloadChoice -VideoName "random name" |
            Should Be $true
    }
}


text:
'use strict';

angular.module('somafmPlayerApp')
  .directive("sfVolumebar", [
    function () {
      return {
        restrict :"E",
        replace: true,
        scope: {
          value: "=",
          valueChange: "&"
        },
        templateUrl: 'common/volumebar.tpl.html',
        link: function (scope, element, attr) {
          var width,
            offset,
            scrubber = element.children().eq(1),
            dragging = false;

          scope.$watch('value', function (val) {
            scrubber.css("width", val / attr.max * 100 + "%");
          });

          element.on('mousedown', function (event) {
            dragging = true;
            width =  element[0].getBoundingClientRect().width;
            offset = element[0].getBoundingClientRect().left;
          });

          element.on('mouseup', function (event) {
            dragging = false;
            _calcScrubberWidth(event.pageX);
          });

          element.on('mousemove', function (event) {
            if (dragging) {
              _calcScrubberWidth(event.pageX);
            }
          });

          function _calcScrubberWidth (x) {
            var dif = x - offset;

            if (dif < 0) {
              dif = attr.min;
              scrubber.css("width", "0%");
              scope.value = attr.min;
            }
            else if (dif > width) {
              dif = attr.max;
              scrubber.css("width", "100%");
              scope.value = attr.max;
            }
            else {
              var per = dif / width;
              scrubber.css("width", per * 100 + "%");
              scope.value = per * attr.max;
            }

            scope.valueChange({val: scope.value});

            scope.$apply();
          }

        }
      }
    }
  ]);


text:
"use strict";

// Implements a CSV (comma separated values) grammar using the Myna parsing library
// See https://tools.ietf.org/html/rfc4180
// Because this grammar is computed at run-time, it can support tab delimited data by passing in "\t"
// to the constructor as the delimiter.
function CreateCsvGrammar(myna, delimiter)
{
    if (delimiter === undefined)
        delimiter = ",";

    // Set a shorthand for the Myna parsing library object
    let m = myna;

    let g = new function()
    {
        this.textdata   = m.notChar('\n\r"' + delimiter);
        this.quoted     = m.doubleQuoted(m.notChar('"').or('""').zeroOrMore);
        this.field      = this.textdata.or(this.quoted).zeroOrMore.ast;
        this.record     = this.field.delimited(delimiter).ast;
        this.file       = this.record.delimited(m.newLine).ast;
    }

    // Register the grammar, providing a name and the default parse rule
    myna.registerGrammar("csv", g, g.file);
}

// Export the grammar for usage by Node.js and CommonJs compatible module loaders
if (typeof module === "object" && module.exports)
    module.exports = CreateCsvGrammar;


text:
package com.siyeh.ig.style;

import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.refactoring.util.LambdaRefactoringUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class LambdaParameterTypeCanBeSpecifiedInspection extends BaseInspection {

  @Nls
  @NotNull
  @Override
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("lambda.parameter.type.can.be.specified.name");
  }

  @NotNull
  @Override
  protected String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message("lambda.parameter.type.can.be.specified.descriptor", infos);
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new InferLambdaParameterTypeVisitor();
  }

  @Nullable
  @Override
  protected InspectionGadgetsFix buildFix(Object... infos) {
    return new InferLambdaParameterTypeFix(infos);
  }

  private static class InferLambdaParameterTypeVisitor extends BaseInspectionVisitor {
    @Override
    public void visitLambdaExpression(PsiLambdaExpression lambdaExpression) {
      super.visitLambdaExpression(lambdaExpression);
      final PsiParameter[] parameters = lambdaExpression.getParameterList().getParameters();
      if (parameters.length == 0) return;
      for (PsiParameter parameter : parameters) {
        if (parameter.getTypeElement() != null) {
          return;
        }
      }
      final PsiType functionalInterfaceType = lambdaExpression.getFunctionalInterfaceType();
      if (functionalInterfaceType != null &&
          LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType) != null) {
        final String inferredTypesText = LambdaRefactoringUtil.createLambdaParameterListWithFormalTypes(functionalInterfaceType, lambdaExpression,
                                                                                true);
        if (inferredTypesText != null) {
          registerError(lambdaExpression, inferredTypesText);
        }
      }
    }
  }

  private static class InferLambdaParameterTypeFix extends InspectionGadgetsFix {
    private final Object[] myInfos;

    public InferLambdaParameterTypeFix(Object... infos) {
      myInfos = infos;
    }

    @Nls
    @NotNull
    @Override
    public String getName() {
      return InspectionGadgetsBundle.message("lambda.parameter.type.can.be.specified.quickfix", myInfos);
    }

    @Nls
    @NotNull
    @Override
    public String getFamilyName() {
      return InspectionGadgetsBundle.message("lambda.parameter.type.can.be.specified.family.quickfix");
    }

    @Override
    protected void doFix(Project project, ProblemDescriptor descriptor) {
      final PsiElement element = descriptor.getPsiElement();
      if (element instanceof PsiLambdaExpression) {
        LambdaRefactoringUtil.specifyLambdaParameterTypes((PsiLambdaExpression)element);
      }
    }
  }
}


text:
static char const *const heightKey = "Height";

@implementation UINavigationBar (CustomHeight)

- (void)setHeight:(CGFloat)height
{
    objc_setAssociatedObject(self, heightKey, @(height), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSNumber *)height
{
    return objc_getAssociatedObject(self, heightKey);
}

- (CGSize)sizeThatFits:(CGSize)size
{
    CGSize newSize;

    if (self.height) {
        newSize = CGSizeMake(self.superview.bounds.size.width, [self.height floatValue]);
    } else {
        newSize = [super sizeThatFits:size];
    }

    return newSize;
}

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Webapp Boilerplate</title>
    <link rel="icon" type="image/png" href="favicon.png" />

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

    <link rel="stylesheet" href=".tmp/css/main.css">

        <page-header project-name="Webapp Boilerplate"></page-header>

        <page-footer author="Maurizio Battaghini" year="2016"></page-footer>


text:
package com.example;

import org.junit.jupiter.api.Test;
import org.rapidoid.annotation.IntegrationTest;
import org.rapidoid.http.Self;
import org.rapidoid.test.RapidoidIntegrationTest;
import org.rapidoid.u.U;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * This test will execute the main class specified in the annotation.
 */
@IntegrationTest(main = DslJsonExample.class)
public class DslJsonTest extends RapidoidIntegrationTest {

    @Test
    public void testHelloWorld() {
        // connects to the local server that was started by the Main class (http://localhost:8080)
        // then sends HTTP request GET /hello and parses the JSON result as Map
        Map<String, Object> resp = Self.get("/hello").toMap();

        eq(resp, U.map("msg", "Hello, world!"));
    }

    @Test
    public void testPost() {
        Map<String, Object> resp = Self.post("/compiled").body("{\"x\":3,\"s\":\"a\"}".getBytes(Charset.forName("UTF-8"))).toMap();

        eq(resp, U.map("x", 6, "s", "a"));
    }
}


text:
namespace pugi {
class xml_node;
};

class VCProjectConfigurationPlatform;

typedef std::map<std::string, VCProjectConfigurationPlatform*> PlatformMap;

class VCProjectConfiguration {
public:
    friend class VCProject;

    ~VCProjectConfiguration();
    const std::string& getName() const;
    const PlatformMap& getPlatforms() const;
    VCProjectConfigurationPlatform* addPlatform(const std::string& platformName);
    void removePlatform(const std::string& platform);
    bool setProperty(const std::string& pName, const std::string& pValue);
    bool setItemDefinition(const std::string& item, const std::string& pName, const std::string& pValue);

    void writeSummary(pugi::xml_node& parent) const;
    void writeProperties(pugi::xml_node& bookmark) const;
    void writePropertySheets(pugi::xml_node& bookmark) const;
    void writeItemDefinitions(pugi::xml_node& bookmark) const;

private:
    VCProjectConfiguration(const std::string& name);

    std::string m_name;
    PlatformMap m_platforms;
};


text:
#import <OfficeImport/WBPicture.h>

// Not exported
@interface WBOleObject : WBPicture
{
}

+ (void)readFrom:(id)arg1 at:(int)arg2 oleId:(unsigned int)arg3 textRun:(struct WrdCharacterTextRun *)arg4 paragraph:(id)arg5 to:(id)arg6;

@end


text:
package com.chinamobile.bcbsp.comm;

import com.chinamobile.bcbsp.api.Vertex;
import com.chinamobile.bcbsp.comm.io.util.ExtendedByteArrayDataInput;
import com.chinamobile.bcbsp.comm.io.util.ExtendedByteArrayDataOutput;
import com.chinamobile.bcbsp.comm.io.util.ExtendedDataInput;
import com.chinamobile.bcbsp.comm.io.util.ExtendedDataOutput;
import com.chinamobile.bcbsp.comm.io.util.MessageBytePoolPerPartition;
//import com.chinamobile.bcbsp.ml.PeerMessageInterface;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

/**
 * Constructor of GraphDataFactory. Providing The Unified Interface.
 *
 * @author Liu Jinpeng
 */
public class CommunicationFactory {
  /** message class. */
  private static Class messageClass;
  /** Class logger. */
  private static final Log LOG = LogFactory.getLog(CommunicationFactory.class);
  // SGA-Graph
  private static Class vertexClass;

  /**
   * Constructor of CommunicationFactory.
   */
  private CommunicationFactory() {
  }

  /**
   * Set method of messageClass.
   *
   * @param cls
   */
  public static void setMessageClass(Class cls) {
    messageClass = cls;
    LOG.info("[Message Class Name Is] " + messageClass.getName());
  }

  /** Create the message byte thread pool of per partition. */
  public static MessageBytePoolPerPartition createMsgBytesPoolPerPartition() {
    return new MessageBytePoolPerPartition(10000);
  }

  /**
   * Creates a new byte array output stream, with a buffer capacity of the
   * specified size, in bytes.
   *
   * @param size
   * @return ExtendedDataOutput
   */
  public static ExtendedDataOutput createBytesPool(int size) {
    return new ExtendedByteArrayDataOutput(size);
  }

  /**
   * Creates a new byte array output stream, with a buffer capacity of the
   * specified size, in bytes.
   *
   * @param size
   * @param buf
   * @return ExtendedDataOutput
   */
  public static ExtendedDataOutput createBytesPool(byte[] buf, int size) {
    return new ExtendedByteArrayDataOutput(buf, size);
  }

  /**
   * Creates a new byte array output stream, with a buffer capacity of the
   * specified size, in bytes.
   *
   * @param buf
   *        byte[]
   * @param length
   *        int
   * @return ExtendedDataOutput
   */
  public static ExtendedDataInput createExtendedDataInput(byte[] buf, int off,
      int length) {
    return new ExtendedByteArrayDataInput(buf, off, length);
  }

  /**
   * Create BSP message.
   *
   * @return IMessage
   */
  public static IMessage createBspMessage() {
    LOG.info("ljn test : create BSP message");
    return new BSPMessage();
  }

  // /**
  // * Create Pagerank message.
  // * @return IMessage
  // */
  // public static PeerMessageInterface createPeerMessage() {
  // try {
  // return (PeerMessageInterface) messageClass.newInstance();
  // } catch (InstantiationException e) {
  // throw new RuntimeException("[CombinerTool] caught", e);
  // } catch (IllegalAccessException e) {
  // throw new RuntimeException("[CombinerTool] caught", e);
  // }
  // // return new BSPMessage();
  // }
  public static IMessage createPagerankMessage() {
    try {
      return (IMessage) messageClass.newInstance();
    } catch (InstantiationException e) {
      throw new RuntimeException("[CombinerTool] caught", e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException("[CombinerTool] caught", e);
    }
    // return new BSPMessage();
  }

  public static Vertex createVertex() {
    try {
      return (Vertex) vertexClass.newInstance();
    } catch (InstantiationException e) {
      throw new RuntimeException("[CreateVertex] caught", e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException("[CreateVertex] caught", e);
    }
  }

  public static void setVertexClass(Class vertexClass) {
    CommunicationFactory.vertexClass = vertexClass;
  }
}


text:
try:
    import setuptools
except ImportError:
    print "Missing module setuptools."
    exit(1)

try:
    import distutils.core
except ImportError:
    print "Missing module distutils.core."
    exit(1)

try:
    import google.protobuf
except ImportError:
    print "Missing module google.protobuf."
    exit(1)

try:
    import urllib3
except ImportError:
    print "Missing module urllib3."
    exit(1)

from distutils.core import setup
setup(
    name='ots_python_sdk',
    description='SDK of Open Table Service',
    author='Haowei YAO, Kunpeng HAN',
    author_email='haowei.yao@aliyun-inc.com, kunpeng.hkp@aliyun-inc.com',
    url='http://ots.aliyun.com',
    version='2.0.2',
    packages=['ots2', 'ots2.protobuf', 'ots2.example'],
    requires=['protobuf'],
)


text:
// wxterminal.h                               Copyright (C) A C Norman 2020

// header file to go with wxterminal.cpp

#ifndef header_wxterminal_h
#define header_wxterminal_h 1

// $Id: wxterminal.h 5432 2020-10-15 20:40:59Z arthurcnorman $

// The events declared here are used to send data from the worker thread
// to the GUI thread.

//wxDECLARE_EVENT(SET_PROMPT,        wxCommandEvent);
//wxDECLARE_EVENT(TO_SCREEN,         wxCommandEvent);
//wxDECLARE_EVENT(SET_SWITCH_MENU,   wxCommandEvent);
//wxDECLARE_EVENT(SET_PACKAGE_MENU,  wxCommandEvent);

#endif // header_wxterminal_h

// end of wxterminal.h


text:
CREATE TABLE [dbo].[Announcement] (
    [AnnouncementId] UNIQUEIDENTIFIER NOT NULL,
    [Message]        VARCHAR (256)    NOT NULL,
    [StartDate]      DATETIME         NOT NULL,
    [EndDate]        DATETIME         NOT NULL,
    [Severity]       VARCHAR (16)     NOT NULL,
    [CompanyId]      UNIQUEIDENTIFIER NOT NULL,
    [IsActive]       BIT              NOT NULL,
    [Name]           VARCHAR (64)     NOT NULL,
    [IsDeleted]      BIT              NOT NULL,
    PRIMARY KEY CLUSTERED ([AnnouncementId] ASC),
    FOREIGN KEY ([CompanyId]) REFERENCES [dbo].[Company] ([CompanyId])
);


text:
typedef long NSInteger;
enum {
    UIViewNone         = 0x0,
    UIViewMargin       = 0x1,
    UIViewWidth        = 0x2,
    UIViewRightMargin  = 0x3,
    UIViewBottomMargin = 0xbadbeef
};
typedef NSInteger UITableStyle;

typedef
  enum { two = 1 } NumericEnum2;

typedef enum { three = 1 } NumericEnum3;

typedef enum { four = 1 } NumericEnum4;


text:
{% extends 'layout/default.html' %}
{% block content %}

    {% raw %}

Home

            Menu

              {{jsonFile}}

      <button class="btn btn-primary" ng-click="addRow()">Add Row</button>
      <button class="btn btn-primary" ng-click="deleteRow()">Delete Row</button>
      <button class="btn btn-danger" ng-click="saveModified()">Save</button>

    {% endraw %}

{% endblock %}


text:
class MetaTbottomController extends MRM.MetaComponentController {
  constructor(dom){
    super(dom)
    this.dom = dom;
    this.metaObject = this.createMetaObject();

    this.setupComponent();
    this.parent = null;

    this.updateMetaObject()
  }

  get eventActionSettings(){
    return {
      "class": ["propagateMetaStyle"],
      "id": ["propagateMetaStyle"],
      "align": ["updateTbottomVisibility"]
    }
  }

  get metaAttachedActions(){
    return {
      "attachMetaObject": true,
      "updateTbottomVisibility": true
    }
  }

  get propertiesSettings() {
    return {
      "table-padding-top": {
        type: Number,
        default: 0.01,
        onChange: "updateMetaObject"
      },
      "thickness": {
        type: Number,
        default: 0.03,
        onChange: "updateMetaObject"
      },
      align: {
        type: String,
        default: "front",
        attrName: "align",
        // onChange: (value) => {
        //
        // }
      }
    }
  }

  get tagName() {
    return "meta-tbottom"
  }

  createMetaObject(){
    var group = new THREE.Group();

    return {
      // mesh: mesh,
      group: group
    };
  }

  updateMetaObject(){

  }

}

class MetaTbottom extends MRM.MetaComponent {
  createdCallback() {
    this.controller = new MetaTbottomController(this);
  }
  // attach callback: when attach set meta-table table geometry tbottom side to be visible
}

document.registerElement('meta-tbottom', MetaTbottom);


text:
package com.marverenic.music.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import androidx.annotation.IdRes;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

import com.marverenic.music.R;

/**
 * An {@link RecyclerView.ItemDecoration} that draws a solid color behind
 * a {@link RecyclerView} and its children
 */
public class BackgroundDecoration extends RecyclerView.ItemDecoration {

    private Drawable mBackground;
    private NinePatchDrawable mShadow;
    private int[] excludedIDs;

    /**
     * Create an ItemDecorator for use with a RecyclerView
     * @param excludedLayoutIDs A list of layoutIDs to exclude adding a background color to
     *                          empty to add a background to the entire RecyclerView
     */
    public BackgroundDecoration(@IdRes int... excludedLayoutIDs) {
        excludedIDs = excludedLayoutIDs;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();

        if (mShadow == null || mBackground == null) {
            Context ctx = parent.getContext();

            int color = ContextCompat.getColor(ctx, R.color.background_elevated);
            mBackground = new ColorDrawable(color);

            mShadow = (NinePatchDrawable) ContextCompat.getDrawable(ctx, R.drawable.list_shadow);
        }

        Rect shadowPadding = new Rect();
        mShadow.getPadding(shadowPadding);

        if (excludedIDs == null || excludedIDs.length == 0) {
            int top = 0;
            int bottom = c.getHeight();

            mBackground.setBounds(left, top, right, bottom);
            mBackground.draw(c);

            mShadow.setBounds(left - shadowPadding.left, top - shadowPadding.top,
                    right + shadowPadding.right, bottom + shadowPadding.bottom);
            mShadow.draw(c);
        } else {
            int layoutCount = parent.getChildCount();
            for (int i = 0; i < layoutCount; i++) {
                View topView = parent.getChildAt(i);
                if (includeView(topView.getId())) {

                    //noinspection StatementWithEmptyBody
                    while (++i < layoutCount && includeView(parent.getChildAt(i).getId())) {
                        // Find the last view in this section that will receive a background
                        // This loop is intentionally left empty
                    }

                    View bottomView = parent.getChildAt(--i);
                    Rect topInset = new Rect();
                    Rect endInset = new Rect();
                    parent.getLayoutManager().calculateItemDecorationsForChild(topView, topInset);
                    parent.getLayoutManager().calculateItemDecorationsForChild(bottomView, endInset);

                    RecyclerView.LayoutParams topParams =
                            (RecyclerView.LayoutParams) topView.getLayoutParams();
                    RecyclerView.LayoutParams bottomParams =
                            (RecyclerView.LayoutParams) bottomView.getLayoutParams();

                    int top = topView.getTop() - topParams.topMargin - topInset.top;
                    int bottom;

                    if (i == layoutCount - 1 || parent.getChildAdapterPosition(bottomView)
                            == parent.getAdapter().getItemCount() - 1) {
                        // If this is the last item in the adapter or last visible view,
                        // fill the parent
                        bottom = parent.getBottom();
                    } else {
                        // Otherwise, fill to the bottom of the last item in the section
                        bottom = bottomView.getBottom() + endInset.bottom
                                + bottomParams.bottomMargin;
                    }

                    mBackground.setBounds(left, top, right, bottom);
                    mBackground.draw(c);

                    mShadow.setBounds(left - shadowPadding.left, top - shadowPadding.top,
                            right + shadowPadding.right, bottom + shadowPadding.bottom);
                    mShadow.draw(c);
                }
            }
        }
    }

    private boolean includeView(int viewId) {
        for (int i : excludedIDs) {
            if (viewId == i) {
                return false;
            }
        }
        return true;
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NpgsqlAppLifecycleBehavior.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Implements the Npgsql feature manager class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Npgsql.Application
{
    using System.Threading;
    using System.Threading.Tasks;

    using global::Npgsql.Logging;

    using Kephas.Application;
    using Kephas.Logging;
    using Kephas.Npgsql.Logging;
    using Kephas.Services;
    using Kephas.Threading.Tasks;

    /// <summary>
    /// The Npgsql application lifecycle behavior.
    /// </summary>
    public class NpgsqlAppLifecycleBehavior : IAppLifecycleBehavior
    {
        /// <summary>
        /// Interceptor called before the application starts its asynchronous initialization.
        /// </summary>
        /// <param name="appContext">Context for the application.</param>
        /// <param name="cancellationToken">Optional. The cancellation token.</param>
        /// <returns>
        /// The asynchronous result.
        /// </returns>
        public Task BeforeAppInitializeAsync(IContext appContext, CancellationToken cancellationToken = default)
        {
            NpgsqlLogManager.Provider = new NpgsqlLoggingProviderAdapter(appContext.CompositionContext.GetExport<ILogManager>());

            return Task.CompletedTask;
        }

        /// <summary>
        /// Interceptor called after the application completes its asynchronous initialization.
        /// </summary>
        /// <param name="appContext">Context for the application.</param>
        /// <param name="cancellationToken">Optional. The cancellation token.</param>
        /// <returns>
        /// The asynchronous result.
        /// </returns>
        public Task AfterAppInitializeAsync(IContext appContext, CancellationToken cancellationToken = default)
        {
            return Task.CompletedTask;
        }

        /// <summary>
        /// Interceptor called before the application starts its asynchronous finalization.
        /// </summary>
        /// <param name="appContext">Context for the application.</param>
        /// <param name="cancellationToken">Optional. The cancellation token.</param>
        /// <returns>
        /// A Task.
        /// </returns>
        public Task BeforeAppFinalizeAsync(IContext appContext, CancellationToken cancellationToken = default)
        {
            return Task.CompletedTask;
        }

        /// <summary>
        /// Interceptor called after the application completes its asynchronous finalization.
        /// </summary>
        /// <param name="appContext">Context for the application.</param>
        /// <param name="cancellationToken">Optional. The cancellation token.</param>
        /// <returns>
        /// A Task.
        /// </returns>
        public Task AfterAppFinalizeAsync(IContext appContext, CancellationToken cancellationToken = default)
        {
            return Task.CompletedTask;
        }
    }
}


text:
<?php

namespace Trello\Tests\Functional;

use Trello\Client;
use Trello\Exception\ApiLimitExceedException;
use Trello\Exception\RuntimeException;

/**
 * @group functional
 */
class TestCase extends \PHPUnit_Framework_TestCase
{
    protected $boardId;

    /**
     * Trello client
     * @var Client
     */
    protected $client;

    public function setUp()
    {
        parent::setUp();

        $client = new Client();

        // You have to specify authentication and a board id here to run full suite

        $this->boardId = '547440ad3f8b882bc11f0497';

        $this->client = $client;
    }
}


text:
require 'i18n'
require 'capybara/dsl'

module Formulaic
  module Inputs
    class Input
      include Capybara::DSL

      def initialize(label, value)
        @label = label.to_str
        @value = value
      end

      private

      attr_accessor :label, :value
    end
  end
end


text:
//
//  ViewController.m
//  ACPButtons
//
//  Created by Antonio Casero Palmero on 7/14/13.
//  Copyright (c) 2013 ACP. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];

    //We set up different buttons

    /*--------------------------------------------------------------------------
        Custom buttons with gradients
     --------------------------------------------------------------------------*/

    [_testButtonNoImage1 setStyleType:ACPButtonOK];
    [_testButtonNoImage1 setLabelTextColor:[UIColor whiteColor] highlightedColor:[UIColor whiteColor] disableColor:nil];
    [_testButtonNoImage1 setLabelFont:[UIFont fontWithName:@"Trebuchet MS" size:20]];

    [_testButtonNoImage2 setStyleType:ACPButtonCancel];
    [_testButtonNoImage2 setCornerRadius:10];

    [_testButtonNoImage3 setStyle:[UIColor yellowColor]  andBottomColor:[UIColor orangeColor]];
    [_testButtonNoImage3 setLabelTextColor:[UIColor orangeColor] highlightedColor:[UIColor redColor] disableColor:nil];
    [_testButtonNoImage3 setCornerRadius:20];
    [_testButtonNoImage3 setBorderStyle:[UIColor orangeColor] andInnerColor:nil];
//    [_testButtonNoImage3 setGlowHighlightedState:YES];

     /*--------------------------------------------------------------------------
        Custom Flat buttons
      --------------------------------------------------------------------------*/
    [_testButtonNoImage4 setFlatStyleType:ACPButtonGrey];
    [_testButtonNoImage5 setFlatStyleType:ACPButtonDarkGrey];
    [_testButtonNoImage5 setBorderStyle:[UIColor blackColor] andInnerColor:[UIColor darkGrayColor]];
    [_testButtonNoImage5 setLabelFont:[UIFont fontWithName:@"Trebuchet MS" size:20]];

     /*--------------------------------------------------------------------------
        Image resize buttons
      --------------------------------------------------------------------------*/
    [_testButtonWithImage1 setStyleWithImage:@"cont-bt_normal.png" highlightedImage:@"cont-bt_normal.png" disableImage:nil andInsets:UIEdgeInsetsMake(19, 7, 19, 7)];
    [_testButtonWithImage1 setLabelTextShadow:CGSizeMake(-1, -1) normalColor:[UIColor blackColor] highlightedColor:nil disableColor:nil];
    [_testButtonWithImage1 setLabelFont:[UIFont fontWithName:@"Helvetica-BoldOblique" size:20]];
    [_testButtonWithImage1 setGlowHighlightedState:YES];

    [_testButtonWithImage2 setStyleWithImage:@"alert-gray-button.png" highlightedImage:nil disableImage:nil andInsets:UIEdgeInsetsMake(19, 7, 19, 7)];
    [_testButtonWithImage2 setGlowHighlightedState:YES];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
<?php
/**
 * Created by PhpStorm.
 * User: loick
 * Date: 05/01/15
 * Time: 21:35
 */

namespace app\controllers;

use SwagFramework\mvc\Controller;

class ErrorsController extends Controller
{
    public function err404()
    {
        $this->getView()->render('errors/err404');
    }
}


text:
package com.ctrip.framework.apollo.openapi.service;

import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.openapi.entity.Consumer;
import com.ctrip.framework.apollo.openapi.entity.ConsumerAudit;
import com.ctrip.framework.apollo.openapi.entity.ConsumerRole;
import com.ctrip.framework.apollo.openapi.entity.ConsumerToken;
import com.ctrip.framework.apollo.openapi.repository.ConsumerAuditRepository;
import com.ctrip.framework.apollo.openapi.repository.ConsumerRepository;
import com.ctrip.framework.apollo.openapi.repository.ConsumerRoleRepository;
import com.ctrip.framework.apollo.openapi.repository.ConsumerTokenRepository;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.po.Role;
import com.ctrip.framework.apollo.portal.repository.RoleRepository;
import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.UserService;
import com.ctrip.framework.apollo.portal.util.RoleUtils;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.hash.Hashing;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author Jason Song(song_s@ctrip.com)
 */
@Service
public class ConsumerService {

  private static final FastDateFormat TIMESTAMP_FORMAT = FastDateFormat.getInstance("yyyyMMddHHmmss");
  private static final Joiner KEY_JOINER = Joiner.on("|");

  private final UserInfoHolder userInfoHolder;
  private final ConsumerTokenRepository consumerTokenRepository;
  private final ConsumerRepository consumerRepository;
  private final ConsumerAuditRepository consumerAuditRepository;
  private final ConsumerRoleRepository consumerRoleRepository;
  private final PortalConfig portalConfig;
  private final RolePermissionService rolePermissionService;
  private final UserService userService;
  private final RoleRepository roleRepository;

  public ConsumerService(
      final UserInfoHolder userInfoHolder,
      final ConsumerTokenRepository consumerTokenRepository,
      final ConsumerRepository consumerRepository,
      final ConsumerAuditRepository consumerAuditRepository,
      final ConsumerRoleRepository consumerRoleRepository,
      final PortalConfig portalConfig,
      final RolePermissionService rolePermissionService,
      final UserService userService,
      final RoleRepository roleRepository) {
    this.userInfoHolder = userInfoHolder;
    this.consumerTokenRepository = consumerTokenRepository;
    this.consumerRepository = consumerRepository;
    this.consumerAuditRepository = consumerAuditRepository;
    this.consumerRoleRepository = consumerRoleRepository;
    this.portalConfig = portalConfig;
    this.rolePermissionService = rolePermissionService;
    this.userService = userService;
    this.roleRepository = roleRepository;
  }

  public Consumer createConsumer(Consumer consumer) {
    String appId = consumer.getAppId();

    Consumer managedConsumer = consumerRepository.findByAppId(appId);
    if (managedConsumer != null) {
      throw new BadRequestException("Consumer already exist");
    }

    String ownerName = consumer.getOwnerName();
    UserInfo owner = userService.findByUserId(ownerName);
    if (owner == null) {
      throw new BadRequestException(String.format("User does not exist. UserId = %s", ownerName));
    }
    consumer.setOwnerEmail(owner.getEmail());

    String operator = userInfoHolder.getUser().getUserId();
    consumer.setDataChangeCreatedBy(operator);
    consumer.setDataChangeLastModifiedBy(operator);

    return consumerRepository.save(consumer);
  }

  public ConsumerToken generateAndSaveConsumerToken(Consumer consumer, Date expires) {
    Preconditions.checkArgument(consumer != null, "Consumer can not be null");

    ConsumerToken consumerToken = generateConsumerToken(consumer, expires);
    consumerToken.setId(0);

    return consumerTokenRepository.save(consumerToken);
  }

  public ConsumerToken getConsumerTokenByAppId(String appId) {
    Consumer consumer = consumerRepository.findByAppId(appId);
    if (consumer == null) {
      return null;
    }

    return consumerTokenRepository.findByConsumerId(consumer.getId());
  }

  public Long getConsumerIdByToken(String token) {
    if (Strings.isNullOrEmpty(token)) {
      return null;
    }
    ConsumerToken consumerToken = consumerTokenRepository.findTopByTokenAndExpiresAfter(token,
                                                                                new Date());
    return consumerToken == null ? null : consumerToken.getConsumerId();
  }

  public Consumer getConsumerByConsumerId(long consumerId) {
    return consumerRepository.findById(consumerId).orElse(null);
  }

  public List<ConsumerRole> assignNamespaceRoleToConsumer(String token, String appId, String namespaceName) {
    return assignNamespaceRoleToConsumer(token, appId, namespaceName, null);
  }

  @Transactional
  public List<ConsumerRole> assignNamespaceRoleToConsumer(String token, String appId, String namespaceName, String env) {
    Long consumerId = getConsumerIdByToken(token);
    if (consumerId == null) {
      throw new BadRequestException("Token is Illegal");
    }

    Role namespaceModifyRole =
        rolePermissionService.findRoleByRoleName(RoleUtils.buildModifyNamespaceRoleName(appId, namespaceName, env));
    Role namespaceReleaseRole =
        rolePermissionService.findRoleByRoleName(RoleUtils.buildReleaseNamespaceRoleName(appId, namespaceName, env));

    if (namespaceModifyRole == null || namespaceReleaseRole == null) {
      throw new BadRequestException("Namespace's role does not exist. Please check whether namespace has created.");
    }

    long namespaceModifyRoleId = namespaceModifyRole.getId();
    long namespaceReleaseRoleId = namespaceReleaseRole.getId();

    ConsumerRole managedModifyRole = consumerRoleRepository.findByConsumerIdAndRoleId(consumerId, namespaceModifyRoleId);
    ConsumerRole managedReleaseRole = consumerRoleRepository.findByConsumerIdAndRoleId(consumerId, namespaceReleaseRoleId);
    if (managedModifyRole != null && managedReleaseRole != null) {
      return Arrays.asList(managedModifyRole, managedReleaseRole);
    }

    String operator = userInfoHolder.getUser().getUserId();

    ConsumerRole namespaceModifyConsumerRole = createConsumerRole(consumerId, namespaceModifyRoleId, operator);
    ConsumerRole namespaceReleaseConsumerRole = createConsumerRole(consumerId, namespaceReleaseRoleId, operator);

    ConsumerRole createdModifyConsumerRole = consumerRoleRepository.save(namespaceModifyConsumerRole);
    ConsumerRole createdReleaseConsumerRole = consumerRoleRepository.save(namespaceReleaseConsumerRole);

    return Arrays.asList(createdModifyConsumerRole, createdReleaseConsumerRole);
  }

  @Transactional
  public ConsumerRole assignAppRoleToConsumer(String token, String appId) {
    Long consumerId = getConsumerIdByToken(token);
    if (consumerId == null) {
      throw new BadRequestException("Token is Illegal");
    }

    Role masterRole = rolePermissionService.findRoleByRoleName(RoleUtils.buildAppMasterRoleName(appId));
    if (masterRole == null) {
      throw new BadRequestException("App's role does not exist. Please check whether app has created.");
    }

    long roleId = masterRole.getId();
    ConsumerRole managedModifyRole = consumerRoleRepository.findByConsumerIdAndRoleId(consumerId, roleId);
    if (managedModifyRole != null) {
      return managedModifyRole;
    }

    String operator = userInfoHolder.getUser().getUserId();
    ConsumerRole consumerRole = createConsumerRole(consumerId, roleId, operator);
    return consumerRoleRepository.save(consumerRole);
  }

  @Transactional
  public void createConsumerAudits(Iterable<ConsumerAudit> consumerAudits) {
    consumerAuditRepository.saveAll(consumerAudits);
  }

  @Transactional
  public ConsumerToken createConsumerToken(ConsumerToken entity) {
    entity.setId(0); //for protection

    return consumerTokenRepository.save(entity);
  }

  private ConsumerToken generateConsumerToken(Consumer consumer, Date expires) {
    long consumerId = consumer.getId();
    String createdBy = userInfoHolder.getUser().getUserId();
    Date createdTime = new Date();

    ConsumerToken consumerToken = new ConsumerToken();
    consumerToken.setConsumerId(consumerId);
    consumerToken.setExpires(expires);
    consumerToken.setDataChangeCreatedBy(createdBy);
    consumerToken.setDataChangeCreatedTime(createdTime);
    consumerToken.setDataChangeLastModifiedBy(createdBy);
    consumerToken.setDataChangeLastModifiedTime(createdTime);

    generateAndEnrichToken(consumer, consumerToken);

    return consumerToken;
  }

  void generateAndEnrichToken(Consumer consumer, ConsumerToken consumerToken) {

    Preconditions.checkArgument(consumer != null);

    if (consumerToken.getDataChangeCreatedTime() == null) {
      consumerToken.setDataChangeCreatedTime(new Date());
    }
    consumerToken.setToken(generateToken(consumer.getAppId(), consumerToken
        .getDataChangeCreatedTime(), portalConfig.consumerTokenSalt()));
  }

  String generateToken(String consumerAppId, Date generationTime, String
      consumerTokenSalt) {
    return Hashing.sha1().hashString(KEY_JOINER.join(consumerAppId, TIMESTAMP_FORMAT.format
        (generationTime), consumerTokenSalt), Charsets.UTF_8).toString();
  }

    ConsumerRole createConsumerRole(Long consumerId, Long roleId, String operator) {
    ConsumerRole consumerRole = new ConsumerRole();

    consumerRole.setConsumerId(consumerId);
    consumerRole.setRoleId(roleId);
    consumerRole.setDataChangeCreatedBy(operator);
    consumerRole.setDataChangeLastModifiedBy(operator);

    return consumerRole;
  }

  public Set<String> findAppIdsAuthorizedByConsumerId(long consumerId) {
    List<ConsumerRole> consumerRoles = this.findConsumerRolesByConsumerId(consumerId);
    List<Long> roleIds = consumerRoles.stream().map(ConsumerRole::getRoleId)
        .collect(Collectors.toList());

    return this.findAppIdsByRoleIds(roleIds);
  }

  private List<ConsumerRole> findConsumerRolesByConsumerId(long consumerId) {
    return this.consumerRoleRepository.findByConsumerId(consumerId);
  }

  private Set<String> findAppIdsByRoleIds(List<Long> roleIds) {
    Iterable<Role> roleIterable = this.roleRepository.findAllById(roleIds);

    Set<String> appIds = new HashSet<>();

    roleIterable.forEach(role -> {
      if (!role.isDeleted()) {
        String roleName = role.getRoleName();
        String appId = RoleUtils.extractAppIdFromRoleName(roleName);
        appIds.add(appId);
      }
    });

    return appIds;
  }
}


text:
> `npm install --save @types/sinon`

# Summary
This package contains type definitions for Sinon (http://sinonjs.org/).

# Details
Files were exported from https://www.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/sinon

Additional Details
 * Last updated: Mon, 20 Mar 2017 21:34:19 GMT
 * Dependencies: none
 * Global values: sinon

# Credits
These definitions were written by William Sears <https://github.com/mrbigdog2u>.


text:
package org.json4s
package native

import text.Document
import text.Document._
import io.Source

trait JsonMethods extends org.json4s.JsonMethods[Document] {

  def parse(in: JsonInput, useBigDecimalForDouble: Boolean = false, useBigIntForLong: Boolean = true): JValue = in match {
    case StringInput(s) => JsonParser.parse(s, useBigDecimalForDouble)
    case ReaderInput(rdr) => JsonParser.parse(rdr, useBigDecimalForDouble)
    case StreamInput(stream) => JsonParser.parse(Source.fromInputStream(stream).bufferedReader(), useBigDecimalForDouble)
    case FileInput(file) => JsonParser.parse(Source.fromFile(file).bufferedReader(), useBigDecimalForDouble)
  }

  def parseOpt(in: JsonInput, useBigDecimalForDouble: Boolean = false, useBigIntForLong: Boolean = true): Option[JValue] = in match {
    case StringInput(s) => JsonParser.parseOpt(s, useBigDecimalForDouble)
    case ReaderInput(rdr) => JsonParser.parseOpt(rdr, useBigDecimalForDouble)
    case StreamInput(stream) => JsonParser.parseOpt(Source.fromInputStream(stream).bufferedReader(), useBigDecimalForDouble)
    case FileInput(file) => JsonParser.parseOpt(Source.fromFile(file).bufferedReader(), useBigDecimalForDouble)
  }

  /** Renders JSON.
   * @see Printer#compact
   * @see Printer#pretty
   */
  def render(value: JValue)(implicit formats: Formats = DefaultFormats): Document =
    formats.emptyValueStrategy.replaceEmpty(value) match {
      case null          => text("null")
      case JBool(true)   => text("true")
      case JBool(false)  => text("false")
      case JDouble(n)    => text(n.toString)
      case JDecimal(n)   => text(n.toString)
      case JLong(n)      => text(n.toString)
      case JInt(n)       => text(n.toString)
      case JNull         => text("null")
      case JNothing      => sys.error("can't render 'nothing'")
      case JString(null) => text("null")
      case JString(s)    => text("\""+ParserUtil.quote(s)+"\"")
      case JArray(arr)   => text("[") :: series(trimArr(arr).map(render)) :: text("]")
      case JObject(obj)  =>
        val nested = break :: fields(trimObj(obj).map({case (n,v) => text("\""+ParserUtil.quote(n)+"\":") :: render(v)}))
        text("{") :: nest(2, nested) :: break :: text("}")
    }

  private def trimArr(xs: List[JValue]) = xs.filter(_ != JNothing)
  private def trimObj(xs: List[JField]) = xs.filter(_._2 != JNothing)
  private def series(docs: List[Document]) = punctuate(text(","), docs)
  private def fields(docs: List[Document]) = punctuate(text(",") :: break, docs)

  private def punctuate(p: Document, docs: List[Document]): Document =
    if (docs.isEmpty) empty
    else docs.reduceLeft((d1, d2) => d1 :: p :: d2)

  def compact(d: Document): String = Printer.compact(d)
  def pretty(d: Document): String = Printer.pretty(d)

}

object JsonMethods extends native.JsonMethods


text:
package v3

import (
	"fmt"

	. "github.com/cloudfoundry/cf-acceptance-tests/cats_suite_helpers"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
	"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
	. "github.com/cloudfoundry/cf-acceptance-tests/helpers/app_helpers"
	"github.com/cloudfoundry/cf-acceptance-tests/helpers/assets"
	"github.com/cloudfoundry/cf-acceptance-tests/helpers/random_name"
	"github.com/cloudfoundry/cf-acceptance-tests/helpers/skip_messages"
	. "github.com/cloudfoundry/cf-acceptance-tests/helpers/v3_helpers"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = V3Describe("v3 buildpack app lifecycle", func() {
	var (
		appName                         string
		appGuid                         string
		packageGuid                     string
		spaceGuid                       string
		appCreationEnvironmentVariables string
		token                           string
		uploadUrl                       string
		expectedNullResponse            string
	)

	BeforeEach(func() {
		appName = random_name.CATSRandomName("APP")
		spaceGuid = GetSpaceGuidFromName(TestSetup.RegularUserContext().Space)
		appCreationEnvironmentVariables = `"foo"=>"bar"`
		appGuid = CreateApp(appName, spaceGuid, `{"foo":"bar"}`)
		packageGuid = CreatePackage(appGuid)
		token = GetAuthToken()
		uploadUrl = fmt.Sprintf("%s%s/v3/packages/%s/upload", Config.Protocol(), Config.GetApiEndpoint(), packageGuid)

		appUrl := "https://" + appName + "." + Config.GetAppsDomain()
		nullSession := helpers.CurlSkipSSL(Config.GetSkipSSLValidation(), appUrl).Wait(Config.DefaultTimeoutDuration())
		expectedNullResponse = string(nullSession.Buffer().Contents())
	})

	AfterEach(func() {
		FetchRecentLogs(appGuid, token, Config)
		DeleteApp(appGuid)
	})

	Context("with a ruby_buildpack", func() {
		BeforeEach(func() {
			UploadPackage(uploadUrl, assets.NewAssets().DoraZip, token)
			WaitForPackageToBeReady(packageGuid)
		})

		It("can run apps with processes from the Procfile", func() {
			lastUsageEventGuid := LastAppUsageEventGuid(TestSetup)

			buildGuid := StageBuildpackPackage(packageGuid, Config.GetRubyBuildpackName())

			usageEvents := UsageEventsAfterGuid(TestSetup, lastUsageEventGuid)
			event := AppUsageEvent{Entity: Entity{State: "STAGING_STARTED", ParentAppGuid: appGuid, ParentAppName: appName}}
			Expect(UsageEventsInclude(usageEvents, event)).To(BeTrue())

			WaitForBuildToStage(buildGuid)

			usageEvents = UsageEventsAfterGuid(TestSetup, lastUsageEventGuid)
			event = AppUsageEvent{Entity: Entity{State: "STAGING_STOPPED", ParentAppGuid: appGuid, ParentAppName: appName}}
			Expect(UsageEventsInclude(usageEvents, event)).To(BeTrue())

			dropletGuid := GetDropletFromBuild(buildGuid)

			AssignDropletToApp(appGuid, dropletGuid)

			processes := GetProcesses(appGuid, appName)
			webProcess := GetProcessByType(processes, "web")
			workerProcess := GetProcessByType(processes, "worker")

			Expect(webProcess.Guid).ToNot(BeEmpty())
			Expect(workerProcess.Guid).ToNot(BeEmpty())

			CreateAndMapRoute(appGuid, TestSetup.RegularUserContext().Space, Config.GetAppsDomain(), webProcess.Name)

			lastUsageEventGuid = LastAppUsageEventGuid(TestSetup)

			StartApp(appGuid)

			Eventually(func() string {
				return helpers.CurlAppRoot(Config, webProcess.Name)
			}, Config.CfPushTimeoutDuration()).Should(ContainSubstring("Hi, I'm Dora!"))

			output := helpers.CurlApp(Config, webProcess.Name, "/env")
			Expect(output).To(ContainSubstring(fmt.Sprintf("application_name\\\":\\\"%s", appName)))
			Expect(output).To(ContainSubstring(appCreationEnvironmentVariables))

			Expect(string(cf.Cf("apps").Wait(Config.DefaultTimeoutDuration()).Out.Contents())).To(MatchRegexp(fmt.Sprintf("(v3-)?(%s)*(-web)?(\\s)+(started)", webProcess.Name)))
			Expect(string(cf.Cf("apps").Wait(Config.DefaultTimeoutDuration()).Out.Contents())).To(MatchRegexp(fmt.Sprintf("(v3-)?(%s)*(-web)?(\\s)+(started)", workerProcess.Name)))

			usageEvents = UsageEventsAfterGuid(TestSetup, lastUsageEventGuid)

			event1 := AppUsageEvent{Entity: Entity{ProcessType: webProcess.Type, AppGuid: webProcess.Guid, State: "STARTED", ParentAppGuid: appGuid, ParentAppName: appName}}
			event2 := AppUsageEvent{Entity: Entity{ProcessType: workerProcess.Type, AppGuid: workerProcess.Guid, State: "STARTED", ParentAppGuid: appGuid, ParentAppName: appName}}
			Expect(UsageEventsInclude(usageEvents, event1)).To(BeTrue())
			Expect(UsageEventsInclude(usageEvents, event2)).To(BeTrue())

			StopApp(appGuid)

			Expect(string(cf.Cf("apps").Wait(Config.DefaultTimeoutDuration()).Out.Contents())).To(MatchRegexp(fmt.Sprintf("(v3-)?(%s)*(-web)?(\\s)+(stopped)", webProcess.Name)))
			Expect(string(cf.Cf("apps").Wait(Config.DefaultTimeoutDuration()).Out.Contents())).To(MatchRegexp(fmt.Sprintf("(v3-)?(%s)*(-web)?(\\s)+(stopped)", workerProcess.Name)))

			usageEvents = UsageEventsAfterGuid(TestSetup, lastUsageEventGuid)
			event1 = AppUsageEvent{Entity: Entity{ProcessType: webProcess.Type, AppGuid: webProcess.Guid, State: "STOPPED", ParentAppGuid: appGuid, ParentAppName: appName}}
			event2 = AppUsageEvent{Entity: Entity{ProcessType: workerProcess.Type, AppGuid: workerProcess.Guid, State: "STOPPED", ParentAppGuid: appGuid, ParentAppName: appName}}
			Expect(UsageEventsInclude(usageEvents, event1)).To(BeTrue())
			Expect(UsageEventsInclude(usageEvents, event2)).To(BeTrue())

			Eventually(func() string {
				return helpers.CurlAppRoot(Config, webProcess.Name)
			}, Config.DefaultTimeoutDuration()).Should(ContainSubstring(expectedNullResponse))
		})
	})

	Context("with a java_buildpack", func() {
		BeforeEach(func() {
			UploadPackage(uploadUrl, assets.NewAssets().JavaSpringZip, token)
			WaitForPackageToBeReady(packageGuid)
		})

		It("can run spring apps", func() {
			buildGuid := StageBuildpackPackage(packageGuid, Config.GetJavaBuildpackName())
			WaitForBuildToStage(buildGuid)
			dropletGuid := GetDropletFromBuild(buildGuid)

			AssignDropletToApp(appGuid, dropletGuid)

			processes := GetProcesses(appGuid, appName)
			webProcess := GetProcessByType(processes, "web")

			Expect(webProcess.Guid).ToNot(BeEmpty())
			ScaleProcess(appGuid, webProcess.Type, V3_JAVA_MEMORY_LIMIT)

			CreateAndMapRoute(appGuid, TestSetup.RegularUserContext().Space, Config.GetAppsDomain(), webProcess.Name)

			lastUsageEventGuid := LastAppUsageEventGuid(TestSetup)
			StartApp(appGuid)

			Eventually(func() string {
				return helpers.CurlAppRoot(Config, webProcess.Name)
			}, Config.DefaultTimeoutDuration()).Should(ContainSubstring("ok"))

			Expect(string(cf.Cf("apps").Wait(Config.DefaultTimeoutDuration()).Out.Contents())).To(MatchRegexp(fmt.Sprintf("(v3-)?(%s)*(-web)?(\\s)+(started)", webProcess.Name)))

			usageEvents := UsageEventsAfterGuid(TestSetup, lastUsageEventGuid)

			event1 := AppUsageEvent{Entity: Entity{ProcessType: webProcess.Type, AppGuid: webProcess.Guid, State: "STARTED", ParentAppGuid: appGuid, ParentAppName: appName}}
			Expect(UsageEventsInclude(usageEvents, event1)).To(BeTrue())

			StopApp(appGuid)

			Expect(string(cf.Cf("apps").Wait(Config.DefaultTimeoutDuration()).Out.Contents())).To(MatchRegexp(fmt.Sprintf("(v3-)?(%s)*(-web)?(\\s)+(stopped)", webProcess.Name)))

			usageEvents = UsageEventsAfterGuid(TestSetup, lastUsageEventGuid)
			event1 = AppUsageEvent{Entity: Entity{ProcessType: webProcess.Type, AppGuid: webProcess.Guid, State: "STOPPED", ParentAppGuid: appGuid, ParentAppName: appName}}
			Expect(UsageEventsInclude(usageEvents, event1)).To(BeTrue())

			Eventually(func() string {
				return helpers.CurlAppRoot(Config, webProcess.Name)
			}, Config.DefaultTimeoutDuration()).Should(ContainSubstring(expectedNullResponse))
		})
	})
})

var _ = V3Describe("v3 docker app lifecycle", func() {
	var (
		appName                         string
		appGuid                         string
		packageGuid                     string
		spaceGuid                       string
		appCreationEnvironmentVariables string
		token                           string
		expectedNullResponse            string
	)

	BeforeEach(func() {
		if !Config.GetIncludeDocker() {
			Skip(skip_messages.SkipDockerMessage)
		}
		appName = random_name.CATSRandomName("APP")
		spaceGuid = GetSpaceGuidFromName(TestSetup.RegularUserContext().Space)
		appCreationEnvironmentVariables = `"foo":"bar"`
		appGuid = CreateDockerApp(appName, spaceGuid, `{"foo":"bar"}`)
		packageGuid = CreateDockerPackage(appGuid, "cloudfoundry/diego-docker-app:latest")
		token = GetAuthToken()

		appUrl := "https://" + appName + "." + Config.GetAppsDomain()
		nullSession := helpers.CurlSkipSSL(Config.GetSkipSSLValidation(), appUrl).Wait(Config.DefaultTimeoutDuration())
		expectedNullResponse = string(nullSession.Buffer().Contents())
	})

	AfterEach(func() {
		FetchRecentLogs(appGuid, token, Config)
		DeleteApp(appGuid)
	})

	It("can run apps", func() {
		buildGuid := StageDockerPackage(packageGuid)
		WaitForBuildToStage(buildGuid)
		dropletGuid := GetDropletFromBuild(buildGuid)

		AssignDropletToApp(appGuid, dropletGuid)

		processes := GetProcesses(appGuid, appName)
		webProcess := GetProcessByType(processes, "web")

		Expect(webProcess.Guid).ToNot(BeEmpty())

		CreateAndMapRoute(appGuid, TestSetup.RegularUserContext().Space, Config.GetAppsDomain(), webProcess.Name)

		lastUsageEventGuid := LastAppUsageEventGuid(TestSetup)
		StartApp(appGuid)

		Eventually(func() string {
			return helpers.CurlAppRoot(Config, webProcess.Name)
		}, Config.DefaultTimeoutDuration()).Should(Equal("0"))

		output := helpers.CurlApp(Config, webProcess.Name, "/env")
		Expect(output).To(ContainSubstring(fmt.Sprintf("application_name\\\":\\\"%s", appName)))
		Expect(output).To(ContainSubstring(appCreationEnvironmentVariables))

		Expect(string(cf.Cf("apps").Wait(Config.DefaultTimeoutDuration()).Out.Contents())).To(MatchRegexp(fmt.Sprintf("(v3-)?(%s)*(-web)?(\\s)+(started)", webProcess.Name)))
		usageEvents := UsageEventsAfterGuid(TestSetup, lastUsageEventGuid)

		event := AppUsageEvent{Entity: Entity{ProcessType: webProcess.Type, AppGuid: webProcess.Guid, State: "STARTED", ParentAppGuid: appGuid, ParentAppName: appName}}
		Expect(UsageEventsInclude(usageEvents, event)).To(BeTrue())

		StopApp(appGuid)

		Expect(string(cf.Cf("apps").Wait(Config.DefaultTimeoutDuration()).Out.Contents())).To(MatchRegexp(fmt.Sprintf("(v3-)?(%s)*(-web)?(\\s)+(stopped)", webProcess.Name)))

		usageEvents = UsageEventsAfterGuid(TestSetup, lastUsageEventGuid)
		event = AppUsageEvent{Entity: Entity{ProcessType: webProcess.Type, AppGuid: webProcess.Guid, State: "STOPPED", ParentAppGuid: appGuid, ParentAppName: appName}}
		Expect(UsageEventsInclude(usageEvents, event)).To(BeTrue())

		Eventually(func() string {
			return helpers.CurlAppRoot(Config, webProcess.Name)
		}, Config.DefaultTimeoutDuration()).Should(ContainSubstring(expectedNullResponse))
	})
})


text:
div.network-navigation {
    width:34px;
    height:34px;
    -moz-border-radius: 17px;
    border-radius: 17px;
    position:absolute;
    display:inline-block;
    background-position: 2px 2px;
    background-repeat:no-repeat;
    cursor: pointer;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

div.network-navigation:hover {
    box-shadow: 0px 0px 3px 3px rgba(56, 207, 21, 0.30);
}

div.network-navigation:active {
    box-shadow: 0px 0px 1px 3px rgba(56, 207, 21, 0.95);
}

div.network-navigation.up {
    background-image: url("img/network/upArrow.png");
    bottom:50px;
    left:55px;
}
div.network-navigation.down {
    background-image: url("img/network/downArrow.png");
    bottom:10px;
    left:55px;
}
div.network-navigation.left {
    background-image: url("img/network/leftArrow.png");
    bottom:10px;
    left:15px;
}
div.network-navigation.right {
    background-image: url("img/network/rightArrow.png");
    bottom:10px;
    left:95px;
}
div.network-navigation.zoomIn {
    background-image: url("img/network/plus.png");
    bottom:10px;
    right:15px;
}
div.network-navigation.zoomOut {
    background-image: url("img/network/minus.png");
    bottom:10px;
    right:55px;
}
div.network-navigation.zoomExtends {
    background-image: url("img/network/zoomExtends.png");
    bottom:50px;
    right:15px;
}


text:
from enum import Enum

from pypika.functions import *
from pypika.terms import Arithmetic, ArithmeticExpression, CustomFunction, Function

import frappe
from frappe.query_builder.custom import GROUP_CONCAT, MATCH, STRING_AGG, TO_TSVECTOR
from frappe.query_builder.utils import ImportMapper, db_type_is

from .utils import PseudoColumn

class Concat_ws(Function):
	def __init__(self, *terms, **kwargs):
		super().__init__("CONCAT_WS", *terms, **kwargs)

class Locate(Function):
	def __init__(self, *terms, **kwargs):
		super().__init__("LOCATE", *terms, **kwargs)

class Timestamp(Function):
	def __init__(self, term: str, time=None, alias=None):
		if time:
			super().__init__("TIMESTAMP", term, time, alias=alias)
		else:
			super().__init__("TIMESTAMP", term, alias=alias)

GroupConcat = ImportMapper({db_type_is.MARIADB: GROUP_CONCAT, db_type_is.POSTGRES: STRING_AGG})

Match = ImportMapper({db_type_is.MARIADB: MATCH, db_type_is.POSTGRES: TO_TSVECTOR})

class _PostgresTimestamp(ArithmeticExpression):
	def __init__(self, datepart, timepart, alias=None):
		if isinstance(datepart, str):
			datepart = Cast(datepart, "date")
		if isinstance(timepart, str):
			timepart = Cast(timepart, "time")

		super().__init__(operator=Arithmetic.add, left=datepart, right=timepart, alias=alias)

CombineDatetime = ImportMapper(
	{
		db_type_is.MARIADB: CustomFunction("TIMESTAMP", ["date", "time"]),
		db_type_is.POSTGRES: _PostgresTimestamp,
	}
)

DateFormat = ImportMapper(
	{
		db_type_is.MARIADB: CustomFunction("DATE_FORMAT", ["date", "format"]),
		db_type_is.POSTGRES: ToChar,
	}
)

class Cast_(Function):
	def __init__(self, value, as_type, alias=None):
		if frappe.db.db_type == "mariadb" and (
			(hasattr(as_type, "get_sql") and as_type.get_sql().lower() == "varchar")
			or str(as_type).lower() == "varchar"
		):
			# mimics varchar cast in mariadb
			# as mariadb doesn't have varchar data cast
			# https://mariadb.com/kb/en/cast/#description

			# ref: https://stackoverflow.com/a/32542095
			super().__init__("CONCAT", value, "", alias=alias)
		else:
			# from source: https://pypika.readthedocs.io/en/latest/_modules/pypika/functions.html#Cast
			super().__init__("CAST", value, alias=alias)
			self.as_type = as_type

	def get_special_params_sql(self, **kwargs):
		if self.name.lower() == "cast":
			type_sql = (
				self.as_type.get_sql(**kwargs)
				if hasattr(self.as_type, "get_sql")
				else str(self.as_type).upper()
			)
			return f"AS {type_sql}"

def _aggregate(function, dt, fieldname, filters, **kwargs):
	return (
		frappe.qb.engine.build_conditions(dt, filters)
		.select(function(PseudoColumn(fieldname)))
		.run(**kwargs)[0][0]
		or 0
	)

class SqlFunctions(Enum):
	DayOfYear = "dayofyear"
	Extract = "extract"
	Locate = "locate"
	Count = "count"
	Sum = "sum"
	Avg = "avg"
	Max = "max"
	Min = "min"
	Abs = "abs"
	Timestamp = "timestamp"

def _max(dt, fieldname, filters=None, **kwargs):
	return _aggregate(Max, dt, fieldname, filters, **kwargs)

def _min(dt, fieldname, filters=None, **kwargs):
	return _aggregate(Min, dt, fieldname, filters, **kwargs)

def _avg(dt, fieldname, filters=None, **kwargs):
	return _aggregate(Avg, dt, fieldname, filters, **kwargs)

def _sum(dt, fieldname, filters=None, **kwargs):
	return _aggregate(Sum, dt, fieldname, filters, **kwargs)


text:
local FastACDC_grouped, parent = torch.class('acdc.FastACDC_grouped', 'nn.Module')

function FastACDC_grouped:__init(dim, groupSize, opt)
  parent.__init(self)
  local opt = opt or {}

  if opt then
    if opt.use_bias ~= nil then
      self.use_bias = opt.use_bias
    else
      self.use_bias = true
    end
    self.sign_init = opt.sign_init or false
    self.rand_init = opt.rand_init or false
  else
    self.use_bias = true
    self.sign_init = false
    self.rand_init = false
  end

  assert(dim % 2 == 0, "Input size must be even.  Odd sizes are not supported.")

  self.dim = dim
  self.groupSize = groupSize
  self.A = torch.Tensor(dim*groupSize)
  self.Ab = torch.Tensor(dim*groupSize)
  self.D = torch.Tensor(dim*groupSize)
  self.Db = torch.Tensor(dim*groupSize)

  self.gradA = torch.Tensor(dim*groupSize)
  self.gradAb = torch.Tensor(dim*groupSize)
  self.gradD = torch.Tensor(dim*groupSize)
  self.gradDb = torch.Tensor(dim*groupSize)

  self.tmp1 = torch.Tensor()
  self.tmp2 = torch.Tensor()
  self.delta_mid = torch.Tensor()
  self.activationsD = torch.Tensor()

  self:reset()
end

function FastACDC_grouped:reset()
  if self.sign_init then
    self.A:uniform(-1, 1)
    self.A:copy(self.A:gt(0):float():add(-1, self.A:le(0):float()))

    self.D:uniform(-1, 1)
    self.D:copy(self.D:gt(0):float():add(-1, self.D:le(0):float()))
  else
    self.A:fill(2)
    self.D:fill(0.7)
  end

  if self.rand_init then
    self.A:add(self.A:clone():uniform(-0.01, 0.01))
    self.D:add(self.D:clone():uniform(-0.01, 0.01))
  end

  self.Ab:fill(0.1)
  self.Db:fill(0.2)

  self.gradA:fill(0)
  self.gradAb:fill(0)
  self.gradD:fill(0)
  self.gradDb:fill(0)
end

function FastACDC_grouped:updateOutput(input)
  assert(input:size(input:nDimension()) == self.dim,
    "Incorrect input size.  Expected " .. self.dim .. ", got " ..
    input:size(input:nDimension()))

  input = input:contiguous()
  self.output = self.output:resize(input:size(1), self.groupSize, input:size(3)):zero():contiguous()

  self.tmp1 = self.tmp1:resize(2 * self.output:nElement()):zero()
  self.tmp2 = self.tmp2:resize(2 * self.output:nElement()):zero()
  self.delta_mid = self.delta_mid:resize(self.output:nElement()):zero()

  input.nn.Fast_ACDC_updateOutput(self, input)

  return self.output
end

function FastACDC_grouped:updateGradInput(input, gradOutput)
  input = input:contiguous()
  gradOutput = gradOutput:contiguous()
  self.gradInput = self.gradInput:resizeAs(gradOutput):contiguous():zero()

  input.nn.Fast_ACDC_updateGradInput(self, input, gradOutput)

  return self.gradInput
end

function FastACDC_grouped:accGradParameters(input, gradOutput, scale)
  scale = scale or 1
  assert(scale == 1, "scale != 1 is not implemented")

  local input = input:contiguous()
  local gradOutput = gradOutput:contiguous()

  self.activationsD = self.activationsD:resizeAs(gradOutput):zero()

  input.nn.Fast_ACDC_accGradParams(self, input, gradOutput)

  if not self.use_bias then
    self.gradAb:zero()
    self.gradDb:zero()
  end
end

function FastACDC_grouped:parameters()
  local params = {
    self.A,
    self.Ab,
    self.D,
    self.Db,
  }
  local grads = {
    self.gradA,
    self.gradAb,
    self.gradD,
    self.gradDb,
  }
  return params, grads
end

function FastACDC_grouped:print_parameters()
   print(self.A)
   print(self.Ab)
   print(self.D)
   print(self.Db)
end

function FastACDC_grouped:print_grads()
   print(self.gradA)
   print(self.gradAb)
   print(self.gradD)
   print(self.gradDb)
end

FastACDC_grouped.sharedAccUpdateGradParameters = FastACDC_grouped.accUpdateGradParameters


text:
import sbt.Keys._
import sbt._
import BuildGearpump._
import BuildDashboard.services
import BuildExperiments.{cgroup, storm, yarn, akkastream}
import xerial.sbt.Pack._

object Pack extends sbt.Build {
  val daemonClassPath = Seq(
    "${PROG_HOME}/conf",
    // This is for DFSJarStore
    "${PROG_HOME}/lib/yarn/*"
  )

  val applicationClassPath = Seq(
    // Current working directory
    ".",
    "${PROG_HOME}/conf"
  )

  val serviceClassPath = Seq(
    "${PROG_HOME}/conf",
    "${PROG_HOME}/lib/services/*",
    "${PROG_HOME}/dashboard"
  )

  val yarnClassPath = Seq(
    "${PROG_HOME}/conf",
    "${PROG_HOME}/lib/services/*",
    "${PROG_HOME}/lib/yarn/*",
    "${PROG_HOME}/conf/yarnconf",
    "/etc/hadoop/conf",
    "/etc/hbase/conf"
  )

  val stormClassPath = daemonClassPath ++ Seq(
    "${PROG_HOME}/lib/storm/*"
  )

  val akkaStreamsClassPath = daemonClassPath ++ Seq(
    "${PROG_HOME}/lib/akkastream/*"
  )

  lazy val packProject = Project(
    id = "gearpump-pack",
    base = file(s"$distDirectory"),
    settings = commonSettings ++ noPublish ++
      packSettings ++
      Seq(
        packMain := Map(
          "gear" -> "org.apache.gearpump.cluster.main.Gear",
          "local" -> "org.apache.gearpump.cluster.main.Local",
          "master" -> "org.apache.gearpump.cluster.main.Master",
          "worker" -> "org.apache.gearpump.cluster.main.Worker",
          "services" -> "org.apache.gearpump.services.main.Services",
          "yarnclient" -> "org.apache.gearpump.experiments.yarn.client.Client",
          "storm" -> "org.apache.gearpump.experiments.storm.StormRunner",
          "akkastream" -> "org.apache.gearpump.akkastream.example.Test"
        ),
        packJvmOpts := Map(
          "gear" -> Seq(
            "-Djava.net.preferIPv4Stack=true",
            "-Dgearpump.home=${PROG_HOME}"),

          "local" -> Seq(
            "-server",
            "-Djava.net.preferIPv4Stack=true",
            "-DlogFilename=local",
            "-Dgearpump.home=${PROG_HOME}",
            "-Djava.rmi.server.hostname=localhost"),

          "master" -> Seq(
            "-server",
            "-Djava.net.preferIPv4Stack=true",
            "-DlogFilename=master",
            "-Dgearpump.home=${PROG_HOME}",
            "-Djava.rmi.server.hostname=localhost"),

          "worker" -> Seq(
            "-server",
            "-Djava.net.preferIPv4Stack=true",
            "-DlogFilename=worker",
            "-Dgearpump.home=${PROG_HOME}",
            "-Djava.rmi.server.hostname=localhost"),

          "services" -> Seq(
            "-server",
            "-Djava.net.preferIPv4Stack=true",
            "-Dgearpump.home=${PROG_HOME}",
            "-Djava.rmi.server.hostname=localhost"),

          "yarnclient" -> Seq(
            "-server",
            "-Djava.net.preferIPv4Stack=true",
            "-Dgearpump.home=${PROG_HOME}",
            "-Djava.rmi.server.hostname=localhost"),

          "storm" -> Seq(
            "-server",
            "-Djava.net.preferIPv4Stack=true",
            "-Dgearpump.home=${PROG_HOME}"),

          "akkastream" -> Seq(
            "-server",
            "-noverify",
            "-Djava.net.preferIPv4Stack=true",
            "-Dgearpump.home=${PROG_HOME}")
        ),
        packLibDir := Map(
          "lib/yarn" -> new ProjectsToPack(gearpumpHadoop.id, yarn.id).
            exclude(services.id, core.id),
          "lib/services" -> new ProjectsToPack(services.id).exclude(core.id),
          // "lib/akkastream" -> new ProjectsToPack(akkastream.id),
          "lib/storm" -> new ProjectsToPack(storm.id).exclude(streaming.id)
        ),
        packExclude := Seq(thisProjectRef.value.project),

        packResourceDir += (baseDirectory.value / ".." / "bin" -> "bin"),
        packResourceDir += (baseDirectory.value / ".." / "conf" -> "conf"),
        packResourceDir += (baseDirectory.value / ".." / "yarnconf" -> "conf/yarnconf"),
        packResourceDir += (baseDirectory.value / ".." / "core" / "target" /
          CrossVersion.binaryScalaVersion(scalaVersion.value) -> "lib"),
        packResourceDir += (baseDirectory.value / ".." / "streaming" / "target" /
          CrossVersion.binaryScalaVersion(scalaVersion.value) -> "lib"),
        packResourceDir += (baseDirectory.value / ".." / "services" / "dashboard" -> "dashboard"),
        packResourceDir += (baseDirectory.value / ".." / "examples" / "target" /
          CrossVersion.binaryScalaVersion(scalaVersion.value) -> "examples"),
        packResourceDir += (baseDirectory.value / ".." / "integrationtest" / "target" /
          CrossVersion.binaryScalaVersion(scalaVersion.value) -> "integrationtest"),

        // The classpath should not be expanded. Otherwise, the classpath maybe too long.
        // On windows, it may report shell error "command line too long"
        packExpandedClasspath := false,
        packExtraClasspath := Map(
          "gear" -> applicationClassPath,
          "local" -> daemonClassPath,
          "master" -> daemonClassPath,
          "worker" -> applicationClassPath,
          "services" -> serviceClassPath,
          "yarnclient" -> yarnClassPath,
          "storm" -> stormClassPath,
          "akkastream" -> akkaStreamsClassPath
        ),

        packArchivePrefix := projectName + "-" + scalaBinaryVersion.value,
        packArchiveExcludes := Seq("integrationtest")

      )
  ).dependsOn(core,
    streaming,
    services,
    yarn,
    storm,
    // akkastream,
    cgroup).
    disablePlugins(sbtassembly.AssemblyPlugin)
}


text:
(function() {
  var XMLCData, XMLNode, create,
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  create = require('lodash/create');

  XMLNode = require('./XMLNode');

  module.exports = XMLCData = (function(superClass) {
    extend(XMLCData, superClass);

    function XMLCData(parent, text) {
      XMLCData.__super__.constructor.call(this, parent);
      if (text == null) {
        throw new Error("Missing CDATA text");
      }
      this.text = this.stringify.cdata(text);
    }

    XMLCData.prototype.clone = function() {
      return create(XMLCData.prototype, this);
    };

    XMLCData.prototype.toString = function(options, level) {
      var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
      pretty = (options != null ? options.pretty : void 0) || false;
      indent = (ref = options != null ? options.indent : void 0) != null ? ref : '  ';
      offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
      newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
      level || (level = 0);
      space = new Array(level + offset + 1).join(indent);
      r = '';
      if (pretty) {
        r += space;
      }
      r += '<![CDATA[' + this.text + ']]>';
      if (pretty) {
        r += newline;
      }
      return r;
    };

    return XMLCData;

  })(XMLNode);

}).call(this);


text:
package me.clementsauvage;

import me.clementsauvage.Clavier;
import me.clementsauvage.Color;
import me.clementsauvage.models.Item;
import me.clementsauvage.models.Game;

public class Main {

    public static void main(String[] args) {

        int numberOfPlayer;

        do {
            System.out.println(Color.BOLD.get() + "Combien de joueur à cette partie ?" + Color.RESET.get());
            numberOfPlayer = Clavier.lireInt();

            if(numberOfPlayer == 0) {
                System.out.println("T'as bouffé un clown ?");
            } else if(numberOfPlayer == 1) {
                System.out.println("Tu ne peux pas jouer tout seul, sociopathe !");
            } else if(numberOfPlayer > 2) {
                System.out.println(Color.RED.get() + "Pour l'instant mon super jeu ne peu se jouer qu'a max. 2 joueurs" + Color.RED.get());
            }

        } while (numberOfPlayer != 2);

        Game shifumi = new Game(numberOfPlayer);
        shifumi.start();

    }
}