text:
package com.animerom.filemanager.preferences;

/**
 * An enumeration of the search result sort modes.
 */
public enum FileTimeFormatMode implements ObjectStringIdentifier {

    /**
     * System-defined.
     */
    SYSTEM("0", null), //$NON-NLS-1$
    /**
     * Locale dependent
     */
    LOCALE("1", null), //$NON-NLS-1$
    /**
     * dd/MM/yyyy HH:mm:ss
     */
    DDMMYYYY_HHMMSS("2", "dd/MM/yyyy HH:mm:ss"), //$NON-NLS-1$ //$NON-NLS-2$
    /**
     * MM/dd/yyyy HH:mm:ss
     */
    MMDDYYYY_HHMMSS("3", "MM/dd/yyyy HH:mm:ss"), //$NON-NLS-1$ //$NON-NLS-2$
    /**
     * yyyy-MM-dd HH:mm:ss
     */
    YYYYMMDD_HHMMSS("4", "yyyy-MM-dd HH:mm:ss"); //$NON-NLS-1$ //$NON-NLS-2$

    private String mId;
    private String mFormat;

    /**
     * Constructor of FileTimeFormatMode.
     *
     * @param id The unique identifier of the enumeration
     * @param format The format (if apply)
     */
    private FileTimeFormatMode(String id, String format) {
        this.mId = id;
        this.mFormat = format;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getId() {
        return this.mId;
    }

    /**
     * Method that returns the format of the filetime.
     *
     * @return String The format of the filetime.
     */
    public String getFormat() {
        return this.mFormat;
    }

    /**
     * Method that returns an instance of {@link FileTimeFormatMode} from its
     * unique identifier.
     *
     * @param id The unique identifier
     * @return FileTimeFormatMode The filetime format mode
     */
    public static FileTimeFormatMode fromId(String id) {
        FileTimeFormatMode[] values = values();
        int cc = values.length;
        for (int i = 0; i < cc; i++) {
            if (values[i].mId.compareTo(id) == 0) {
                return values[i];
            }
        }
        return null;
    }

}


text:
/*
 *
 */
package net.community.chest.io.input;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.CharBuffer;

/**
 *
Copyright as per GPLv2

 *
 *
This {@link InputStream} "logs" whatever is read through it
 * via an {@link Appendable} instance (if not null)

 * @author Lyor G.
 * @since Aug 2, 2011 2:30:25 PM
 */
public class LoggingInputStream extends FilterInputStream {
    private Appendable    _out;
    public Appendable getAppender ()
    {
        return _out;
    }

    public void setAppender (Appendable out)
    {
        _out = out;
    }

    public LoggingInputStream (Appendable out, InputStream inp)
    {
        super(inp);
        _out = out;
    }
    /*
     * @see java.io.FilterInputStream#read()
     */
    @Override
    public int read () throws IOException
    {
        final int            result=super.read();
        final Appendable    out=getAppender();
        if ((result != (-1)) && (out != null))
            out.append((char) (result & 0x00FF));
        return result;
    }
    /*
     * @see java.io.FilterInputStream#read(byte[], int, int)
     */
    @Override
    public int read (byte[] b, int off, int len) throws IOException
    {
        final int            result=super.read(b, off, len);
        final Appendable    out=getAppender();
        if ((result > 0) && (out != null))
            out.append(CharBuffer.wrap(convertToChars(b, off, result)));
        return result;
    }

    private char[]    _workBuf;
    protected char[] convertToChars (byte[] b, int off, int len)
    {
        final int    curLen=(_workBuf == null) ? 0 : _workBuf.length;
        if (curLen < len)
            _workBuf = new char[len + Byte.MAX_VALUE];
        for (int    curOffset=off, lIndex=0; lIndex < len; curOffset++, lIndex++)
            _workBuf[lIndex] = (char) (b[curOffset] & 0x00FF);
        return _workBuf;
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.metrics;

import static org.chromium.chrome.browser.metrics.LaunchMetrics.EnumeratedHistogramSample;

import android.content.Intent;

/**
 * Helper class to record which kind of media notifications does the user click to go back to
 * Chrome.
 */
public class MediaNotificationUma {
    public static final int SOURCE_INVALID = -1;
    public static final int SOURCE_MEDIA = 0;
    public static final int SOURCE_PRESENTATION = 1;
    public static final int SOURCE_MEDIA_FLING = 2;
    public static final int SOURCE_MAX = 3;

    public static final String INTENT_EXTRA_NAME =
            "org.chromium.chrome.browser.metrics.MediaNotificationUma.EXTRA_CLICK_SOURCE";

    private static final EnumeratedHistogramSample sClickSourceHistogram =
            new LaunchMetrics.EnumeratedHistogramSample(
                    "Media.Notification.Click", SOURCE_MAX);

    /**
     * Record the UMA as specified by {@link intent}. The {@link intent} should contain intent extra
     * of name {@link INTENT_EXTRA_NAME} indicating the type.
     * @param intent The intent starting the activity.
     */
    public static void recordClickSource(Intent intent) {
        if (intent == null) return;
        int source = intent.getIntExtra(INTENT_EXTRA_NAME, SOURCE_INVALID);
        if (source == SOURCE_INVALID || source >= SOURCE_MAX) return;
        sClickSourceHistogram.record(source);
    }
}


text:
export default Em.ObjectController.extend({

  title: 'My Workouts',
  currentWeek: function() {
    return moment().isoWeek();
  }.property()

});


text:
package describe

import (
	"io/ioutil"
	"reflect"
	"strings"
	"testing"

	kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"

	authorizationapi "github.com/openshift/origin/pkg/authorization/api"
	buildapi "github.com/openshift/origin/pkg/build/api"
	deployapi "github.com/openshift/origin/pkg/deploy/api"
	imageapi "github.com/openshift/origin/pkg/image/api"
	projectapi "github.com/openshift/origin/pkg/project/api"
)

// PrinterCoverageExceptions is the list of API types that do NOT have corresponding printers
// If you add something to this list, explain why it doesn't need validation.  waaaa is not a valid
// reason.
var PrinterCoverageExceptions = []reflect.Type{
	reflect.TypeOf(&imageapi.DockerImage{}), // not a top level resource
	reflect.TypeOf(&buildapi.BuildLog{}),    // just a marker type
}

// MissingPrinterCoverageExceptions is the list of types that were missing printer methods when I started
// You should never add to this list
// TODO printers should be added for these types
var MissingPrinterCoverageExceptions = []reflect.Type{
	reflect.TypeOf(&authorizationapi.SubjectAccessReviewResponse{}),
	reflect.TypeOf(&authorizationapi.ResourceAccessReviewResponse{}),
	reflect.TypeOf(&authorizationapi.SubjectAccessReview{}),
	reflect.TypeOf(&authorizationapi.ResourceAccessReview{}),
	reflect.TypeOf(&deployapi.DeploymentConfigRollback{}),
	reflect.TypeOf(&imageapi.ImageStreamMapping{}),
	reflect.TypeOf(&buildapi.BuildLogOptions{}),
	reflect.TypeOf(&buildapi.BuildRequest{}),
	reflect.TypeOf(&projectapi.ProjectRequest{}),
}

func TestPrinterCoverage(t *testing.T) {
	printer := NewHumanReadablePrinter(false, false, false, []string{})

main:
	for _, apiType := range kapi.Scheme.KnownTypes("") {
		if !strings.Contains(apiType.PkgPath(), "openshift/origin") {
			continue
		}

		ptrType := reflect.PtrTo(apiType)
		for _, exception := range PrinterCoverageExceptions {
			if ptrType == exception {
				continue main
			}
		}
		for _, exception := range MissingPrinterCoverageExceptions {
			if ptrType == exception {
				continue main
			}
		}

		newStructValue := reflect.New(apiType)
		newStruct := newStructValue.Interface()

		if err := printer.PrintObj(newStruct.(runtime.Object), ioutil.Discard); (err != nil) && strings.Contains(err.Error(), "error: unknown type ") {
			t.Errorf("missing printer for %v.  Check pkg/cmd/cli/describe/printer.go", apiType)
		}
	}
}


text:
import { Utils } from '../../lib/vulcan-lib';
import Users from '../../lib/collections/users/collection';
import { registerMigration, migrateDocuments } from './migrationUtils';
import * as _ from 'underscore';

registerMigration({
  name: "fixCapitalizedSlugs",
  dateWritten: "2019-05-14",
  idempotent: true,
  action: async () => await migrateDocuments({
    description: `lowercase slugs`,
    collection: Users,
    unmigratedDocumentQuery: {
      slug: /.*[A-Z].*/,
    },
    batchSize: 1000,
    migrate: async (users) => {
      let updates = _.map(users, user => ({
        updateOne: {
          filter: { _id: user._id },
          update: {
            $set: {
              slug: Utils.getUnusedSlugByCollectionName('Users', Utils.slugify(user.slug))
            }
          }
        }
      }));
      await Users.rawCollection().bulkWrite(updates, { ordered: false });
    },
  })
});


text:
'use strict';

var exports = {};

exports.collMethods = ['find', 'findOne', 'findById',
                    'findReadOnly', 'findOneReadOnly', 'findByIdReadOnly',
                    'insert', 'update', 'remove', 'lock', 'count'];

exports.connMethods = ['commit', 'rollback', 'eval', 'info', 'resetCounter', 'flushBackend', '$unload', '$findReadOnly'];

exports.version = require('../package').version;

module.exports = exports;


text:
package com.github.smallcreep.cucumber.seeds.generator.placeholders;

import com.github.smallcreep.cucumber.seeds.generator.Placeholder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.cactoos.BiFunc;
import org.cactoos.Text;
import org.cactoos.text.FormattedText;

/**
 * Placeholder with params in round braces,
 * replace all placeholders in parameter.
 * @since 0.2.0
 */
public abstract class PlaceholderWithParams implements Placeholder {

    /**
     * Function string.
     */
    private static final String FUNCTION = "%s\\(%s\\)";

    /**
     * Origin function for placeholder.
     */
    private final BiFunc<String, String, String> origin;

    /**
     * Placeholder.
     */
    private final Placeholder placeholder;

    /**
     * Pattern.
     */
    private final Pattern pattern;

    /**
     * Regexp.
     */
    private final Text regexp;

    /**
     * Ctor.
     * @param origin Origin function for placeholder
     * @param regexp Regexp
     * @param placeholder Placeholder
     * @throws Exception if fails
     */
    public PlaceholderWithParams(
        final BiFunc<String, String, String> origin,
        final String regexp,
        final Placeholder placeholder
    ) throws Exception {
        this.origin = origin;
        this.pattern = Pattern.compile(
            new FormattedText(
                PlaceholderWithParams.FUNCTION,
                regexp,
                "([^)]*)"
            ).asString()
        );
        this.regexp = new FormattedText(
            PlaceholderWithParams.FUNCTION,
            regexp,
            "%s"
        );
        this.placeholder = placeholder;
    }

    @Override
    public final String apply(final String input) throws Exception {
        String result = input;
        Matcher matcher = this.pattern.matcher(result);
        while (matcher.find()) {
            final String group = matcher.group(1);
            result = new PlaceholderRegexp(
                temp -> this.origin.apply(temp, this.placeholder.apply(group)),
                String.format(this.regexp.asString(), Pattern.quote(group))
            ).apply(result);
            matcher = this.pattern.matcher(result);
        }
        return result;
    }
}


text:
qemu-system-i386 -vga std -rtc base=localtime,clock=host \
    -fda img/floppy.img -boot a


text:
package org.sociotech.urbanlifeplus.microinforadiator.service;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import org.sociotech.urbanlifeplus.microinforadiator.interfaces.proximity.Proximity;
import org.sociotech.urbanlifeplus.microinforadiator.model.User;

/**
 * @author vituslehner 25.08.17
 */
public class UserDeviceMessage {

    private final User user;
    private final Proximity proximity;
    private final String mirIBeaconMajorMinor;

    @JsonCreator
    public UserDeviceMessage(@JsonProperty("user") User user,
                             @JsonProperty("proximity") Proximity proximity,
                             @JsonProperty("mirIBeaconMajorMinor") String mirIBeaconMajorMinor) {
        this.user = user;
        this.proximity = proximity;
        this.mirIBeaconMajorMinor = mirIBeaconMajorMinor;
    }

    public User getUser() {
        return user;
    }

    public Proximity getProximity() {
        return proximity;
    }

    public String getMirIBeaconMajorMinor() {
        return mirIBeaconMajorMinor;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UserDeviceMessage that = (UserDeviceMessage) o;
        return Objects.equal(user, that.user) &&
                proximity == that.proximity &&
                Objects.equal(mirIBeaconMajorMinor, that.mirIBeaconMajorMinor);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(user, proximity, mirIBeaconMajorMinor);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("user", user)
                .add("proximity", proximity)
                .add("mirIBeaconMajorMinor", mirIBeaconMajorMinor)
                .toString();
    }
}


text:
namespace base {
class SingleThreadTaskRunner;
}

namespace blink {
class PeerConnectionDependencyFactory;

// A map and owner of |WebRtcMediaStreamTrackAdapter|s. It takes care of
// creating, initializing and disposing track adapters independently of media
// streams. Adapters are accessed via |AdapterRef|s, when all references to an
// adapter are destroyed it is disposed and removed from the map.
// Objects of this class must be constructed on the main thread, after which
// they may be accessed from any thread. The two exceptions to that are
// `GetOrCreateLocalTrackAdapter()` that must be called from the main thread and
// `GetOrCreateRemoteTrackAdapter()` which must not be called from the main
// thread.
class MODULES_EXPORT WebRtcMediaStreamTrackAdapterMap
    : public WTF::ThreadSafeRefCounted<WebRtcMediaStreamTrackAdapterMap> {
 public:
  // Acts as an accessor to adapter members without leaking a reference to the
  // adapter. When the last |AdapterRef| is destroyed, the corresponding adapter
  // is |Dispose|d and removed from the map.
  class MODULES_EXPORT AdapterRef {
   public:
    // Must be invoked on the main thread. If this was the last reference to the
    // adapter it will be disposed and removed from the map.
    ~AdapterRef();

    std::unique_ptr<AdapterRef> Copy() const;
    bool is_initialized() const { return adapter_->is_initialized(); }
    void InitializeOnMainThread();
    MediaStreamComponent* track() const { return adapter_->track(); }
    webrtc::MediaStreamTrackInterface* webrtc_track() const {
      return adapter_->webrtc_track();
    }

    // Warning: Holding an external reference to the adapter will prevent
    // |~AdapterRef| from disposing the adapter.
    blink::WebRtcMediaStreamTrackAdapter* GetAdapterForTesting() const {
      return adapter_.get();
    }

   private:
    friend class WebRtcMediaStreamTrackAdapterMap;

    enum class Type { kLocal, kRemote };

    // Assumes map's |lock_| is held.
    AdapterRef(scoped_refptr<WebRtcMediaStreamTrackAdapterMap> map,
               Type type,
               scoped_refptr<blink::WebRtcMediaStreamTrackAdapter> adapter);

    scoped_refptr<WebRtcMediaStreamTrackAdapterMap> map_;
    Type type_;
    // A reference to the entry's adapter, ensures that |HasOneRef()| is false
    // as long as the |AdapterRef| is kept alive (the map entry has one
    // reference to it too).
    scoped_refptr<blink::WebRtcMediaStreamTrackAdapter> adapter_;
  };

  // Must be invoked on the main thread.
  WebRtcMediaStreamTrackAdapterMap(
      blink::PeerConnectionDependencyFactory* const factory,
      scoped_refptr<base::SingleThreadTaskRunner> main_thread);

  // Gets a new reference to the local track adapter, or null if no such adapter
  // was found. When all references are destroyed the adapter is disposed and
  // removed from the map. This method can be called from any thread, but
  // references must be destroyed on the main thread.
  // The adapter is a associated with a blink and webrtc track, lookup works by
  // either track.
  std::unique_ptr<AdapterRef> GetLocalTrackAdapter(
      MediaStreamComponent* component);
  std::unique_ptr<AdapterRef> GetLocalTrackAdapter(
      webrtc::MediaStreamTrackInterface* webrtc_track);
  // Invoke on the main thread. Gets a new reference to the local track adapter
  // for the web track. If no adapter exists for the track one is created and
  // initialized. When all references are destroyed the adapter is disposed and
  // removed from the map. References must be destroyed on the main thread.
  std::unique_ptr<AdapterRef> GetOrCreateLocalTrackAdapter(
      MediaStreamComponent* component);
  size_t GetLocalTrackCount() const;

  // Gets a new reference to the remote track adapter. When all references are
  // destroyed the adapter is disposed and removed from the map. This method can
  // be called from any thread, but references must be destroyed on the main
  // thread. The adapter is a associated with a blink and webrtc track, lookup
  // works by either track.
  // First variety: If an adapter exists it will already be initialized, if one
  // does not exist null is returned.
  std::unique_ptr<AdapterRef> GetRemoteTrackAdapter(
      MediaStreamComponent* component);
  // Second variety: If an adapter exists it may or may not be initialized, see
  // |AdapterRef::is_initialized|. If an adapter does not exist null is
  // returned.
  std::unique_ptr<AdapterRef> GetRemoteTrackAdapter(
      webrtc::MediaStreamTrackInterface* webrtc_track);
  // Invoke on the webrtc signaling thread. Gets a new reference to the remote
  // track adapter for the webrtc track. If no adapter exists for the track one
  // is created and initialization completes on the main thread in a post. When
  // all references are destroyed the adapter is disposed and removed from the
  // map. References must be destroyed on the main thread.
  std::unique_ptr<AdapterRef> GetOrCreateRemoteTrackAdapter(
      scoped_refptr<webrtc::MediaStreamTrackInterface> webrtc_track);
  size_t GetRemoteTrackCount() const;

 private:
  friend class WTF::ThreadSafeRefCounted<WebRtcMediaStreamTrackAdapterMap>;

  // "(MediaStreamComponent, webrtc::MediaStreamTrackInterface) ->
  // WebRtcMediaStreamTrackAdapter" maps. The primary key is based on the object
  // used to create the adapter. Local tracks are created from
  // |MediaStreamComponent|s, remote tracks are created from
  // |webrtc::MediaStreamTrackInterface|s.
  // The adapter keeps the |webrtc::MediaStreamTrackInterface| alive with ref
  // counting making it safe to use a raw pointer for key.
  using LocalTrackAdapterMap = blink::TwoKeysAdapterMap<
      int,  // MediaStreamComponent::UniqueId()
      webrtc::MediaStreamTrackInterface*,
      scoped_refptr<blink::WebRtcMediaStreamTrackAdapter>>;
  using RemoteTrackAdapterMap = blink::TwoKeysAdapterMap<
      webrtc::MediaStreamTrackInterface*,
      int,  // MediaStreamComponent::UniqueId()
      scoped_refptr<blink::WebRtcMediaStreamTrackAdapter>>;

  // Invoke on the main thread.
  virtual ~WebRtcMediaStreamTrackAdapterMap();

  // The adapter map is indirectly owned by `RTCPeerConnection`, which is
  // outlived by the `PeerConnectionDependencyFactory`, so `factory_` should
  // never be null (with the possible exception of the dtor).
  const CrossThreadWeakPersistent<PeerConnectionDependencyFactory> factory_;
  scoped_refptr<base::SingleThreadTaskRunner> main_thread_;

  mutable base::Lock lock_;
  LocalTrackAdapterMap local_track_adapters_;
  RemoteTrackAdapterMap remote_track_adapters_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_WEBRTC_MEDIA_STREAM_TRACK_ADAPTER_MAP_H_


text:
const Koa = require('koa');
const bodyParser = require('.');

const app = new Koa();
app.use(bodyParser());

app.use(async function() {
  // the parsed body will store in this.request.body
  this.body = this.request.body;
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () =>
  console.log(`Server ready at http://localhost:${PORT} 🚀 ..`)
);


text:
// Common definition for video, including fourcc and VideoFormat.

#ifndef WEBRTC_MEDIA_BASE_VIDEOCOMMON_H_  // NOLINT
#define WEBRTC_MEDIA_BASE_VIDEOCOMMON_H_

#include <stdint.h>

#include <string>

#include "webrtc/base/timeutils.h"

namespace cricket {

// TODO(janahan): For now, a hard-coded ssrc is used as the video ssrc.
// This is because when the video frame is passed to the mediaprocessor for
// processing, it doesn't have the correct ssrc. Since currently only Tx
// Video processing is supported, this is ok. When we switch over to trigger
// from capturer, this should be fixed and this const removed.
const uint32_t kDummyVideoSsrc = 0xFFFFFFFF;

// Minimum interval is 10k fps.
#define FPS_TO_INTERVAL(fps) \
    (fps ? rtc::kNumNanosecsPerSec / fps : \
    rtc::kNumNanosecsPerSec / 10000)

//////////////////////////////////////////////////////////////////////////////
// Definition of FourCC codes
//////////////////////////////////////////////////////////////////////////////
// Convert four characters to a FourCC code.
// Needs to be a macro otherwise the OS X compiler complains when the kFormat*
// constants are used in a switch.
#define FOURCC(a, b, c, d)                                        \
  ((static_cast<uint32_t>(a)) | (static_cast<uint32_t>(b) << 8) | \
   (static_cast<uint32_t>(c) << 16) | (static_cast<uint32_t>(d) << 24))
// Some pages discussing FourCC codes:
//   http://www.fourcc.org/yuv.php
//   http://v4l2spec.bytesex.org/spec/book1.htm
//   http://developer.apple.com/quicktime/icefloe/dispatch020.html
//   http://msdn.microsoft.com/library/windows/desktop/dd206750.aspx#nv12
//   http://people.xiph.org/~xiphmont/containers/nut/nut4cc.txt

// FourCC codes grouped according to implementation efficiency.
// Primary formats should convert in 1 efficient step.
// Secondary formats are converted in 2 steps.
// Auxilliary formats call primary converters.
enum FourCC {
  // 9 Primary YUV formats: 5 planar, 2 biplanar, 2 packed.
  FOURCC_I420 = FOURCC('I', '4', '2', '0'),
  FOURCC_I422 = FOURCC('I', '4', '2', '2'),
  FOURCC_I444 = FOURCC('I', '4', '4', '4'),
  FOURCC_I411 = FOURCC('I', '4', '1', '1'),
  FOURCC_I400 = FOURCC('I', '4', '0', '0'),
  FOURCC_NV21 = FOURCC('N', 'V', '2', '1'),
  FOURCC_NV12 = FOURCC('N', 'V', '1', '2'),
  FOURCC_YUY2 = FOURCC('Y', 'U', 'Y', '2'),
  FOURCC_UYVY = FOURCC('U', 'Y', 'V', 'Y'),

  // 2 Secondary YUV formats: row biplanar.
  FOURCC_M420 = FOURCC('M', '4', '2', '0'),

  // 9 Primary RGB formats: 4 32 bpp, 2 24 bpp, 3 16 bpp.
  FOURCC_ARGB = FOURCC('A', 'R', 'G', 'B'),
  FOURCC_BGRA = FOURCC('B', 'G', 'R', 'A'),
  FOURCC_ABGR = FOURCC('A', 'B', 'G', 'R'),
  FOURCC_24BG = FOURCC('2', '4', 'B', 'G'),
  FOURCC_RAW  = FOURCC('r', 'a', 'w', ' '),
  FOURCC_RGBA = FOURCC('R', 'G', 'B', 'A'),
  FOURCC_RGBP = FOURCC('R', 'G', 'B', 'P'),  // bgr565.
  FOURCC_RGBO = FOURCC('R', 'G', 'B', 'O'),  // abgr1555.
  FOURCC_R444 = FOURCC('R', '4', '4', '4'),  // argb4444.

  // 4 Secondary RGB formats: 4 Bayer Patterns.
  FOURCC_RGGB = FOURCC('R', 'G', 'G', 'B'),
  FOURCC_BGGR = FOURCC('B', 'G', 'G', 'R'),
  FOURCC_GRBG = FOURCC('G', 'R', 'B', 'G'),
  FOURCC_GBRG = FOURCC('G', 'B', 'R', 'G'),

  // 1 Primary Compressed YUV format.
  FOURCC_MJPG = FOURCC('M', 'J', 'P', 'G'),

  // 5 Auxiliary YUV variations: 3 with U and V planes are swapped, 1 Alias.
  FOURCC_YV12 = FOURCC('Y', 'V', '1', '2'),
  FOURCC_YV16 = FOURCC('Y', 'V', '1', '6'),
  FOURCC_YV24 = FOURCC('Y', 'V', '2', '4'),
  FOURCC_YU12 = FOURCC('Y', 'U', '1', '2'),  // Linux version of I420.
  FOURCC_J420 = FOURCC('J', '4', '2', '0'),
  FOURCC_J400 = FOURCC('J', '4', '0', '0'),

  // 14 Auxiliary aliases.  CanonicalFourCC() maps these to canonical fourcc.
  FOURCC_IYUV = FOURCC('I', 'Y', 'U', 'V'),  // Alias for I420.
  FOURCC_YU16 = FOURCC('Y', 'U', '1', '6'),  // Alias for I422.
  FOURCC_YU24 = FOURCC('Y', 'U', '2', '4'),  // Alias for I444.
  FOURCC_YUYV = FOURCC('Y', 'U', 'Y', 'V'),  // Alias for YUY2.
  FOURCC_YUVS = FOURCC('y', 'u', 'v', 's'),  // Alias for YUY2 on Mac.
  FOURCC_HDYC = FOURCC('H', 'D', 'Y', 'C'),  // Alias for UYVY.
  FOURCC_2VUY = FOURCC('2', 'v', 'u', 'y'),  // Alias for UYVY on Mac.
  FOURCC_JPEG = FOURCC('J', 'P', 'E', 'G'),  // Alias for MJPG.
  FOURCC_DMB1 = FOURCC('d', 'm', 'b', '1'),  // Alias for MJPG on Mac.
  FOURCC_BA81 = FOURCC('B', 'A', '8', '1'),  // Alias for BGGR.
  FOURCC_RGB3 = FOURCC('R', 'G', 'B', '3'),  // Alias for RAW.
  FOURCC_BGR3 = FOURCC('B', 'G', 'R', '3'),  // Alias for 24BG.
  FOURCC_CM32 = FOURCC(0, 0, 0, 32),  // Alias for BGRA kCMPixelFormat_32ARGB
  FOURCC_CM24 = FOURCC(0, 0, 0, 24),  // Alias for RAW kCMPixelFormat_24RGB

  // 1 Auxiliary compressed YUV format set aside for capturer.
  FOURCC_H264 = FOURCC('H', '2', '6', '4'),
};

// Match any fourcc.

// We move this out of the enum because using it in many places caused
// the compiler to get grumpy, presumably since the above enum is
// backed by an int.
static const uint32_t FOURCC_ANY = 0xFFFFFFFF;

// Converts fourcc aliases into canonical ones.
uint32_t CanonicalFourCC(uint32_t fourcc);

// Get FourCC code as a string.
inline std::string GetFourccName(uint32_t fourcc) {
  std::string name;
  name.push_back(static_cast<char>(fourcc & 0xFF));
  name.push_back(static_cast<char>((fourcc >> 8) & 0xFF));
  name.push_back(static_cast<char>((fourcc >> 16) & 0xFF));
  name.push_back(static_cast<char>((fourcc >> 24) & 0xFF));
  return name;
}

//////////////////////////////////////////////////////////////////////////////
// Definition of VideoFormat.
//////////////////////////////////////////////////////////////////////////////

// VideoFormat with Plain Old Data for global variables.
struct VideoFormatPod {
  int width;  // Number of pixels.
  int height;  // Number of pixels.
  int64_t interval;  // Nanoseconds.
  uint32_t fourcc;  // Color space. FOURCC_ANY means that any color space is OK.
};

struct VideoFormat : VideoFormatPod {
  static const int64_t kMinimumInterval =
      rtc::kNumNanosecsPerSec / 10000;  // 10k fps.

  VideoFormat() {
    Construct(0, 0, 0, 0);
  }

  VideoFormat(int w, int h, int64_t interval_ns, uint32_t cc) {
    Construct(w, h, interval_ns, cc);
  }

  explicit VideoFormat(const VideoFormatPod& format) {
    Construct(format.width, format.height, format.interval, format.fourcc);
  }

  void Construct(int w, int h, int64_t interval_ns, uint32_t cc) {
    width = w;
    height = h;
    interval = interval_ns;
    fourcc = cc;
  }

  static int64_t FpsToInterval(int fps) {
    return fps ? rtc::kNumNanosecsPerSec / fps : kMinimumInterval;
  }

  static int IntervalToFps(int64_t interval) {
    if (!interval) {
      return 0;
    }
    return static_cast<int>(rtc::kNumNanosecsPerSec / interval);
  }

  static float IntervalToFpsFloat(int64_t interval) {
    if (!interval) {
      return 0.f;
    }
    return static_cast<float>(rtc::kNumNanosecsPerSec) /
        static_cast<float>(interval);
  }

  bool operator==(const VideoFormat& format) const {
    return width == format.width && height == format.height &&
        interval == format.interval && fourcc == format.fourcc;
  }

  bool operator!=(const VideoFormat& format) const {
    return !(*this == format);
  }

  bool operator<(const VideoFormat& format) const {
    return (fourcc < format.fourcc) ||
        (fourcc == format.fourcc && width < format.width) ||
        (fourcc == format.fourcc && width == format.width &&
            height < format.height) ||
        (fourcc == format.fourcc && width == format.width &&
            height == format.height && interval > format.interval);
  }

  int framerate() const { return IntervalToFps(interval); }

  // Check if both width and height are 0.
  bool IsSize0x0() const { return 0 == width && 0 == height; }

  // Check if this format is less than another one by comparing the resolution
  // and frame rate.
  bool IsPixelRateLess(const VideoFormat& format) const {
    return width * height * framerate() <
        format.width * format.height * format.framerate();
  }

  // Get a string presentation in the form of "fourcc width x height x fps"
  std::string ToString() const;
};

}  // namespace cricket

#endif  // WEBRTC_MEDIA_BASE_VIDEOCOMMON_H_  // NOLINT


text:
<?php
namespace ZfcDatagrid\Column\Formatter;

use ZfcDatagrid\Column\AbstractColumn;

class FileSize extends AbstractFormatter
{
    /**
     * We implement isApply here ourself, because it's always valid!
     *
     * @var unknown
     */
    protected $validRenderers = [];

    protected static $prefixes = [
        '',
        'K',
        'M',
        'G',
        'T',
        'P',
        'E',
        'Z',
        'Y',
    ];

    public function isApply()
    {
        return true;
    }

    /**
     * The value should be in bytes
     *
     * @see \ZfcDatagrid\Column\Formatter\AbstractFormatter::getFormattedValue()
     */
    public function getFormattedValue(AbstractColumn $column)
    {
        $row   = $this->getRowData();
        $value = $row[$column->getUniqueId()];

        if ('' == $value) {
            return $value;
        }

        $index = 0;
        while ($value >= 1024 && $index < count(self::$prefixes)) {
            $value = $value / 1024;
            $index ++;
        }

        return sprintf('%1.2f %sB', $value, self::$prefixes[$index]);
    }
}


text:
package korolev.http

import java.net.SocketAddress
import java.nio.channels.AsynchronousChannelGroup

import korolev.data.BytesLike
import korolev.data.syntax._
import korolev.effect.io.ServerSocket
import korolev.effect.syntax._
import korolev.effect.{Decoder, Effect, Stream}
import korolev.http.protocol.Http11
import korolev.web.{Request, Response}

import scala.concurrent.ExecutionContext
import scala.util.control.NonFatal

object HttpServer {

  /**
    * @see [[ServerSocket.bind]]
    */
  def apply[F[_]: Effect, B: BytesLike](address: SocketAddress,
                                        backlog: Int = 0,
                                        bufferSize: Int = 8096,
                                        group: AsynchronousChannelGroup = null,
                                        gracefulShutdown: Boolean = false)
                                       (f: Request[Stream[F, B]] => F[Response[Stream[F, B]]])
                                       (implicit ec: ExecutionContext): F[ServerSocket.ServerSocketHandler[F]] = {

    val InternalServerErrorMessage = BytesLike[B].ascii("Internal server error")
    val http11 = new Http11[B]

    ServerSocket.accept[F, B](address, backlog, bufferSize, group, gracefulShutdown) { client =>
      http11
        .decodeRequest(Decoder(client.stream))
        .foreach { request =>
          for {
            response <- f(request).recoverF {
              case NonFatal(error) =>
                ec.reportFailure(error)
                Stream(InternalServerErrorMessage).mat() map { body =>
                  Response(Response.Status.InternalServerError, body, Nil, Some(InternalServerErrorMessage.length))
                }
            }
            byteStream <- http11.renderResponse(response)
            _ <- byteStream.foreach(client.write)
          } yield ()
        }
    }
  }
}


text:
import { IMessage } from '../../../../../../definition/IMessage';
import { IRoom } from '../../../../../../definition/IRoom';
import { ObjectFromApi } from '../../../../../../definition/ObjectFromApi';

export type FilesEndpoint = {
	GET: (params: {
		roomId: IRoom['_id'];
		count: number;
		sort: string;
		query: string;
	}) => {
		files: ObjectFromApi<IMessage>[];
		total: number;
	};
};


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 297028 $ -->
<refentry xml:id="function.dbx-compare" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>dbx_compare</refname>
  <refpurpose>Compare two rows for sorting purposes</refpurpose>
 </refnamediv>
 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>int</type><methodname>dbx_compare</methodname>
   <methodparam><type>array</type><parameter>row_a</parameter></methodparam>
   <methodparam><type>array</type><parameter>row_b</parameter></methodparam>
   <methodparam><type>string</type><parameter>column_key</parameter></methodparam>
   <methodparam choice="opt"><type>int</type><parameter>flags</parameter><initializer>DBX_CMP_ASC | DBX_CMP_NATIVE</initializer></methodparam>
  </methodsynopsis>
  <para>
   <function>dbx_compare</function> is a helper function for
   <function>dbx_sort</function> to ease the make and use of the custom
   sorting function.
  </para>
 </refsect1>
 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>row_a</parameter></term>
     <listitem>
      <para>
       First row
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>row_b</parameter></term>
     <listitem>
      <para>
       Second row
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>column_key</parameter></term>
     <listitem>
      <para>
       The compared column
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>flags</parameter></term>
     <listitem>
      <para>
       The <parameter>flags</parameter> can be set to specify comparison
       direction:
       <itemizedlist>
        <listitem>
         <simpara>
          <constant>DBX_CMP_ASC</constant> - ascending order
         </simpara>
        </listitem>
        <listitem>
         <simpara>
          <constant>DBX_CMP_DESC</constant> - descending order
         </simpara>
        </listitem>
       </itemizedlist>
       and the preferred comparison type:
       <itemizedlist>
        <listitem>
         <simpara>
          <constant>DBX_CMP_NATIVE</constant> - no type conversion
         </simpara>
        </listitem>
        <listitem>
         <simpara>
          <constant>DBX_CMP_TEXT</constant> - compare items as strings
         </simpara>
        </listitem>
        <listitem>
         <simpara>
          <constant>DBX_CMP_NUMBER</constant> - compare items numerically
         </simpara>
        </listitem>
       </itemizedlist>
       One of the direction and one of the type constant can be combined with
       bitwise OR operator (|).
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>
 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Returns <literal>0</literal> if the <literal>row_a[$column_key]</literal>
   is equal to <literal>row_b[$column_key]</literal>, and <literal>1</literal>
   or <literal>-1</literal> if the former is greater or is smaller than the
   latter one, respectively, or vice versa if the <parameter>flag</parameter>
   is set to <constant>DBX_CMP_DESC</constant>.
  </para>
 </refsect1>
 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title><function>dbx_compare</function> example</title>
    <programlisting role="php">
<![CDATA[
<?php
function user_re_order($a, $b)
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM table ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // date in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>
]]>
    </programlisting>
   </example>
  </para>
 </refsect1>
 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>dbx_sort</function></member>
   </simplelist>
  </para>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package com.facebook.buck.cli;

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

import com.facebook.buck.jvm.java.DefaultJavaPackageFinder;
import com.facebook.buck.util.HumanReadableException;
import com.google.common.collect.ImmutableList;
import java.nio.file.Paths;
import org.junit.Test;

public class DefaultJavaPackageFinderTest {

  /** If no paths are specified, then the project root should be considered a Java source root. */
  @Test
  public void testNoPathsSpecified() {
    DefaultJavaPackageFinder javaPackageFinder =
        DefaultJavaPackageFinder.createDefaultJavaPackageFinder(ImmutableList.of());
    assertEquals(Paths.get(""), javaPackageFinder.findJavaPackageFolder(Paths.get("Base.java")));
    assertEquals(
        Paths.get("java/com/example/base/"),
        javaPackageFinder.findJavaPackageFolder(Paths.get("java/com/example/base/Base.java")));
  }

  @Test
  public void testSinglePathFromRoot() {
    DefaultJavaPackageFinder javaPackageFinder =
        DefaultJavaPackageFinder.createDefaultJavaPackageFinder(ImmutableList.of("/java/"));
    assertEquals(
        Paths.get("com/example/base/"),
        javaPackageFinder.findJavaPackageFolder(Paths.get("java/com/example/base/Base.java")));
    assertEquals(
        "com.example.base",
        javaPackageFinder.findJavaPackage(Paths.get("java/com/example/base/Base.java")));
    assertEquals(
        Paths.get(""), javaPackageFinder.findJavaPackageFolder(Paths.get("java/Weird.java")));
    assertEquals("", javaPackageFinder.findJavaPackage(Paths.get("java/Weird.java")));
    assertEquals(
        "When there is no match, the project root should be treated as a Java source root.",
        Paths.get("notjava/"),
        javaPackageFinder.findJavaPackageFolder(Paths.get("notjava/Weird.java")));
    assertEquals(
        "When there is no match, the project root should be treated as a Java source root.",
        "notjava",
        javaPackageFinder.findJavaPackage(Paths.get("notjava/Weird.java")));
  }

  @Test
  public void testOverlappingPathsFromRoot() {
    DefaultJavaPackageFinder javaPackageFinder =
        DefaultJavaPackageFinder.createDefaultJavaPackageFinder(
            ImmutableList.of("/java", "/java/more/specific", "/javatests"));
    assertEquals(
        Paths.get("com/example/base/"),
        javaPackageFinder.findJavaPackageFolder(Paths.get("java/com/example/base/Base.java")));
    assertEquals(
        Paths.get("base/"),
        javaPackageFinder.findJavaPackageFolder(Paths.get("java/more/specific/base/Base.java")));
    assertEquals(
        Paths.get("com/example/base/"),
        javaPackageFinder.findJavaPackageFolder(
            Paths.get("javatests/com/example/base/BaseTest.java")));
  }

  @Test
  public void testSinglePathElement() {
    DefaultJavaPackageFinder javaPackageFinder =
        DefaultJavaPackageFinder.createDefaultJavaPackageFinder(ImmutableList.of("src"));
    assertEquals(
        Paths.get("com/example/base/"),
        javaPackageFinder.findJavaPackageFolder(
            Paths.get("java/main/src/com/example/base/Base.java")));
    assertEquals(
        "When the path element appears more than once, use the rightmost instance as the base.",
        Paths.get("com/example/base/"),
        javaPackageFinder.findJavaPackageFolder(
            Paths.get("java/main/src/other/project/src/com/example/base/Base.java")));
    assertEquals(
        Paths.get(""), javaPackageFinder.findJavaPackageFolder(Paths.get("src/Weird.java")));
    assertEquals(
        "When there is no match, the project root should be treated as a Java source root.",
        Paths.get("notjava/"),
        javaPackageFinder.findJavaPackageFolder(Paths.get("notjava/Weird.java")));
  }

  @Test
  public void testMultiplePathElements() {
    DefaultJavaPackageFinder javaPackageFinder =
        DefaultJavaPackageFinder.createDefaultJavaPackageFinder(ImmutableList.of("src", "src-gen"));
    assertEquals(
        Paths.get("com/example/base/"),
        javaPackageFinder.findJavaPackageFolder(
            Paths.get("java/main/src-gen/other/project/src/com/example/base/Base.java")));
  }

  @Test
  public void testMixOfPrefixesAndPathElements() {
    DefaultJavaPackageFinder javaPackageFinder =
        DefaultJavaPackageFinder.createDefaultJavaPackageFinder(ImmutableList.of("/java", "src"));
    assertEquals(
        "Prefixes take precedence over path elements",
        Paths.get("com/example/base/"),
        javaPackageFinder.findJavaPackageFolder(
            Paths.get("/java/main/src/com/example/base/Base.java")));
  }

  @Test
  public void testInvalidPath() {
    try {
      DefaultJavaPackageFinder.createDefaultJavaPackageFinder(ImmutableList.of("src/"));
      fail("Should have thrown HumanReadableException.");
    } catch (HumanReadableException e) {
      assertEquals(
          "Path pattern that does not start with a slash cannot contain a slash: src/",
          e.getHumanReadableErrorMessage());
    }
  }
}


text:
<link rel="import" href="/jspm_packages/bower/paper-button/paper-button.html">
<link rel="import" href="/jspm_packages/bower/paper-item/paper-item.html">
<link rel="import" href="/jspm_packages/bower/paper-icon-button/paper-icon-button.html">
<link rel="import" href="/jspm_packages/bower/iron-icons/image-icons.html">
<template>
  <require from="../../converter/pagination/page"></require>

      <paper-button raised click.delegate="createEntity()">Novo</paper-button>

        ID
        Nome
        Ações

        ${entity.id}
        ${entity.nome}

          <paper-button raised click.trigger="$parent.editEntity(entity)">Editar</paper-button>
          <paper-button raised click.trigger="$parent.deleteEntity(entity)">Excluir</paper-button>

        <paper-icon-button icon="image:navigate-before"/>

      <paper-button>${pagination.number | currentPage}</paper-button>

        <paper-icon-button icon="image:navigate-next"/>

Total de páginas: ${pagination.totalPages}

Total de elementos: ${pagination.totalElements}

</template>


text:
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SparkDotNet
{

    public partial class Spark
    {

        private readonly string teamsBase = "/v1/teams";

        /// <summary>
        /// Lists teams to which the authenticated user belongs.
        /// </summary>
        /// <param name="max">Limit the maximum number of teams in the response. Default: 100</param>
        /// <returns>List of Team objects.</returns>
        public async Task<List<Team>> GetTeamsAsync(int max = 0)
        {
            var queryParams = new Dictionary<string, string>();
            if (max > 0) queryParams.Add("max",max.ToString());
            var path = getURL(teamsBase, queryParams);
            return await GetItemsAsync<Team>(path);
        }

        /// <summary>
        /// Shows details for a team, by ID.
        /// Specify the room ID in the teamId parameter in the URI.
        /// </summary>
        /// <param name="teamId">The unique identifier for the team.</param>
        /// <returns>Team object.</returns>
        public async Task<Team> GetTeamAsync(string teamId)
        {
            var queryParams = new Dictionary<string, string>();
            var path = getURL($"{teamsBase}/{teamId}", queryParams);
            return await GetItemAsync<Team>(path);
        }

        /// <summary>
        /// Creates a team. The authenticated user is automatically added as a member of the team.
        /// See the Team Memberships API to learn how to add more people to the team.
        /// </summary>
        /// <param name="name">A user-friendly name for the team.</param>
        /// <returns>Team object.</returns>
        public async Task<Team> CreateTeamAsync(string name)
        {
            var postBody = new Dictionary<string, object>();
            postBody.Add("name", name);
            return await PostItemAsync<Team>(teamsBase, postBody);
        }

        /// <summary>
        /// Deletes a team, by ID.
        /// Specify the team ID in the teamId parameter in the URI.
        /// </summary>
        /// <param name="teamId">The unique identifier for the team.</param>
        /// <returns>Boolean indicating success of operation.</returns>
        public async Task<bool> DeleteTeamAsync(string teamId)
        {
            return await DeleteItemAsync($"{teamsBase}/{teamId}");
        }

        /// <summary>
        /// Deletes a team, by object.
        /// </summary>
        /// <param name="team">The team object.</param>
        /// <returns>Boolean indicating success of operation.</returns>
        public async Task<bool> DeleteTeamAsync(Team team)
        {
            return await DeleteTeamAsync(team.id);
        }

        /// <summary>
        /// Updates details for a team, by ID.
        /// Specify the team ID in the teamId parameter in the URI.
        /// </summary>
        /// <param name="teamId">The unique identifier for the team.</param>
        /// <param name="name">A user-friendly name for the team.</param>
        /// <returns>Team object.</returns>
        public async Task<Team> UpdateTeamAsync(string teamId, string name)
        {
            var putBody = new Dictionary<string, object>();
            putBody.Add("name",name);
            var path = $"{teamsBase}/{teamId}";
            return await UpdateItemAsync<Team>(path, putBody);
        }
    }

}


text:
SET SQL_MODE='ALLOW_INVALID_DATES';
use kylo;
delimiter //

create procedure update_to_050()

begin

CREATE TABLE IF NOT EXISTS `AUDIT_LOG` (
  `id` binary(16) NOT NULL,
  `create_time` timestamp,
  `user` varchar(100) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  `log_type` varchar(45) DEFAULT NULL,
  `entity_id` varchar(45),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

/**
If the VARCHAR version of the FEED_ID was added by mistake remove the column.
 */
IF EXISTS(SELECT table_name
            FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_schema = 'kylo'
             AND table_name = 'BATCH_JOB_INSTANCE' and column_name = 'FEED_ID' and lower(DATA_TYPE) = 'varchar') THEN

   ALTER TABLE BATCH_JOB_INSTANCE
             DROP COLUMN FEED_ID;
END IF;

/**
Add the FEED_ID column
 */
IF NOT EXISTS(SELECT table_name
            FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_schema = 'kylo'
             AND table_name = 'BATCH_JOB_INSTANCE' and column_name = 'FEED_ID') then
/** Adds the FEED column to the INSTANCE TABLE */
ALTER TABLE BATCH_JOB_INSTANCE
ADD COLUMN `FEED_ID` BINARY(16) NULL;
end if;

/**
CREATE the table to store the Check data feed refs
 */
CREATE TABLE IF NOT EXISTS FEED_CHECK_DATA_FEEDS (
  `FEED_ID` BINARY(16) NOT NULL COMMENT '',
  `CHECK_DATA_FEED_ID` BINARY(16) NOT NULL COMMENT '',
  PRIMARY KEY (`FEED_ID`, `CHECK_DATA_FEED_ID`));

/**
Set the Feed ID to the respective JOB_INSTANCE table
 */
UPDATE BATCH_JOB_INSTANCE i
INNER JOIN FEED f on f.NAME = i.JOB_NAME
SET i.FEED_ID = f.ID;

END//

delimiter ;

-- Execute the procedure
call update_to_050();

-- Drop the procedure
drop procedure update_to_050;


text:
/*! \file ored/utilities/strike.hpp
    \brief strike description
    \ingroup utilities
*/

#pragma once

#include <ql/types.hpp>

#include <string>

namespace ore {
namespace data {

struct Strike {
    enum class Type { ATM, ATMF, ATM_Offset, Absolute, Delta };
    Type type;
    QuantLib::Real value;
};

//! Convert text to Strike
/*!
\ingroup utilities
*/
Strike parseStrike(const std::string& s);

//! Convert Strike to text
/*!
\ingroup utilities
*/
std::ostream& operator<<(std::ostream& out, const Strike& s);
}
}


text:
.. This work is licensed under a Creative Commons Attribution 4.0 International
.. License.
.. http://creativecommons.org/licenses/by/4.0
.. (c) OPNFV, Ericsson AB and others.

==================
Yardstick Overview
==================

.. toctree::
   :maxdepth: 2

   01-introduction
   02-methodology
   03-architecture
   04-vtc-overview
   05-apexlake_installation
   06-apexlake_api
   07-installation
   08-yardstick_plugin
   09-result-store-InfluxDB
   10-list-of-tcs
   glossary
   references


text:
package org.specs.literate
import scala.xml._
import org.specs.specification._

trait Html extends HtmlFormatting with Wiki
class HtmlFormatter extends HtmlFormatting
trait HtmlFormatting extends WikiFormatter {
  override def escapeHtml(s: String) = s
  override  def format(desc: Elem, examples: Iterable[Example]): Node = {
    val toLoad = "<t>" + setStatus(desc.toString, examples) + "</t>"
    try {
      XML.loadString(toLoad)
    } catch {
      case e => Text(e.getMessage + "\n" + toLoad)
    }
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<style>
	<info>
		<name>gk_eSport</name>
		<author>GavickPro</author>
		<desc>Image Show GK4 style for eSport template.</desc>
		<version>1.0</version>
	</info>
	<config>
		<field type="text" name="image_w" label="Image width" desc="" default="1000" unit="px" />
		<field type="text" name="image_h" label="Image height" desc="" default="550" unit="px" />

		<field type="text" name="thumb_w" label="Thumbnail width" desc="" default="200" unit="px" />
		<field type="text" name="thumb_h" label="Thumbnail height" desc="" default="120" unit="px" />

		<field type="text" name="image_bg" label="Image background color" desc="Slide image background as hexdecimal value" default="#000000" unit="" />

		<field type="text" name="quality" label="Image quality" desc="Quality of images (used in the JPG images) - percentage value between 0 and 100." default="95" unit="%" />

		<field type="switch" name="thumbnails" label="Thumbnails" desc="You can enable showing thumbnails." default="1" class="gk_switch" />
		<field type="select" name="thumbnails_position" label="Thumbnails position" desc="Position of the thumbnails" default="bottom" class="">
			<option value="gkThumbsBottom">Bottom</option>
			<option value="gkThumbsTop">Top</option>
		</field>

		<field type="switch" name="text_block" label="Text block" desc="You can enable showing text block with the slide title." default="1" class="gk_switch" />

		<field type="switch" name="slide_links" label="Slide links" desc="You can enable links in the slides." default="1" class="gk_switch" />

		<field type="select" name="anim_type" label="Animation type" desc="Animation type used in the slideshow" default="gkDrops" class="">
			<option value="gkDrops">Drop animation</option>
			<option value="gkOpacity">Opacity</option>
		</field>

		<field type="text" name="animation_speed" label="Animation speed" desc="Animation speed in miliseconds" default="750" unit="ms" />
		<field type="text" name="animation_interval" label="Animation interval" desc="Animation interval in miliseconds" default="35" unit="ms" />
		<field type="text" name="row_amount" label="Amount of bubble rows" desc="Amount of rows with bubbles" default="4" unit="" />
		<field type="text" name="lvl2_divider" label="Amount of divided bubbles" desc="Amount of bubbles which will be divided to smaller bubbles. It cannot be bigger than total amount of bubbles." default="4" unit="" />
		<field type="text" name="max_anim" label="Max. animations amount" desc="Maximal amount of animations started on the same time." default="5" unit="" />

		<field type="text" name="slide_interval" label="Slide interval" desc="Slide interval in miliseconds" default="5000" unit="ms" />
		<field type="switch" name="autoanimation" label="Autoanimation" desc="Autoanimation of the slides" default="1" class="gk_switch" />
	</config>
</style>


text:
package synitex.backup.rest.dto;

import com.fasterxml.jackson.annotation.JsonProperty;

public class DestinationDto {

    @JsonProperty("id")
    private String id;

    @JsonProperty("name")
    private String name;

    @JsonProperty("type")
    private String type;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}


text:
package org.springframework.cloud.dataflow.core;

/**
 * @author David Turanski
 **/
public class PlatformTaskExecutionInformation {

	/**
	 * The platform instance (account) name.
	 */
	private final String name;

	/**
	 * The platform type name.
	 */
	private final String type;

	/**
	 * The maximum concurrently running task executions allowed.
	 */
	private final int maximumTaskExecutions;

	/**
	 * The current number of running task executions.
	 */
	private final int runningExecutionCount;

	public PlatformTaskExecutionInformation(String name, String type, int maximumTaskExecutions,
			int runningExecutionCount) {
		this.name = name;
		this.type = type;
		this.maximumTaskExecutions = maximumTaskExecutions;
		this.runningExecutionCount = runningExecutionCount;
	}

	public String getName() {
		return name;
	}

	public String getType() {
		return type;
	}

	public int getMaximumTaskExecutions() {
		return maximumTaskExecutions;
	}

	public int getRunningExecutionCount() {
		return runningExecutionCount;
	}
}


text:
@interface WangQiJieXiaoCell ()

@property (nonatomic, weak) UIImageView *iconImageView;
@property (nonatomic, weak) UILabel *zhongJiangNameLabel;
@property (nonatomic, weak) UILabel *ipLabel;
@property (nonatomic, weak) UILabel *luckNumLabel;
@property (nonatomic, weak) UILabel *renCiLabel;

@end

@implementation WangQiJieXiaoCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        [self drawView];
    }

    return self;
}

+ (WangQiJieXiaoCell *)cellWithTableView:(UITableView *)tableView
{
    static NSString *idenifier = @"WangQiJieXiaoCell";
    WangQiJieXiaoCell *cell = [tableView dequeueReusableCellWithIdentifier:idenifier];
    if (cell == nil)
    {
        cell = [[WangQiJieXiaoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idenifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    return cell;
}

- (void)drawView
{
    UIImageView *iconImageView = [[UIImageView alloc] init];
    iconImageView.image = [UIImage imageNamed:@"default"];
    [self.contentView addSubview:iconImageView];

    UILabel *zhongJiangNameLabel = [[UILabel alloc] init];
    zhongJiangNameLabel.font = [UIFont systemFontOfSize:10];
    zhongJiangNameLabel.textColor = [UIColor blackColor];
    zhongJiangNameLabel.text = @"中奖者:王先生";
    [self.contentView addSubview:zhongJiangNameLabel];
    self.zhongJiangNameLabel = zhongJiangNameLabel;

    UILabel *ipLabel = [[UILabel alloc] init];
    ipLabel.font = [UIFont systemFontOfSize:10];
    ipLabel.textColor = [UIColor blackColor];
    ipLabel.text = @"用户IP:00.00.00.00";
    [self.contentView addSubview:ipLabel];
    self.ipLabel = ipLabel;

    UILabel *luckNumLabel = [[UILabel alloc] init];
    luckNumLabel.font = [UIFont systemFontOfSize:10];
    luckNumLabel.textColor = [UIColor blackColor];
    luckNumLabel.text = @"幸运号码:0000000";
    [self.contentView addSubview:luckNumLabel];
    self.luckNumLabel = luckNumLabel;

    UILabel *renCiLabel = [[UILabel alloc] init];
    renCiLabel.font = [UIFont systemFontOfSize:10];
    renCiLabel.textColor = [UIColor blackColor];
    renCiLabel.text = @"本期参与:20人次";
    [self.contentView addSubview:renCiLabel];
    self.renCiLabel = renCiLabel;

    iconImageView.sd_layout
    .leftSpaceToView(self.contentView,15)
    .centerYEqualToView(self.contentView)
    .heightIs(40)
    .widthIs(40);

    zhongJiangNameLabel.sd_layout
    .leftSpaceToView(iconImageView,10)
    .rightSpaceToView(self.contentView,10)
    .topSpaceToView(self.contentView,7)
    .heightIs(15);

    ipLabel.sd_layout
    .leftSpaceToView(iconImageView,10)
    .rightSpaceToView(self.contentView,10)
    .topSpaceToView(zhongJiangNameLabel,5)
    .heightIs(15);

    luckNumLabel.sd_layout
    .leftSpaceToView(iconImageView,10)
    .rightSpaceToView(self.contentView,5)
    .topSpaceToView(ipLabel,10)
    .heightIs(15);

    renCiLabel.sd_layout
    .leftSpaceToView(iconImageView,10)
    .rightSpaceToView(self.contentView,5)
    .topSpaceToView(luckNumLabel,10)
    .heightIs(15);
}

@end


text:
@interface GADMUnityBaseAdNetworkAdapterProxy : NSObject

- (nonnull instancetype)initWithGADMAdNetworkConnector:(nonnull id<GADMAdNetworkConnector>)connector
                                       adapter:(nonnull id<GADMAdNetworkAdapter>)adapter;

@property(nonatomic, weak) id<GADMAdNetworkConnector> connector;
@property(nonatomic, weak) id<GADMAdNetworkAdapter> adapter;

@end


text:
package com.opengamma.financial.analytics.model.equity.varianceswap;

import java.util.Collections;
import java.util.Set;

import com.opengamma.analytics.financial.equity.StaticReplicationDataBundle;
import com.opengamma.analytics.financial.equity.variance.pricing.VarianceSwapStaticReplication;
import com.opengamma.analytics.financial.varianceswap.VarianceSwap;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;

/**
 *
 */
public class EquityVarianceSwapStaticReplicationPresentValueFunction extends EquityVarianceSwapStaticReplicationFunction {
  private static final VarianceSwapStaticReplication PRICER = new VarianceSwapStaticReplication();

  public EquityVarianceSwapStaticReplicationPresentValueFunction() {
    super(ValueRequirementNames.PRESENT_VALUE);
  }

  @Override
  protected Set<ComputedValue> computeValues(final ValueSpecification resultSpec, final FunctionInputs inputs, final VarianceSwap derivative,
      final StaticReplicationDataBundle market) {
    return Collections.singleton(new ComputedValue(resultSpec, PRICER.presentValue(derivative, market)));
  }

}


text:
	#if defined(Net_EXPORTS)
		#define Net_API __declspec(dllexport)
	#else
		#define Net_API __declspec(dllimport)
	#endif
#endif

#if !defined(Net_API)
	#define Net_API
#endif

//
// Automatically link Net library.
//
#if defined(_MSC_VER)
	#if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(Net_EXPORTS)
		#if defined(POCO_DLL)
			#if defined(_DEBUG)
				#pragma comment(lib, "PocoNetd.lib")
			#else
				#pragma comment(lib, "PocoNet.lib")
			#endif
		#else
			#if defined(_DEBUG)
				#pragma comment(lib, "PocoNetmtd.lib")
			#else
				#pragma comment(lib, "PocoNetmt.lib")
			#endif
		#endif
	#endif
#endif

#endif // Net_Net_INCLUDED


text:
module Azure::Web::Mgmt::V2015_04_01
  module Models
    #
    # Address information for domain registration.
    #
    class Address

      include MsRestAzure

      # @return [String] First line of an Address.
      attr_accessor :address1

      # @return [String] The second line of the Address. Optional.
      attr_accessor :address2

      # @return [String] The city for the address.
      attr_accessor :city

      # @return [String] The country for the address.
      attr_accessor :country

      # @return [String] The postal code for the address.
      attr_accessor :postal_code

      # @return [String] The state or province for the address.
      attr_accessor :state

      #
      # Mapper for Address class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'Address',
          type: {
            name: 'Composite',
            class_name: 'Address',
            model_properties: {
              address1: {
                client_side_validation: true,
                required: true,
                serialized_name: 'address1',
                type: {
                  name: 'String'
                }
              },
              address2: {
                client_side_validation: true,
                required: false,
                serialized_name: 'address2',
                type: {
                  name: 'String'
                }
              },
              city: {
                client_side_validation: true,
                required: true,
                serialized_name: 'city',
                type: {
                  name: 'String'
                }
              },
              country: {
                client_side_validation: true,
                required: true,
                serialized_name: 'country',
                type: {
                  name: 'String'
                }
              },
              postal_code: {
                client_side_validation: true,
                required: true,
                serialized_name: 'postalCode',
                type: {
                  name: 'String'
                }
              },
              state: {
                client_side_validation: true,
                required: true,
                serialized_name: 'state',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package org.jnbis.internal.record.writer;

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

import org.jnbis.api.model.record.HighResolutionGrayscaleFingerprint;
import org.jnbis.internal.NistHelper.RecordType;

public class HighResolutionGrayscaleFingerprintWriter extends RecordWriter<HighResolutionGrayscaleFingerprint> {

    @Override
    public RecordType getRecordType() {
        return RecordType.RT4_HR_GS_FINGERPRINT;
    }

    @Override
    public void write(OutputStream out, HighResolutionGrayscaleFingerprint record) throws IOException {
        int imageSize = record.getImageData().length;

        ByteBuffer buffer = ByteBuffer.allocate(18);
        buffer.order(ByteOrder.BIG_ENDIAN);

        /* Header (length) */
        buffer.putInt(buffer.limit() + imageSize);

        /* IDC */
        if (record.getIdc() == null) {
            throw new IllegalArgumentException("IDC is not set");
        }
        buffer.put(record.getIdc().byteValue());

        /* IMP */
        buffer.put((byte) record.getImpressionType());

        /* FGP */
        if (record.getFingerPosition() == null || record.getFingerPosition().length != 6) {
            throw new IllegalArgumentException("There should be 6 FGP values");
        }
        for (int f: record.getFingerPosition()) {
            buffer.put((byte) f);
        }

        /* ISR */
        buffer.put((byte) record.getImageScanningResolution());

        /* HLL */
        buffer.putShort((short) record.getHorizontalLineLength());

        /* VLL */
        buffer.putShort((short) record.getVerticalLineLength());

        /* CGA */
        buffer.put(Byte.parseByte(record.getCompressionAlgorithm()));

        out.write(buffer.array());

        out.write(record.getImageData());
    }

}


text:
import get from 'lodash.get';

import { DisplaySchema } from '../types/styles';

type ImageRatioSchemaType = {
  sm?: string[];
  md?: string[];
  lg?: string[];
  xlg?: string[];
};

const breakpoints = ['sm', 'md', 'lg', 'xlg'];
const horizontalPadding = 12;

export const setDisplaySchema = (schema?: DisplaySchema) => {
  if (schema) {
    let previous = {};
    return breakpoints.reduce((acc: DisplaySchema, breakpoint: string) => {
      const current = { ...previous, ...get(schema, breakpoint) };
      previous = current;
      return { ...acc, [breakpoint]: current };
    }, {});
  }

  return;
};

export const getImageRatioSchema = (schema?: DisplaySchema) => {
  if (!schema) {
    return {};
  }

  let previous: string;
  return Object.entries(schema).reduce(
    (acc: ImageRatioSchemaType, [key, value]) => {
      const ratio = get(value, 'imageRatio', previous);
      previous = ratio;
      return ratio && !get(value, 'isImageHidden')
        ? { ...acc, [ratio]: [...get(acc, ratio, []), key] }
        : acc;
    },
    {}
  );
};

export const isSideBySide = (breakpoint: string, schema?: DisplaySchema) =>
  get(get(schema, breakpoint), 'isSideBySide') === true;

export const isImageHidden = (breakpoint: string, schema?: DisplaySchema) =>
  get(get(schema, breakpoint), 'isImageHidden') === true;

export const isCentered = (breakpoint: string, schema?: DisplaySchema) =>
  get(get(schema, breakpoint), 'isCentered') === true;

const calculateSlotPadding = (numberOfColumns: number) =>
  ((numberOfColumns * 2 - 2) * horizontalPadding) / numberOfColumns;

export const calculateSlotWidth = (
  widthAsPercent: number,
  numberOfColumns: number
) => `calc(${widthAsPercent}% - ${calculateSlotPadding(numberOfColumns)}px)`;


text:
const _ = require('lodash');
const pluralize = require('pluralize');
const { createFaker } = require('./faker');
const { parseLiquibaseChangelogDate } = require('./liquibase');
const { entityDefaultConfig } = require('../generators/generator-defaults');
const { stringHashCode } = require('../generators/utils');
const { fieldToReference } = require('./field');
const { PaginationTypes, ServiceTypes } = require('../jdl/jhipster/entity-options');
const { GATEWAY, MICROSERVICE } = require('../jdl/jhipster/application-types');
const { MapperTypes } = require('../jdl/jhipster/entity-options');
const { OAUTH2 } = require('../jdl/jhipster/authentication-types');
const { CommonDBTypes } = require('../jdl/jhipster/field-types');

const { BOOLEAN, LONG, STRING, UUID } = CommonDBTypes;
const { MAPSTRUCT } = MapperTypes;
const { PAGINATION, INFINITE_SCROLL } = PaginationTypes;
const { SERVICE_IMPL } = ServiceTypes;
const NO_SERVICE = ServiceTypes.NO;
const NO_PAGINATION = PaginationTypes.NO;
const NO_MAPPER = MapperTypes.NO;

const BASE_TEMPLATE_DATA = {
  primaryKey: undefined,
  skipUiGrouping: false,
  haveFieldWithJavadoc: false,
  existingEnum: false,
  searchEngine: false,

  fieldsContainDate: false,
  fieldsContainInstant: false,
  fieldsContainUUID: false,
  fieldsContainZonedDateTime: false,
  fieldsContainDuration: false,
  fieldsContainLocalDate: false,
  fieldsContainBigDecimal: false,
  fieldsContainBlob: false,
  fieldsContainImageBlob: false,
  fieldsContainTextBlob: false,
  fieldsContainBlobOrImage: false,
  validation: false,
  fieldsContainOwnerManyToMany: false,
  fieldsContainNoOwnerOneToOne: false,
  fieldsContainOwnerOneToOne: false,
  fieldsContainOneToMany: false,
  fieldsContainManyToOne: false,
  fieldsContainEmbedded: false,
  fieldsIsReactAvField: false,

  get otherRelationships() {
    return [];
  },

  get enums() {
    return [];
  },
  // these variable hold field and relationship names for question options during update
  get fieldNameChoices() {
    return [];
  },
  get blobFields() {
    return [];
  },
  get differentTypes() {
    return [];
  },
  get differentRelationships() {
    return [];
  },
  get i18nToLoad() {
    return [];
  },
};

function _derivedProperties(entityWithConfig) {
  const pagination = entityWithConfig.pagination;
  const dto = entityWithConfig.dto;
  const service = entityWithConfig.service;
  _.defaults(entityWithConfig, {
    paginationPagination: pagination === PAGINATION,
    paginationInfiniteScroll: pagination === INFINITE_SCROLL,
    paginationNo: pagination === NO_PAGINATION,
    dtoMapstruct: dto === MAPSTRUCT,
    serviceImpl: service === SERVICE_IMPL,
    serviceNo: service === NO_SERVICE,
  });
}

function prepareEntityForTemplates(entityWithConfig, generator) {
  const entityName = entityWithConfig.name;
  _.defaults(entityWithConfig, entityDefaultConfig, BASE_TEMPLATE_DATA);

  entityWithConfig.changelogDateForRecent = parseLiquibaseChangelogDate(entityWithConfig.changelogDate);
  entityWithConfig.faker = entityWithConfig.faker || createFaker(generator.jhipsterConfig.nativeLanguage);
  entityWithConfig.resetFakerSeed = (suffix = '') =>
    entityWithConfig.faker.seed(stringHashCode(entityWithConfig.name.toLowerCase() + suffix));
  entityWithConfig.resetFakerSeed();

  entityWithConfig.entityAngularJSSuffix = entityWithConfig.angularJSSuffix;
  if (entityWithConfig.entityAngularJSSuffix && !entityWithConfig.entityAngularJSSuffix.startsWith('-')) {
    entityWithConfig.entityAngularJSSuffix = `-${entityWithConfig.entityAngularJSSuffix}`;
  }

  entityWithConfig.useMicroserviceJson = entityWithConfig.useMicroserviceJson || entityWithConfig.microserviceName !== undefined;
  if (generator.jhipsterConfig.applicationType === GATEWAY && entityWithConfig.useMicroserviceJson) {
    if (!entityWithConfig.microserviceName) {
      throw new Error('Microservice name for the entity is not found. Entity cannot be generated!');
    }
    entityWithConfig.microserviceAppName = generator.getMicroserviceAppName(entityWithConfig.microserviceName);
    entityWithConfig.skipServer = true;
  }

  _.defaults(entityWithConfig, {
    entityNameCapitalized: _.upperFirst(entityName),
    entityClass: _.upperFirst(entityName),
    entityInstance: _.lowerFirst(entityName),
    entityTableName: generator.getTableName(entityName),
    entityNamePlural: pluralize(entityName),
  });

  const dto = entityWithConfig.dto === MAPSTRUCT;
  if (dto) {
    _.defaults(entityWithConfig, {
      dtoClass: generator.asDto(entityWithConfig.entityClass),
      dtoInstance: generator.asDto(entityWithConfig.entityInstance),
    });
  }

  _.defaults(entityWithConfig, {
    persistClass: generator.asEntity(entityWithConfig.entityClass),
    persistInstance: generator.asEntity(entityWithConfig.entityInstance),
  });

  _.defaults(entityWithConfig, {
    restClass: dto ? entityWithConfig.dtoClass : entityWithConfig.persistClass,
    restInstance: dto ? entityWithConfig.dtoInstance : entityWithConfig.persistInstance,
  });

  _.defaults(entityWithConfig, {
    entityNamePluralizedAndSpinalCased: _.kebabCase(entityWithConfig.entityNamePlural),
    entityClassPlural: _.upperFirst(entityWithConfig.entityNamePlural),
    entityInstancePlural: _.lowerFirst(entityWithConfig.entityNamePlural),
  });

  _.defaults(entityWithConfig, {
    // Implement i18n variant ex: 'male', 'female' when applied
    entityI18nVariant: 'default',
    entityClassHumanized: _.startCase(entityWithConfig.entityNameCapitalized),
    entityClassPluralHumanized: _.startCase(entityWithConfig.entityClassPlural),
  });

  entityWithConfig.entityFileName = _.kebabCase(
    entityWithConfig.entityNameCapitalized + _.upperFirst(entityWithConfig.entityAngularJSSuffix)
  );
  entityWithConfig.entityFolderName = generator.getEntityFolderName(entityWithConfig.clientRootFolder, entityWithConfig.entityFileName);
  entityWithConfig.entityModelFileName = entityWithConfig.entityFolderName;
  entityWithConfig.entityParentPathAddition = generator.getEntityParentPathAddition(entityWithConfig.clientRootFolder);
  entityWithConfig.entityPluralFileName = entityWithConfig.entityNamePluralizedAndSpinalCased + entityWithConfig.entityAngularJSSuffix;
  entityWithConfig.entityServiceFileName = entityWithConfig.entityFileName;

  entityWithConfig.entityAngularName = entityWithConfig.entityClass + generator.upperFirstCamelCase(entityWithConfig.entityAngularJSSuffix);
  entityWithConfig.entityAngularNamePlural = pluralize(entityWithConfig.entityAngularName);
  entityWithConfig.entityReactName = entityWithConfig.entityClass + generator.upperFirstCamelCase(entityWithConfig.entityAngularJSSuffix);

  entityWithConfig.entityApiUrl = entityWithConfig.entityNamePluralizedAndSpinalCased;
  entityWithConfig.entityStateName = _.kebabCase(entityWithConfig.entityAngularName);
  entityWithConfig.entityUrl = entityWithConfig.entityStateName;

  entityWithConfig.entityTranslationKey = entityWithConfig.clientRootFolder
    ? _.camelCase(`${entityWithConfig.clientRootFolder}-${entityWithConfig.entityInstance}`)
    : entityWithConfig.entityInstance;
  entityWithConfig.entityTranslationKeyMenu = _.camelCase(
    entityWithConfig.clientRootFolder
      ? `${entityWithConfig.clientRootFolder}-${entityWithConfig.entityStateName}`
      : entityWithConfig.entityStateName
  );

  entityWithConfig.differentTypes.push(entityWithConfig.entityClass);
  entityWithConfig.i18nToLoad.push(entityWithConfig.entityInstance);
  entityWithConfig.i18nKeyPrefix = `${entityWithConfig.frontendAppName}.${entityWithConfig.entityTranslationKey}`;
  entityWithConfig.i18nAlertHeaderPrefix = entityWithConfig.i18nKeyPrefix;
  if (entityWithConfig.microserviceAppName) {
    entityWithConfig.i18nAlertHeaderPrefix = `${entityWithConfig.microserviceAppName}.${entityWithConfig.entityTranslationKey}`;
  }

  const hasBuiltInUserField = entityWithConfig.relationships.some(relationship => generator.isBuiltInUser(relationship.otherEntityName));
  entityWithConfig.saveUserSnapshot =
    entityWithConfig.applicationType === MICROSERVICE &&
    entityWithConfig.authenticationType === OAUTH2 &&
    hasBuiltInUserField &&
    entityWithConfig.dto === NO_MAPPER;

  entityWithConfig.generateFakeData = type => {
    const fieldsToGenerate =
      type === 'cypress' ? entityWithConfig.fields.filter(field => !field.id || !field.autoGenerate) : entityWithConfig.fields;
    const fieldEntries = fieldsToGenerate.map(field => {
      const fieldData = field.generateFakeData(type);
      if (!field.nullable && fieldData === null) return undefined;
      return [field.fieldName, fieldData];
    });
    const withError = fieldEntries.find(entry => !entry);
    if (withError) {
      generator.warning(`Error generating a full sample for entity ${entityName}`);
      return undefined;
    }
    return Object.fromEntries(fieldEntries);
  };
  _derivedProperties(entityWithConfig);

  return entityWithConfig;
}

function derivedPrimaryKeyProperties(primaryKey) {
  _.defaults(primaryKey, {
    hasUUID: primaryKey.fields && primaryKey.fields.some(field => field.fieldType === UUID),
    hasLong: primaryKey.fields && primaryKey.fields.some(field => field.fieldType === LONG),
    typeUUID: primaryKey.type === UUID,
    typeString: primaryKey.type === STRING,
    typeLong: primaryKey.type === LONG,
    typeNumeric: !primaryKey.composite && primaryKey.fields[0].fieldTypeNumeric,
  });
}

function prepareEntityPrimaryKeyForTemplates(entityWithConfig, generator, enableCompositeId = true) {
  const idFields = entityWithConfig.fields.filter(field => field.id);
  const idRelationships = entityWithConfig.relationships.filter(relationship => relationship.id);
  let idCount = idFields.length + idRelationships.length;

  if (idCount === 0) {
    let idField = entityWithConfig.fields.find(field => field.fieldName === 'id');
    if (idField) {
      idField.id = true;
    } else {
      idField = {
        fieldName: 'id',
        id: true,
        fieldNameHumanized: 'ID',
        fieldTranslationKey: 'global.field.id',
        autoGenerate: true,
      };
      entityWithConfig.fields.unshift(idField);
    }
    idFields.push(idField);
    idCount++;
  } else if (idRelationships.length > 0) {
    idRelationships.forEach(relationship => {
      // deprecated property
      relationship.useJPADerivedIdentifier = true;
      // relationships id data are not available at this point, so calculate it when needed.
      relationship.derivedPrimaryKey = {
        get derivedFields() {
          return relationship.otherEntity.primaryKey.fields.map(field => ({
            originalField: field,
            ...field,
            derived: true,
            derivedEntity: relationship.otherEntity,
            jpaGeneratedValue: false,
            liquibaseAutoIncrement: false,
            // Mapsid is generated by relationship select
            autoGenerate: true,
            readonly: true,
            get derivedPath() {
              if (field.derivedPath) {
                if (relationship.otherEntity.primaryKey.derived) {
                  return [relationship.relationshipName, ...field.derivedPath.splice(1)];
                }
                return [relationship.relationshipName, ...field.derivedPath];
              }
              return [relationship.relationshipName, field.fieldName];
            },
            get path() {
              return [relationship.relationshipName, ...field.path];
            },
            get fieldName() {
              return idCount === 1 ? field.fieldName : `${relationship.relationshipName}${field.fieldNameCapitalized}`;
            },
            get fieldNameCapitalized() {
              return idCount === 1
                ? field.fieldNameCapitalized
                : `${relationship.relationshipNameCapitalized}${field.fieldNameCapitalized}`;
            },
            get columnName() {
              return idCount === 1 ? field.columnName : `${generator.getColumnName(relationship.relationshipName)}_${field.columnName}`;
            },
            get reference() {
              return fieldToReference(entityWithConfig, this);
            },
            get relationshipsPath() {
              return [relationship, ...field.relationshipsPath];
            },
          }));
        },
      };
    });
  }

  if (idCount === 1 && idRelationships.length === 1) {
    const relationshipId = idRelationships[0];
    // One-To-One relationships with id uses @MapsId.
    // Almost every info is taken from the parent, except some info like autoGenerate and derived.
    // calling fieldName as id is for backward compatibility, in the future we may want to prefix it with relationship name.
    entityWithConfig.primaryKey = {
      fieldName: 'id',
      derived: true,
      // MapsId copy the id from the relationship.
      autoGenerate: true,
      get fields() {
        return this.derivedFields;
      },
      get derivedFields() {
        return relationshipId.derivedPrimaryKey.derivedFields;
      },
      get ownFields() {
        return relationshipId.otherEntity.primaryKey.ownFields;
      },
      relationships: idRelationships,
      get name() {
        return relationshipId.otherEntity.primaryKey.name;
      },
      get nameCapitalized() {
        return relationshipId.otherEntity.primaryKey.nameCapitalized;
      },
      get type() {
        return relationshipId.otherEntity.primaryKey.type;
      },
      get tsType() {
        return relationshipId.otherEntity.primaryKey.tsType;
      },
      get composite() {
        return relationshipId.otherEntity.primaryKey.composite;
      },
      get ids() {
        return this.fields.map(field => fieldToId(field));
      },
    };
  } else {
    const composite = enableCompositeId ? idCount > 1 : false;
    let primaryKeyName;
    let primaryKeyType;
    if (composite) {
      primaryKeyName = 'id';
      primaryKeyType = `${entityWithConfig.entityClass}Id`;
    } else {
      const idField = idFields[0];
      idField.dynamic = false;
      // Allow ids type to be empty and fallback to default type for the database.
      if (!idField.fieldType) {
        idField.fieldType = generator.getPkType(entityWithConfig.databaseType);
      }
      primaryKeyName = idField.fieldName;
      primaryKeyType = idField.fieldType;
    }

    entityWithConfig.primaryKey = {
      derived: false,
      name: primaryKeyName,
      nameCapitalized: _.upperFirst(primaryKeyName),
      type: primaryKeyType,
      tsType: generator.getTypescriptKeyType(primaryKeyType),
      composite,
      relationships: idRelationships,
      // Fields declared in this entity
      ownFields: idFields,
      // Fields declared and inherited
      get fields() {
        return [...this.ownFields, ...this.derivedFields];
      },
      get autoGenerate() {
        return this.composite ? false : this.fields[0].autoGenerate;
      },
      // Fields inherited from id relationships.
      get derivedFields() {
        return this.relationships.map(rel => rel.derivedPrimaryKey.derivedFields).flat();
      },
      get ids() {
        return this.fields.map(field => fieldToId(field));
      },
    };
  }
  return entityWithConfig;
}

function fieldToId(field) {
  return {
    field,
    get name() {
      return field.fieldName;
    },
    get nameCapitalized() {
      return field.fieldNameCapitalized;
    },
    get nameDotted() {
      return field.derivedPath ? field.derivedPath.join('.') : field.fieldName;
    },
    get nameDottedAsserted() {
      return field.derivedPath ? `${field.derivedPath.join('!.')}!` : `${field.fieldName}!`;
    },
    get setter() {
      return `set${this.nameCapitalized}`;
    },
    get getter() {
      return (field.fieldType === BOOLEAN ? 'is' : 'get') + this.nameCapitalized;
    },
    get autoGenerate() {
      return !!field.autoGenerate;
    },
    get relationshipsPath() {
      return field.relationshipsPath;
    },
  };
}

/**
 * Copy required application config into entity.
 * Some entity features are related to the backend instead of the current app.
 * This allows to entities files based on the backend features.
 *
 * @param {Object} entity - entity to copy the config into.
 * @param {Object} config - config object.
 * @returns {Object} the entity parameter for chaining.
 */
function loadRequiredConfigIntoEntity(entity, config) {
  _.defaults(entity, {
    databaseType: config.databaseType,
    prodDatabaseType: config.prodDatabaseType,
    skipUiGrouping: config.skipUiGrouping,
    searchEngine: config.searchEngine,
    jhiPrefix: config.jhiPrefix,
    authenticationType: config.authenticationType,
    reactive: config.reactive,
  });
  return entity;
}

module.exports = {
  prepareEntityForTemplates,
  prepareEntityPrimaryKeyForTemplates,
  loadRequiredConfigIntoEntity,
  derivedPrimaryKeyProperties,
};


text:
<?php

 namespace Album\Model;

 use Zend\Db\TableGateway\TableGateway;

 class AlbumTable
 {
     protected $tableGateway;

     public function __construct(TableGateway $tableGateway)
     {
         $this->tableGateway = $tableGateway;
     }

     public function fetchAll(Array $columns = array('id','title', 'artist'))
     {
         $sqlSelect = $this->tableGateway->getSql()->select();
         $sqlSelect->columns($columns);
         $sqlSelect->join('genres', 'album.genre_id = genres.id', array('genre'=>'name'), 'left');

         $resultSet = $this->tableGateway->selectWith($sqlSelect);
         return $resultSet;
     }

     public function getAlbum($id)
     {
         $id  = (int) $id;
         $rowset = $this->tableGateway->select(array('id' => $id));
         $row = $rowset->current();
         if (!$row) {
             throw new \Exception("Could not find row $id");
         }
         return $row;
     }

     public function saveAlbum(Album $album)
     {
         $data = array(
             'artist' => $album->artist,
             'title'  => $album->title,
             'genre_id'  => $album->genre_id,
         );

         $id = (int) $album->id;
         if ($id == 0) {
             $this->tableGateway->insert($data);
         } else {
             if ($this->getAlbum($id)) {
                 $this->tableGateway->update($data, array('id' => $id));
             } else {
                 throw new \Exception('Album id does not exist');
             }
         }
     }

     public function deleteAlbum($id)
     {
         $this->tableGateway->delete(array('id' => (int) $id));
     }
 }


text: function bar(e){try{foo()}catch(t){alert("Exception caught (foo not defined)")}alert(e)}bar(10)


text:
[sqlτyped](https://github.com/jonifreeman/sqltyped) - a macro which infers Scala types by analysing SQL statements.

This release adds following new features and improvements:

## Support for multiple compile time datasources

In Scala code bring correct configuration into scope by:

   implicit object postgresql extends ConfigurationName

The above configuration reads following system properties to establish a connection to database at compile time:

    sqltyped.postgresql.url
    sqltyped.postgresql.driver
    sqltyped.postgresql.username
    sqltyped.postgresql.password

## Support for collections in IN-clause

JDBC does not have a standard way to support queries like:

    select age from person where name in (?)

where parameter is a collection of values. Some drivers support PreparedStatement#setArray(), MySQL implicitely supports this through PreparedStatement#setObject() etc.

This version adds following support:

### MySQL

    select age from person where name in (?)

is typed as

    Seq[String] => List[Int]

### PostgreSQL

    select age from person where name = any(?)

is typed as

    Seq[String] => List[Int]

## MySQL type conversion support

    scala> sql("select convert(age, char(10)) from person").apply
    res0: List[String] = List("36", "14")

## Results to CSV conversion

    scala> val rows = sql("select name as fname, age from person limit 100").apply.values
    scala> CSV.fromList(rows)
    res1: String =
    "joe","36"
    "moe","14"

## Results to untyped List conversion

   scala> val rows = sql("select name, age from person limit 100").apply
   scala> Record.toTupleLists(rows)
   res2: List[List[(String, Any)]] = List(List(("name", "joe"), ("age", 36)), List(("name", "moe"), ("age", 14)))

## Improved nullability analysis

In previous versions, if a selected column was nullable it was always boxed to Option[A]. However, if the column is restricted with `WHERE x IS NOT NULL` and the expression contains only 'and' operators then it obviously can't be null and boxing is unnecessary.