text:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { getComments, addComment } from '../actions/comment_actions'
import { sortComments } from '../actions/sort_actions'
import NavTabs from './NavTabs'
import PostContainer from './PostContainer'
import CommentContainer from './CommentContainer'
import sortBy from 'sort-by'
import _ from 'lodash'
import { Modal } from 'react-bootstrap'
import { guid } from '../utils/helpers'

class PostView extends Component {
  state = {
    addCommentModalOpen: false,
    addComment: {
      author: '',
      body: '',
    }
  }

  componentDidMount() {
    this.props.getComments(this.props.currentPostId)
  }

  openAddCommentModal = () => {
    this.setState(() => ({
      addCommentModalOpen: true,
      addComment: {
        author: '',
        body: '',
      }
    }))
  }

  updateAddCommentAuthor = (newAuthor) => {
    this.setState({
      addComment: {
        ...this.state.addComment,
        author: newAuthor
      }
    })
  }

  updateAddCommentBody = (newBody) => {
    this.setState({
      addComment: {
        ...this.state.addComment,
        body: newBody
      }
    })
  }

  submitAddComment = (comment) => {
    const newComment = {
      ...comment,
      id: guid(),
      parentId: this.props.currentPostId,
      timestamp: Date.now()
    }
    this.props.addComment(newComment)
    this.closeAddCommentModal()
  }

  closeAddCommentModal = () => {
    this.setState(() => ({ addCommentModalOpen: false }))
  }

  onSort = () => {
    this.props.sortComments()
  }

  render() {
    const { currentCategory, currentPostId, comments, sort, history } = this.props
    const { addCommentModalOpen, addComment } = this.state

    return (

Readable

        <NavTabs currentCategory={currentCategory} />

          <PostContainer postId={currentPostId} history={history}/>

            <big>Comments ({comments.length})</big>

            <button onClick={()=>this.openAddCommentModal()}>[ + ]</button>
            <button onClick={()=>this.onSort()}>[ Sort by: {sort.comments} ]</button>

          {comments.map((comment) => (
            <CommentContainer key={comment.id} commentId={comment.id}/>
          ))}

        <Modal
          className='static-modal'
          show={addCommentModalOpen}
        >
          <Modal.Header>
            <input
              className='input-title'
              type="text"
              value={addComment.author}
              placeholder='Comment Author'
              onChange={(e) => this.updateAddCommentAuthor(e.target.value)}
            />
          </Modal.Header>
          <Modal.Body>
            <input
              type="text"
              value={addComment.body}
              placeholder='Comment Content'
              onChange={(e) => this.updateAddCommentBody(e.target.value)}
            />
          </Modal.Body>
          <Modal.Footer>
            <button onClick={()=>this.submitAddComment(addComment)}>Save</button>
            <button onClick={this.closeAddCommentModal}>Close</button>
          </Modal.Footer>
        </Modal>

    )
  }
}

function mapStateToProps ({ comments, sort }, { match : { params : { category, id }}}) {
  const currentCategory = category
  const currentPostId = id
  const showingComments = _.values(comments).sort(sortBy(sort.comments))
  return {
    currentCategory: currentCategory,
    currentPostId: currentPostId,
    comments: showingComments,
    sort: sort
  }
}

function mapDispatchToProps (dispatch) {
  return {
    getComments: (parentId) => dispatch(getComments(parentId)),
    addComment: (body) => dispatch(addComment(body)),
    sortComments: () => dispatch(sortComments()),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(PostView)


text:
/* These apply across all breakpoints because they are outside of a media query */
/* Make the labels light gray all caps across the board */
.movie-list thead th,
.movie-list tbody th .ui-table-cell-label,
.movie-list tbody td .ui-table-cell-label {
    text-transform: uppercase;
    font-size: .7em;
    color: rgba(0,0,0,0.5);
    font-weight: normal;
}
/* White bg, large blue text for rank and title */
.movie-list tbody th {
    font-size: 1.2em;
    background-color: #fff;
    color: #77bbff;
    text-align: center;
}
/*  Add a bit of extra left padding for the title */
.movie-list tbody td.title {
    padding-left: .8em;
}
/* Add strokes */
.movie-list thead th {
    border-bottom: 1px solid #d6d6d6; /* non-RGBA fallback */
    border-bottom: 1px solid rgba(0,0,0,.1);
}
.movie-list tbody th,
.movie-list tbody td {
    border-bottom: 1px solid #e6e6e6; /* non-RGBA fallback  */
    border-bottom: 1px solid rgba(0,0,0,.05);
}
/*  Custom stacked styles for mobile sizes */
/*  Use a max-width media query so we don't have to undo these styles */
@media (max-width: 40em) {
    /*  Negate the margin between sections */
    .movie-list tbody th {
        margin-top: 0;
        text-align: left;
    }
    /*  White bg, large blue text for rank and title */
    .movie-list tbody th,
    .movie-list tbody td.title {
        display: block;
        font-size: 1.2em;
        line-height: 110%;
        padding: .5em .5em;
        background-color: #fff;
        color: #77bbff;
        -moz-box-shadow: 0 1px 6px rgba(0,0,0,.1);
        -webkit-box-shadow: 0 1px 6px rgba(0,0,0,.1);
        box-shadow: 0 1px 6px rgba(0,0,0,.1);
    }
    /*  Hide labels for rank and title */
    .movie-list tbody th .ui-table-cell-label,
    .movie-list tbody td.title .ui-table-cell-label {
        display: none;
    }
    /*  Position the title next to the rank, pad to the left */
    .movie-list tbody td.title {
        margin-top: -2.1em;
        padding-left: 2.2em;
        border-bottom: 1px solid rgba(0,0,0,.15);
    }
    /*  Make the data bold */
    .movie-list th,
    .movie-list td {
        font-weight: bold;
    }
    /* Make the label elements a percentage width */
    .movie-list td .ui-table-cell-label,
    .movie-list th .ui-table-cell-label {
        min-width: 20%;
    }
}
/* Media query to show as a standard table at wider widths */
@media ( min-width: 40em ) {
    /* Show the table header rows */
    .movie-list td,
    .movie-list th,
    .movie-list tbody th,
    .movie-list tbody td,
    .movie-list thead td,
    .movie-list thead th {
        display: table-cell;
        margin: 0;
    }
    /* Hide the labels in each cell */
    .movie-list td .ui-table-cell-label,
    .movie-list th .ui-table-cell-label {
        display: none;
    }
}
/* Hack to make IE9 and WP7.5 treat cells like block level elements */
/* Applied in a max-width media query up to the table layout breakpoint so we don't need to negate this */
@media ( max-width: 40em ) {
    .movie-list td,
    .movie-list th {
        width: 100%;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        float: left;
        clear: left;
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
// MessagePack for Java
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//
package org.msgpack.core.buffer;

import java.nio.ByteBuffer;

import static org.msgpack.core.Preconditions.checkArgument;

/**
 * Universal MessageBuffer implementation supporting Java6 and Android.
 * This buffer always uses ByteBuffer-based memory access
 */
public class MessageBufferU
        extends MessageBuffer
{
    private final ByteBuffer wrap;

    MessageBufferU(byte[] arr, int offset, int length)
    {
        super(arr, offset, length);
        this.wrap = ByteBuffer.wrap(arr, offset, length).slice();
    }

    MessageBufferU(ByteBuffer bb)
    {
        super(bb);
        this.wrap = bb.slice();
    }

    private MessageBufferU(Object base, long address, int length, ByteBuffer wrap)
    {
        super(base, address, length);
        this.wrap = wrap;
    }

    @Override
    public MessageBufferU slice(int offset, int length)
    {
        if (offset == 0 && length == size()) {
            return this;
        }
        else {
            checkArgument(offset + length <= size());
            try {
                wrap.position(offset);
                wrap.limit(offset + length);
                return new MessageBufferU(base, address + offset, length, wrap.slice());
            }
            finally {
                resetBufferPosition();
            }
        }
    }

    private void resetBufferPosition()
    {
        wrap.position(0);
        wrap.limit(size);
    }

    @Override
    public byte getByte(int index)
    {
        return wrap.get(index);
    }

    @Override
    public boolean getBoolean(int index)
    {
        return wrap.get(index) != 0;
    }

    @Override
    public short getShort(int index)
    {
        return wrap.getShort(index);
    }

    @Override
    public int getInt(int index)
    {
        return wrap.getInt(index);
    }

    @Override
    public float getFloat(int index)
    {
        return wrap.getFloat(index);
    }

    @Override
    public long getLong(int index)
    {
        return wrap.getLong(index);
    }

    @Override
    public double getDouble(int index)
    {
        return wrap.getDouble(index);
    }

    @Override
    public void getBytes(int index, int len, ByteBuffer dst)
    {
        try {
            wrap.position(index);
            wrap.limit(index + len);
            dst.put(wrap);
        }
        finally {
            resetBufferPosition();
        }
    }

    @Override
    public void putByte(int index, byte v)
    {
        wrap.put(index, v);
    }

    @Override
    public void putBoolean(int index, boolean v)
    {
        wrap.put(index, v ? (byte) 1 : (byte) 0);
    }

    @Override
    public void putShort(int index, short v)
    {
        wrap.putShort(index, v);
    }

    @Override
    public void putInt(int index, int v)
    {
        wrap.putInt(index, v);
    }

    @Override
    public void putFloat(int index, float v)
    {
        wrap.putFloat(index, v);
    }

    @Override
    public void putLong(int index, long l)
    {
        wrap.putLong(index, l);
    }

    @Override
    public void putDouble(int index, double v)
    {
        wrap.putDouble(index, v);
    }

    @Override
    public ByteBuffer sliceAsByteBuffer(int index, int length)
    {
        try {
            wrap.position(index);
            wrap.limit(index + length);
            return wrap.slice();
        }
        finally {
            resetBufferPosition();
        }
    }

    @Override
    public ByteBuffer sliceAsByteBuffer()
    {
        return sliceAsByteBuffer(0, size);
    }

    @Override
    public void getBytes(int index, byte[] dst, int dstOffset, int length)
    {
        try {
            wrap.position(index);
            wrap.get(dst, dstOffset, length);
        }
        finally {
            resetBufferPosition();
        }
    }

    @Override
    public void putByteBuffer(int index, ByteBuffer src, int len)
    {
        assert (len <= src.remaining());

        if (src.hasArray()) {
            putBytes(index, src.array(), src.position() + src.arrayOffset(), len);
            src.position(src.position() + len);
        }
        else {
            int prevSrcLimit = src.limit();
            try {
                src.limit(src.position() + len);
                wrap.position(index);
                wrap.put(src);
            }
            finally {
                src.limit(prevSrcLimit);
            }
        }
    }

    @Override
    public void putBytes(int index, byte[] src, int srcOffset, int length)
    {
        try {
            wrap.position(index);
            wrap.put(src, srcOffset, length);
        }
        finally {
            resetBufferPosition();
        }
    }

    @Override
    public void copyTo(int index, MessageBuffer dst, int offset, int length)
    {
        try {
            wrap.position(index);
            dst.putByteBuffer(offset, wrap, length);
        }
        finally {
            resetBufferPosition();
        }
    }

    @Override
    public void putMessageBuffer(int index, MessageBuffer src, int srcOffset, int len)
    {
        putByteBuffer(index, src.sliceAsByteBuffer(srcOffset, len), len);
    }

    @Override
    public byte[] toByteArray()
    {
        byte[] b = new byte[size()];
        getBytes(0, b, 0, b.length);
        return b;
    }
}


text:
/* setgrp.c - by Michael Haardt. Set the gid if possible
 * Added a bit more error recovery/reporting - poe
 * Vesa Roukonen added code for asking password */

/* 1999-02-22 Arkadiusz Miśkiewicz <misiek@pld.ORG.PL>
 * - added Native Language Support
 */

#include <errno.h>
#include <getopt.h>
#include <grp.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

#ifdef HAVE_CRYPT_H
# include <crypt.h>
#endif

#ifdef HAVE_GETSGNAM
# include <gshadow.h>
#endif

#include "c.h"
#include "closestream.h"
#include "nls.h"
#include "pathnames.h"
#include "xalloc.h"

static char *xgetpass(FILE *input, const char *prompt)
{
	char *pass = NULL;
	struct termios saved, no_echo;
	const int fd = fileno(input);
	size_t dummy = 0;
	ssize_t len;

	fputs(prompt, stdout);
	if (isatty(fd)) {
		/* disable echo */
		tcgetattr(fd, &saved);
		no_echo = saved;
		no_echo.c_lflag &= ~ECHO;
		no_echo.c_lflag |= ECHONL;
		if (tcsetattr(fd, TCSANOW, &no_echo))
			err(EXIT_FAILURE, _("could not set terminal attributes"));
	}
	len = getline(&pass, &dummy, input);
	if (isatty(fd))
		/* restore terminal */
		if (tcsetattr(fd, TCSANOW, &saved))
			err(EXIT_FAILURE, _("could not set terminal attributes"));
	if (len < 0)
		err(EXIT_FAILURE, _("getline() failed"));
	if (0 < len && *(pass + len - 1) == '\n')
		*(pass + len - 1) = '\0';
	return pass;
}

/* Ensure memory is set to value c without compiler optimization getting
 * into way that could happen with memset(3). */
static int memset_s(void *v, size_t sz, const int c)
{
	volatile unsigned char *p = v;

	if (v == NULL)
		return EINVAL;
	while (sz--)
		*p++ = c;
	return 0;
}

/* try to read password from gshadow */
static char *get_gshadow_pwd(const char *groupname)
{
#ifdef HAVE_GETSGNAM
	struct sgrp *sgrp;

	sgrp = getsgnam(groupname);
	return sgrp ? xstrdup(sgrp->sg_passwd) : NULL;
#else
	char buf[BUFSIZ];
	char *pwd = NULL;
	FILE *f;

	if (groupname == NULL || *groupname == '\0')
		return NULL;

	f = fopen(_PATH_GSHADOW, "r");
	if (!f)
		return NULL;

	while (fgets(buf, sizeof buf, f)) {
		char *cp = strchr(buf, ':');
		if (!cp)
			/* any junk in gshadow? */
			continue;
		*cp = '\0';
		if (strcmp(buf, groupname) == 0) {
			if (cp - buf >= BUFSIZ)
				/* only group name on line */
				break;
			pwd = cp + 1;
			if ((cp = strchr(pwd, ':')) && pwd == cp + 1)
				/* empty password */
				pwd = NULL;
			else if (cp)
				*cp = '\0';
			break;
		}
	}
	fclose(f);
	return pwd ? xstrdup(pwd) : NULL;
#endif	/* HAVE_GETSGNAM */
}

static int allow_setgid(const struct passwd *pe, const struct group *ge)
{
	char **look;
	int notfound = 1;
	char *pwd, *xpwd;

	if (getuid() == 0)
		/* root may do anything */
		return TRUE;
	if (ge->gr_gid == pe->pw_gid)
		/* You can switch back to your default group */
		return TRUE;

	look = ge->gr_mem;
	while (*look && (notfound = strcmp(*look++, pe->pw_name))) ;

	if (!notfound)
		/* member of group => OK */
		return TRUE;

	/* Ask for password. Often there is no password in /etc/group, so
	 * contrary to login et al. we let an empty password mean the same
	 * as in /etc/passwd */

	/* check /etc/gshadow */
	if (!(pwd = get_gshadow_pwd(ge->gr_name)))
		pwd = ge->gr_passwd;

	if (pwd && *pwd && (xpwd = xgetpass(stdin, _("Password: ")))) {
		char *cbuf = crypt(xpwd, pwd);

		memset_s(xpwd, strlen(xpwd), 0);
		free(xpwd);
		if (!cbuf)
			warn(_("crypt failed"));
		else if (strcmp(pwd, cbuf) == 0)
			return TRUE;
	}

	/* default to denial */
	return FALSE;
}

static void __attribute__((__noreturn__)) usage(FILE *out)
{
	fprintf(out, USAGE_HEADER);
	fprintf(out, _(" %s <group>\n"), program_invocation_short_name);

	fputs(USAGE_SEPARATOR, out);
	fputs(_("Log in to a new group.\n"), out);

	fprintf(out, USAGE_OPTIONS);
	fprintf(out, USAGE_HELP);
	fprintf(out, USAGE_VERSION);
	fprintf(out, USAGE_MAN_TAIL("newgrp(1)"));
	exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
}

int main(int argc, char *argv[])
{
	struct passwd *pw_entry;
	struct group *gr_entry;
	char *shell;
	char ch;
	static const struct option longopts[] = {
		{"version", no_argument, NULL, 'V'},
		{"help", no_argument, NULL, 'h'},
		{NULL, 0, NULL, 0}
	};

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	atexit(close_stdout);

	while ((ch = getopt_long(argc, argv, "Vh", longopts, NULL)) != -1)
		switch (ch) {
		case 'V':
			printf(UTIL_LINUX_VERSION);
			return EXIT_SUCCESS;
		case 'h':
			usage(stdout);
		default:
			usage(stderr);
		}

	if (!(pw_entry = getpwuid(getuid())))
		err(EXIT_FAILURE, _("who are you?"));

	if (argc < 2) {
		if (setgid(pw_entry->pw_gid) < 0)
			err(EXIT_FAILURE, _("setgid failed"));
	} else {
		errno = 0;
		if (!(gr_entry = getgrnam(argv[1]))) {
			if (errno)
				err(EXIT_FAILURE, _("no such group"));
			else
				errx(EXIT_FAILURE, _("no such group"));
		}
		if (!allow_setgid(pw_entry, gr_entry))
			errx(EXIT_FAILURE, _("permission denied"));
		if (setgid(gr_entry->gr_gid) < 0)
			err(EXIT_FAILURE, _("setgid failed"));
	}

	if (setuid(getuid()) < 0)
		err(EXIT_FAILURE, _("setuid failed"));

	fflush(NULL);
	shell = (pw_entry->pw_shell && *pw_entry->pw_shell ?
				pw_entry->pw_shell : _PATH_BSHELL);
	execl(shell, shell, (char *)0);
	warn(_("failed to execute %s"), shell);
	fflush(stderr);

	return EXIT_FAILURE;
}


text:
<?php

namespace Magento\Checkout\Test\Unit\Model;

class GuestShippingInformationManagementTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $shippingInformationManagementMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $quoteIdMaskFactoryMock;

    /**
     * @var \Magento\Checkout\Model\GuestShippingInformationManagement
     */
    protected $model;

    protected function setUp()
    {
        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->quoteIdMaskFactoryMock = $this->getMock(
            '\Magento\Quote\Model\QuoteIdMaskFactory',
            ['create'],
            [],
            '',
            false
        );
        $this->shippingInformationManagementMock = $this->getMock(
            '\Magento\Checkout\Api\ShippingInformationManagementInterface'
        );

        $this->model = $objectManager->getObject(
            'Magento\Checkout\Model\GuestShippingInformationManagement',
            [
                'quoteIdMaskFactory' => $this->quoteIdMaskFactoryMock,
                'shippingInformationManagement' => $this->shippingInformationManagementMock
            ]
        );
    }

    public function testSaveAddressInformation()
    {
        $cartId = 'masked_id';
        $quoteId = 100;
        $addressInformationMock = $this->getMock('\Magento\Checkout\Api\Data\ShippingInformationInterface');

        $quoteIdMaskMock = $this->getMock('\Magento\Quote\Model\QuoteIdMask', ['load', 'getQuoteId'], [], '', false);
        $this->quoteIdMaskFactoryMock->expects($this->once())->method('create')->willReturn($quoteIdMaskMock);

        $quoteIdMaskMock->expects($this->once())->method('load')->with($cartId, 'masked_id')->willReturnSelf();
        $quoteIdMaskMock->expects($this->once())->method('getQuoteId')->willReturn($quoteId);

        $paymentInformationMock = $this->getMock('\Magento\Checkout\Api\Data\PaymentDetailsInterface');
        $this->shippingInformationManagementMock->expects($this->once())
            ->method('saveAddressInformation')
            ->with($quoteId, $addressInformationMock)
            ->willReturn($paymentInformationMock);

        $this->model->saveAddressInformation($cartId, $addressInformationMock);
    }
}


text:
package com.cc.apptroy;

/**
 * Created by CwT on 15/7/31.
 */
public class DexFileInfo {
    private String dexPath;
    private int mCookie;
    private ClassLoader defineClassLoader;

    public DexFileInfo(String dexPath,int mCookie) {
        super();
        this.dexPath = dexPath;
        this.mCookie = mCookie;
//        Log.d("cc", "start");
//        NativeFunction.getInstance().saveDexFileByCookie(mCookie, ModuleContext.getInstance().getBaseClassLoader());
//        XposedBridge.log("dexpath: " + dexPath + ", mcookie: " + mCookie);
//        Log.d("cc", "dexpath: " + dexPath + ", mcookie: " + mCookie);
//        Log.d("cc", "end");
    }

    public DexFileInfo(String dexPath,int mCookie,ClassLoader classLoader) {
        this(dexPath,mCookie);
        this.defineClassLoader = classLoader;
    }

    public String getDexPath() {
        return dexPath;
    }

    public int getmCookie() {
        return mCookie;
    }

    public void setmCookie(int mCookie) {
        this.mCookie = mCookie;
    }

    public ClassLoader getDefineClassLoader() {
        return defineClassLoader;
    }

    public void setDefineClassLoader(ClassLoader defineClassLoader) {
        this.defineClassLoader = defineClassLoader;
    }

    public void setDexPath(String dexPath) {
        this.dexPath = dexPath;
    }
}


text:
package org.orienteer.core.component.widget.property;

import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.record.impl.ODocument;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.orienteer.core.component.widget.AbstractSchemaLocalizationWidget;
import org.orienteer.core.widget.Widget;

/**
 * Widget to show and modify {@link com.orientechnologies.orient.core.metadata.schema.OProperty} localization.
 */
@Widget(id="property-localization", domain="property", tab="localization", autoEnable=true)
public class OPropertyLocalizationWidget extends AbstractSchemaLocalizationWidget<OProperty> {

    public OPropertyLocalizationWidget(String id, IModel<OProperty> model, final IModel<ODocument> widgetDocumentModel) {
        super(id, model, widgetDocumentModel);

    }

    @Override
    protected String getLocalizationKey(OProperty oProperty) {
        return oProperty.getOwnerClass().getName() + "." + oProperty.getName();
    }

    @Override
    protected IModel<String> getTitleModel() {
        return new ResourceModel("class.localization");
    }

}


text:
<Title>Boost Graph Library: Copy Graph</Title>

<TT>copy_graph</TT>

template <class VertexListGraph, class MutableGraph>
void copy_graph(const VertexListGraph& G, MutableGraph& G_copy,
    const bgl_named_params<P, T, R>& params = all defaults)

This function copies all of the vertices and edges from graph
<tt>G</tt> into <tt>G_copy</tt>. Also, it copies the vertex and edge
properties, either by using the <tt>vertex_all</tt> and
<tt>edge_all</tt> property maps, or by user-supplied copy functions.

Where Defined

<TT>boost/graph/copy.hpp</TT>

Parameters

IN: <tt>const VertexListGraph& G</tt>

A directed or undirected graph. The graph type must be a model of Vertex List Graph.

OUT: <tt>MutableGraph& G_copy</tt>

The resulting copy of the graph.  The graph type must be a model of Mutable Graph.

Named Parameters

IN: <tt>vertex_copy(VertexCopier vc)</tt>

This is a Binary Function that copies the properties of a vertex in the original graph
into the corresponding vertex in the copy.

Default: <tt>vertex_copier<VertexListGraph, MutableGraph></tt>
which uses the property tag <tt>vertex_all</tt> to access a property
map from the graph.

IN: <tt>edge_copy(EdgeCopier ec)</tt>

This is a Binary Function that copies the properties of an edge in the original graph
into the corresponding edge in the copy.

Default: <tt>edge_copier<VertexListGraph, MutableGraph></tt>
which uses the property tag <tt>edge_all</tt> to access a property
map from the graph.

IN: <tt>vertex_index_map(VertexIndexMap i_map)</tt>

The vertex index map type must be a model of Readable Property
Map and must map the vertex descriptors of <tt>G</tt> to the
integers in the half-open range <tt>[0,num_vertices(G))</tt>.

Default: <tt>get(vertex_index, G)</tt>.
Note: if you use this default, make sure your graph has
an internal <tt>vertex_index</tt> property. For example,
<tt>adjacency_list</tt> with <tt>VertexList=listS</tt> does
not have an internal <tt>vertex_index</tt> property.

UTIL/OUT: <tt>orig_to_copy(Orig2CopyMap c)</tt>

This maps vertices in the original graph to vertices in the copy.

Default: an
  </tt>iterator_property_map</tt> created from a
  <tt>std::vector</tt> of the output graph's vertex descriptor type of size
  <tt>num_vertices(g)</tt> and using the <tt>i_map</tt> for the index
  map.

Complexity

The time complexity is O(V + E).

Copyright © 2000-2001
Jeremy Siek, Indiana University (jsiek@osl.iu.edu)


text:
package com.belatrixsf.connect.services;

import com.belatrixsf.connect.services.contracts.BelatrixConnectService;
import com.belatrixsf.connect.utils.BelatrixConnectCallback;
import com.belatrixsf.connect.utils.ServiceError;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Carlos Piñan
 */
public abstract class BelatrixConnectBaseService implements BelatrixConnectService {

    private List<ServiceRequest> serviceRequestList;

    protected <T> void enqueue(final ServiceRequest<T> serviceRequest, final BelatrixConnectCallback<T> belatrixConnectCallback) {
        if (serviceRequestList == null) {
            serviceRequestList = new ArrayList<>();
        }
        serviceRequestList.add(serviceRequest);
        serviceRequest.enqueue(new BelatrixConnectCallback<T>() {
            @Override
            public void onSuccess(T t) {
                dequeue(serviceRequest);
                belatrixConnectCallback.onSuccess(t);
            }

            @Override
            public void onFailure(ServiceError serviceError) {
                dequeue(serviceRequest);
                belatrixConnectCallback.onFailure(serviceError);
            }
        });
    }

    protected void dequeue(ServiceRequest serviceRequest) {
        serviceRequestList.remove(serviceRequest);
    }

    @Override
    public void cancelAll() {
        if (serviceRequestList != null && !serviceRequestList.isEmpty()) {
            for (ServiceRequest serviceRequest : serviceRequestList) {
                serviceRequest.cancel();
            }
            serviceRequestList.clear();
        }
    }

}


text: <title>WebGL Test Page</title>


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/privacy/dlp/v2beta2/dlp.proto

package com.google.privacy.dlp.v2beta2;

public interface AnalyzeDataSourceRiskRequestOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.privacy.dlp.v2beta2.AnalyzeDataSourceRiskRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * The parent resource name, for example projects/my-project-id.
   *

   *
   * string parent = 1;
   */
  java.lang.String getParent();
  /**
   *

   * The parent resource name, for example projects/my-project-id.
   *

   *
   * string parent = 1;
   */
  com.google.protobuf.ByteString
      getParentBytes();

  /**
   *

   * Configuration for this risk analysis job.
   *

   *
   * .google.privacy.dlp.v2beta2.RiskAnalysisJobConfig job_config = 2;
   */
  boolean hasJobConfig();
  /**
   *

   * Configuration for this risk analysis job.
   *

   *
   * .google.privacy.dlp.v2beta2.RiskAnalysisJobConfig job_config = 2;
   */
  com.google.privacy.dlp.v2beta2.RiskAnalysisJobConfig getJobConfig();
  /**
   *

   * Configuration for this risk analysis job.
   *

   *
   * .google.privacy.dlp.v2beta2.RiskAnalysisJobConfig job_config = 2;
   */
  com.google.privacy.dlp.v2beta2.RiskAnalysisJobConfigOrBuilder getJobConfigOrBuilder();

  /**
   *

   * Optional job ID to use for the created job. If not provided, a job ID will
   * automatically be generated. Must be unique within the project. The job ID
   * can contain uppercase and lowercase letters, numbers, and hyphens; that is,
   * it must match the regular expression: `[a-zA-Z\\d-]+`. The maximum length
   * is 100 characters. Can be empty to allow the system to generate one.
   *

   *
   * string job_id = 3;
   */
  java.lang.String getJobId();
  /**
   *

   * Optional job ID to use for the created job. If not provided, a job ID will
   * automatically be generated. Must be unique within the project. The job ID
   * can contain uppercase and lowercase letters, numbers, and hyphens; that is,
   * it must match the regular expression: `[a-zA-Z\\d-]+`. The maximum length
   * is 100 characters. Can be empty to allow the system to generate one.
   *

   *
   * string job_id = 3;
   */
  com.google.protobuf.ByteString
      getJobIdBytes();
}


text:
<?php

namespace Google\AdsApi\AdWords\v201809\o;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class PlatformCampaignEstimate
{

    /**
     * @var \Google\AdsApi\AdWords\v201809\cm\Platform $platform
     */
    protected $platform = null;

    /**
     * @var \Google\AdsApi\AdWords\v201809\o\StatsEstimate $minEstimate
     */
    protected $minEstimate = null;

    /**
     * @var \Google\AdsApi\AdWords\v201809\o\StatsEstimate $maxEstimate
     */
    protected $maxEstimate = null;

    /**
     * @param \Google\AdsApi\AdWords\v201809\cm\Platform $platform
     * @param \Google\AdsApi\AdWords\v201809\o\StatsEstimate $minEstimate
     * @param \Google\AdsApi\AdWords\v201809\o\StatsEstimate $maxEstimate
     */
    public function __construct($platform = null, $minEstimate = null, $maxEstimate = null)
    {
      $this->platform = $platform;
      $this->minEstimate = $minEstimate;
      $this->maxEstimate = $maxEstimate;
    }

    /**
     * @return \Google\AdsApi\AdWords\v201809\cm\Platform
     */
    public function getPlatform()
    {
      return $this->platform;
    }

    /**
     * @param \Google\AdsApi\AdWords\v201809\cm\Platform $platform
     * @return \Google\AdsApi\AdWords\v201809\o\PlatformCampaignEstimate
     */
    public function setPlatform($platform)
    {
      $this->platform = $platform;
      return $this;
    }

    /**
     * @return \Google\AdsApi\AdWords\v201809\o\StatsEstimate
     */
    public function getMinEstimate()
    {
      return $this->minEstimate;
    }

    /**
     * @param \Google\AdsApi\AdWords\v201809\o\StatsEstimate $minEstimate
     * @return \Google\AdsApi\AdWords\v201809\o\PlatformCampaignEstimate
     */
    public function setMinEstimate($minEstimate)
    {
      $this->minEstimate = $minEstimate;
      return $this;
    }

    /**
     * @return \Google\AdsApi\AdWords\v201809\o\StatsEstimate
     */
    public function getMaxEstimate()
    {
      return $this->maxEstimate;
    }

    /**
     * @param \Google\AdsApi\AdWords\v201809\o\StatsEstimate $maxEstimate
     * @return \Google\AdsApi\AdWords\v201809\o\PlatformCampaignEstimate
     */
    public function setMaxEstimate($maxEstimate)
    {
      $this->maxEstimate = $maxEstimate;
      return $this;
    }

}


text:
<?php

declare(strict_types = 1);
namespace BrowserDetectorTest;

use BrowserDetector\DetectorFactory;
use BrowserDetector\Loader\CompanyLoaderFactory;
use BrowserDetector\Loader\Helper\Filter;
use ExceptionalJSON\DecodeErrorException;
use ExceptionalJSON\EncodeErrorException;
use JsonClass\Json;
use Psr\Log\NullLogger;
use Symfony\Component\Cache\Adapter\NullAdapter;
use Symfony\Component\Cache\Psr16Cache;
use Symfony\Component\Finder\Finder;
use UaResult\Browser\BrowserInterface;
use UaResult\Device\DeviceInterface;
use UaResult\Engine\EngineInterface;
use UaResult\Os\OsInterface;
use UaResult\Result\ResultInterface;

trait UserAgentsTestTrait
{
    /**
     * @var \BrowserDetector\Detector
     */
    private $object;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    private static $logger = null;

    /**
     * @var \Psr\SimpleCache\CacheInterface
     */
    private static $cache = null;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     *
     * @return void
     */
    protected function setUp(): void
    {
        $logger = $this->getMockBuilder(NullLogger::class)
            ->disableOriginalConstructor()
            ->setMethods(['info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency'])
            ->getMock();
        $logger
            ->expects(self::never())
            ->method('info');
        $logger
            ->expects(self::never())
            ->method('notice');
        $logger
            ->expects(self::never())
            ->method('warning');
        $logger
            ->expects(self::never())
            ->method('error');
        $logger
            ->expects(self::never())
            ->method('critical');
        $logger
            ->expects(self::never())
            ->method('alert');
        $logger
            ->expects(self::never())
            ->method('emergency');

        $cache = new Psr16Cache(new NullAdapter());

        /** @var \Psr\Log\NullLogger $logger */
        $factory      = new DetectorFactory($cache, $logger);
        $this->object = $factory();
    }

    /**
     * @throws \RuntimeException
     * @throws \Exception
     *
     * @return array[]
     */
    public function userAgentDataProvider(): array
    {
        $start = microtime(true);

        echo 'starting provider ', static::class, ' ...';

        $data = [];

        $logger               = new NullLogger();
        $jsonParser           = new Json();
        $companyLoaderFactory = new CompanyLoaderFactory($jsonParser, new Filter());

        /** @var \BrowserDetector\Loader\CompanyLoader $companyLoader */
        $companyLoader = $companyLoaderFactory();
        $resultFactory = new ResultFactory($companyLoader);

        $finder = new Finder();
        $finder->files();
        $finder->name('*.json');
        $finder->ignoreDotFiles(true);
        $finder->ignoreVCS(true);
        $finder->sortByName();
        $finder->ignoreUnreadableDirs();

        foreach ($this->sourceDirectory as $directory) {
            $finder->in($directory);
        }

        foreach ($finder as $file) {
            /* @var \Symfony\Component\Finder\SplFileInfo $file */

            try {
                $tests = (new Json())->decode($file->getContents(), true);
            } catch (DecodeErrorException $e) {
                throw new \Exception(sprintf('file "%s" contains invalid json', $file->getPathname()), 0, $e);
            }

            foreach ($tests as $key => $test) {
                if (array_key_exists($key, $data)) {
                    // Test data is duplicated for key
                    continue;
                }

                $data[$key] = [
                    'result' => $resultFactory->fromArray($logger, $test),
                ];
            }
        }

        echo ' finished (', str_pad(number_format(microtime(true) - $start, 4), 7, ' ', STR_PAD_LEFT), ' sec., ', str_pad((string) count($data), 4, ' ', STR_PAD_LEFT), ' test', (1 !== count($data) ? 's' : ''), ')', PHP_EOL;

        return $data;
    }

    /**
     * @dataProvider userAgentDataProvider
     *
     * @param ResultInterface $expectedResult
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     * @throws \PHPUnit\Framework\ExpectationFailedException
     * @throws \PHPUnit\Framework\Exception
     *
     * @return void
     */
    public function testUserAgents(ResultInterface $expectedResult): void
    {
        $headers = $expectedResult->getHeaders();
        $object  = $this->object;
        $result  = $object($headers);

        try {
            $encodedHeaders = (new Json())->encode(
                $headers,
                JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_PRESERVE_ZERO_FRACTION
            );
        } catch (EncodeErrorException $e) {
            $encodedHeaders = '<failed to encode headers>';
        }

        static::assertInstanceOf(
            ResultInterface::class,
            $result,
            sprintf(
                'found result is not an instance of "\UaResult\Result\ResultInterface" for headers %s',
                $encodedHeaders
            )
        );

        $foundBrowser = $result->getBrowser();

        static::assertInstanceOf(
            BrowserInterface::class,
            $foundBrowser,
            sprintf(
                'found browser is not an instance of "\UaResult\Browser\BrowserInterface" for headers %s',
                $encodedHeaders
            )
        );

        $foundEngine = $result->getEngine();

        static::assertInstanceOf(
            EngineInterface::class,
            $foundEngine,
            sprintf(
                'found engine is not an instance of "\UaResult\Engine\EngineInterface" for headers %s',
                $encodedHeaders
            )
        );

        $foundPlatform = $result->getOs();

        static::assertInstanceOf(
            OsInterface::class,
            $foundPlatform,
            sprintf(
                'found platform is not an instance of "\UaResult\Os\OsInterface" for headers %s',
                $encodedHeaders
            )
        );

        $foundDevice = $result->getDevice();

        static::assertInstanceOf(
            DeviceInterface::class,
            $foundDevice,
            sprintf(
                'found result is not an instance of "\UaResult\Device\DeviceInterface" for headers %s',
                $encodedHeaders
            )
        );

        self::assertEquals(
            $expectedResult,
            $result,
            sprintf(
                'detection result mismatch for headers %s',
                $encodedHeaders
            )
        );
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>junior</artifactId>
        <groupId>ru.job4j</groupId>
        <version>2.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <build>
        <resources>
            <resource>
                <directory>src/test/texts</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <finalName>pack</finalName>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>io.Args</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <artifactId>chapter_006</artifactId>

</project>


text:
require 'spec_helper'

describe Twilio::REST::Message do
  before do
    @message = Twilio::REST::Message.new('someUri', 'someClient')
  end

  it 'sets up a media resources object' do
    expect(@message).to respond_to(:media)
    expect(@message.media.instance_variable_get('@path')).to eq('someUri/Media')
  end
end


text:
package models
// AUTO-GENERATED Slick data model
/** Stand-alone Slick data model for immediate use */
object Tables extends {
  val profile = slick.jdbc.MySQLProfile
} with Tables

/** Slick data model trait for extension, choice of backend or usage in the cake pattern. (Make sure to initialize this late.) */
trait Tables {
  val profile: slick.jdbc.JdbcProfile
  import profile.api._
  import play.api.libs.json._
  import slick.model.ForeignKeyAction
  // NOTE: GetResult mappers for plain SQL are only generated for tables where Slick knows how to map the types of all columns.
  import slick.jdbc.{GetResult => GR}

  /** DDL for all tables. Call .create to execute. */
  lazy val schema: profile.SchemaDescription = Food.schema ++ Type.schema
  @deprecated("Use .schema instead of .ddl", "3.0")
  def ddl = schema

  /** Entity class storing rows of table Food
   *  @param id Database column id SqlType(INT), AutoInc, PrimaryKey
   *  @param name Database column name SqlType(VARCHAR), Length(512,true)
   *  @param image Database column image SqlType(VARCHAR), Length(1024,true), Default(None)
   *  @param typeId Database column type_id SqlType(INT) */
  case class FoodRow(id: Int, name: String, image: Option[String] = None, typeId: Int)
  /** JSON automated mapping for FoodRow */
  implicit val foodRowFormat: OFormat[FoodRow] = Json.format[FoodRow]
  /** GetResult implicit for fetching FoodRow objects using plain SQL queries */
  implicit def GetResultFoodRow(implicit e0: GR[Int], e1: GR[String], e2: GR[Option[String]]): GR[FoodRow] = GR{
    prs => import prs._
    FoodRow.tupled((<<[Int], <<[String], <<?[String], <<[Int]))
  }
  /** Table description of table food. Objects of this class serve as prototypes for rows in queries. */
  class Food(_tableTag: Tag) extends profile.api.Table[FoodRow](_tableTag, Some("foodie"), "food") {
    def * = (id, name, image, typeId) <> (FoodRow.tupled, FoodRow.unapply)
    /** Maps whole row to an option. Useful for outer joins. */
    def ? = (Rep.Some(id), Rep.Some(name), image, Rep.Some(typeId)).shaped.<>({r=>import r._; _1.map(_=> FoodRow.tupled((_1.get, _2.get, _3, _4.get)))}, (_:Any) =>  throw new Exception("Inserting into ? projection not supported."))

    /** Database column id SqlType(INT), AutoInc, PrimaryKey */
    val id: Rep[Int] = column[Int]("id", O.AutoInc, O.PrimaryKey)
    /** Database column name SqlType(VARCHAR), Length(512,true) */
    val name: Rep[String] = column[String]("name", O.Length(512,varying=true))
    /** Database column image SqlType(VARCHAR), Length(1024,true), Default(None) */
    val image: Rep[Option[String]] = column[Option[String]]("image", O.Length(1024,varying=true), O.Default(None))
    /** Database column type_id SqlType(INT) */
    val typeId: Rep[Int] = column[Int]("type_id")

    /** Foreign key referencing Type (database name fk_food_type) */
    lazy val typeFk = foreignKey("fk_food_type", typeId, Type)(r => r.id, onUpdate=ForeignKeyAction.NoAction, onDelete=ForeignKeyAction.NoAction)

    /** Uniqueness Index over (name) (database name name_UNIQUE) */
    val index1 = index("name_UNIQUE", name, unique=true)
  }
  /** Collection-like TableQuery object for table Food */
  lazy val Food = new TableQuery(tag => new Food(tag))

  /** Entity class storing rows of table Type
   *  @param id Database column id SqlType(INT), AutoInc, PrimaryKey
   *  @param name Database column name SqlType(VARCHAR), Length(512,true) */
  case class TypeRow(id: Int, name: String)
  /** JSON automated mapping for TypeRow */
  implicit val typeRowFormat: OFormat[TypeRow] = Json.format[TypeRow]
  /** GetResult implicit for fetching TypeRow objects using plain SQL queries */
  implicit def GetResultTypeRow(implicit e0: GR[Int], e1: GR[String]): GR[TypeRow] = GR{
    prs => import prs._
    TypeRow.tupled((<<[Int], <<[String]))
  }
  /** Table description of table type. Objects of this class serve as prototypes for rows in queries. */
  class Type(_tableTag: Tag) extends profile.api.Table[TypeRow](_tableTag, Some("foodie"), "type") {
    def * = (id, name) <> (TypeRow.tupled, TypeRow.unapply)
    /** Maps whole row to an option. Useful for outer joins. */
    def ? = (Rep.Some(id), Rep.Some(name)).shaped.<>({r=>import r._; _1.map(_=> TypeRow.tupled((_1.get, _2.get)))}, (_:Any) =>  throw new Exception("Inserting into ? projection not supported."))

    /** Database column id SqlType(INT), AutoInc, PrimaryKey */
    val id: Rep[Int] = column[Int]("id", O.AutoInc, O.PrimaryKey)
    /** Database column name SqlType(VARCHAR), Length(512,true) */
    val name: Rep[String] = column[String]("name", O.Length(512,varying=true))

    /** Uniqueness Index over (name) (database name name_UNIQUE) */
    val index1 = index("name_UNIQUE", name, unique=true)
  }
  /** Collection-like TableQuery object for table Type */
  lazy val Type = new TableQuery(tag => new Type(tag))
}


text:
namespace chatterino {

class HighlightController;

class UserHighlightModel : public SignalVectorModel<HighlightPhrase>
{
public:
    explicit UserHighlightModel(QObject *parent);

protected:
    // vector into model row
    virtual HighlightPhrase getItemFromRow(
        std::vector<QStandardItem *> &row,
        const HighlightPhrase &original) override;

    virtual void getRowFromItem(const HighlightPhrase &item,
                                std::vector<QStandardItem *> &row) override;
};

}  // namespace chatterino


text:
/**
 * This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 */
package com.archimatetool.canvas.model;

import com.archimatetool.editor.ui.IHelpHintProvider;
import com.archimatetool.model.IBorderObject;
import com.archimatetool.model.IDiagramModelContainer;
import com.archimatetool.model.IIconic;
import com.archimatetool.model.ILockable;
import com.archimatetool.model.IProperties;
import com.archimatetool.model.ITextContent;
import com.archimatetool.model.ITextPosition;

/**
 *
 * A representation of the model object 'Model Block'.
 *
 *
 *
 * @see com.archimatetool.canvas.model.ICanvasPackage#getCanvasModelBlock()
 * @model superTypes="com.archimatetool.model.Iconic com.archimatetool.model.DiagramModelContainer com.archimatetool.model.Properties com.archimatetool.model.Lockable com.archimatetool.model.BorderObject com.archimatetool.canvas.model.HelpHintProvider com.archimatetool.canvas.model.HintProvider com.archimatetool.model.TextContent com.archimatetool.model.TextPosition"
 * @generated
 */
public interface ICanvasModelBlock extends IIconic, IDiagramModelContainer, IProperties, ILockable, IBorderObject, IHelpHintProvider, IHintProvider, ITextContent, ITextPosition {
} // ICanvasModelBlock


text:
namespace syncer {

namespace {

// These ProxyFooCallback functions are used to invoke a callback in a specific
// thread.

// Invokes |callback| with |result| and |attachments| in the |task_runner|
// thread.
void ProxyGetOrDownloadCallback(
    const scoped_refptr<base::SequencedTaskRunner>& task_runner,
    const AttachmentService::GetOrDownloadCallback& callback,
    const AttachmentService::GetOrDownloadResult& result,
    std::unique_ptr<AttachmentMap> attachments) {
  task_runner->PostTask(
      FROM_HERE, base::Bind(callback, result, base::Passed(&attachments)));
}

}  // namespace

AttachmentServiceProxy::AttachmentServiceProxy() {}

AttachmentServiceProxy::AttachmentServiceProxy(
    const scoped_refptr<base::SequencedTaskRunner>& wrapped_task_runner,
    const base::WeakPtr<AttachmentService>& wrapped)
    : wrapped_task_runner_(wrapped_task_runner), core_(new Core(wrapped)) {
  DCHECK(wrapped_task_runner_.get());
}

AttachmentServiceProxy::AttachmentServiceProxy(
    const scoped_refptr<base::SequencedTaskRunner>& wrapped_task_runner,
    const scoped_refptr<Core>& core)
    : wrapped_task_runner_(wrapped_task_runner), core_(core) {
  DCHECK(wrapped_task_runner_.get());
  DCHECK(core_.get());
}

AttachmentServiceProxy::AttachmentServiceProxy(
    const AttachmentServiceProxy& other) = default;

AttachmentServiceProxy::~AttachmentServiceProxy() {}

void AttachmentServiceProxy::GetOrDownloadAttachments(
    const AttachmentIdList& attachment_ids,
    const GetOrDownloadCallback& callback) {
  DCHECK(wrapped_task_runner_.get());
  GetOrDownloadCallback proxy_callback =
      base::Bind(&ProxyGetOrDownloadCallback,
                 base::ThreadTaskRunnerHandle::Get(), callback);
  wrapped_task_runner_->PostTask(
      FROM_HERE, base::Bind(&AttachmentService::GetOrDownloadAttachments, core_,
                            attachment_ids, proxy_callback));
}

void AttachmentServiceProxy::UploadAttachments(
    const AttachmentIdList& attachment_ids) {
  DCHECK(wrapped_task_runner_.get());
  wrapped_task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&AttachmentService::UploadAttachments, core_, attachment_ids));
}

AttachmentServiceProxy::Core::Core(
    const base::WeakPtr<AttachmentService>& wrapped)
    : wrapped_(wrapped) {}

AttachmentServiceProxy::Core::~Core() {}

void AttachmentServiceProxy::Core::GetOrDownloadAttachments(
    const AttachmentIdList& attachment_ids,
    const GetOrDownloadCallback& callback) {
  if (!wrapped_) {
    return;
  }
  wrapped_->GetOrDownloadAttachments(attachment_ids, callback);
}

void AttachmentServiceProxy::Core::UploadAttachments(
    const AttachmentIdList& attachment_ids) {
  if (!wrapped_) {
    return;
  }
  wrapped_->UploadAttachments(attachment_ids);
}

}  // namespace syncer


text:
import pytest

from flex.loading.schema import (
    swagger_schema_validator,
)
from flex.exceptions import ValidationError
from flex.error_messages import MESSAGES

from tests.utils import (
    assert_message_in_errors,
    assert_path_not_in_errors,
    assert_path_in_errors,
)
from tests.factories import (
    RawSchemaFactory,
)

NON_STRING_VALUES = (1, 1.1, True, ['a', 'b'], {'a': 'b'}, None)

def test_swagger_field_is_required():
    """
    Test that the info field is required for overall schema validation.
    """
    raw_schema = RawSchemaFactory()
    raw_schema.pop('swagger', None)

    assert 'swagger' not in raw_schema

    with pytest.raises(ValidationError) as err:
        swagger_schema_validator(raw_schema)

    assert_message_in_errors(
        MESSAGES['required']['required'],
        err.value.detail,
        'required.swagger',
    )

def test_swagger_field_cannot_be_null():
    raw_schema = RawSchemaFactory(swagger=None)

    assert raw_schema['swagger'] is None

    with pytest.raises(ValidationError) as err:
        swagger_schema_validator(raw_schema)

    assert_path_in_errors(
        'swagger',
        err.value.detail,
    )

def test_swagger_field_with_valid_version():
    raw_schema = RawSchemaFactory(swagger='2.0')

    try:
        swagger_schema_validator(raw_schema)
    except ValidationError as err:
        errors = err.detail
    else:
        errors = {}

    assert_path_not_in_errors(
        'swagger',
        errors
    )

def test_swagger_field_with_invalid_version():
    raw_schema = RawSchemaFactory(swagger='not-valid')

    with pytest.raises(ValidationError) as err:
        swagger_schema_validator(raw_schema)

    assert_message_in_errors(
        MESSAGES['enum']['invalid'],
        err.value.detail,
        'swagger.enum',
    )

@pytest.mark.parametrize(
    'value',
    (1, 1.1, True, ['a', 'b'], {'a': 'b'}, None),
)
def test_version_must_be_a_string(value):
    data = RawSchemaFactory(
        swagger=value,
    )
    with pytest.raises(ValidationError) as err:
        swagger_schema_validator(data)

    assert_message_in_errors(
        MESSAGES['type']['invalid'],
        err.value.detail,
        'swagger.type',
    )


text:
import subprocess
from filecmp import cmp

from tests.fixtures import *
import servi.manifest as man
from servi.command import process_and_run_command_line as servi_run
from servi.utils import file_exists, reset_cwd
from servi.semantic import SemanticVersion
from servi.exceptions import ServiError
from servi.commands.utils import in_servi_code_dir

def test_cmd_utils(mock_template_dir, mock_in_servi_dir):
    # Test changed manifest
    modify_file(pathfor('ansible_config/playbook.yml', c.TEMPLATE))
    assert not servi_run('utils --ensure_latest_manifest')

    # Now test skipping
    assert servi_run('utils --ensure_latest_manifest')

    # Test no manifest
    os.remove(pathfor(c.MANIFEST_FILE, c.TEMPLATE))
    assert not servi_run('utils --ensure_latest_manifest')
    assert file_exists(pathfor(c.MANIFEST_FILE, c.TEMPLATE))

    # While we're at it, let's test that it's a good manifest, and that
    # manifest.load works
    new_man = man.Manifest(c.TEMPLATE, load=True)
    assert "files" in new_man.manifest

    # Only 1 at a time
    with pytest.raises(ServiError):
        servi_run('utils --ensure_latest_manifest --bump minor')

    assert servi_run('utils --set_ver 1.0.0')
    assert servi_run('utils --bump patch')
    m = man.Manifest(c.TEMPLATE)
    assert m.template_version == SemanticVersion('1.0.1')

def test_ensure_latest_globals_in_git(setup_empty, tmpdir):
    """
    Scenarios:
        * No ~/Servifile_globals.yml --> True
        * Not in git directory --> Raise
        * No local version --> copy & False
        * Different local version  --> copy & False
        * Same local version --> True
    """
    # Setup mocked servi directory
    servidir = tmpdir.mkdir('mockservi')
    projdir = tmpdir.mkdir('myproject')
    subprocess.call('git init '+str(servidir), shell=True)

    #
    # In Project Dir
    #
    projdir.chdir()
    assert servi_run('init --skip_servifile_globals .')
    assert servi_run('utils --ensure_latest_globals_in_git ')

    assert servi_run('init -f .')
    with pytest.raises(ServiError):
        assert servi_run('utils --ensure_latest_globals_in_git')

    #
    # In Servi Dir
    #
    servidir.chdir()
    assert not servi_run('utils --ensure_latest_globals_in_git ')
    assert servidir.join(c.SERVIFILE_GLOBAL).check(exists=1)
    modify_file(c.SERVIFILE_GLOBAL_FULL)
    assert not servi_run('utils --ensure_latest_globals_in_git ')
    assert cmp(c.SERVIFILE_GLOBAL_FULL,
               str(servidir.join(c.SERVIFILE_GLOBAL)), shallow=False)

    assert servi_run('utils --ensure_latest_globals_in_git ')

def test_in_servi_code_dir(tmpdir):
    import py.path

    projdir = tmpdir.mkdir('myproject')
    thisdir = py.path.local(os.path.dirname(__file__))
    servidir = thisdir.join('..')
    with reset_cwd():
        servidir.chdir()
        assert in_servi_code_dir()
        subdir = servidir.join('tests')
        subdir.chdir()
        assert in_servi_code_dir()
        projdir.chdir()
        assert not in_servi_code_dir()

def test_link_githook(setup_init):
    with pytest.raises(ServiError):  # Not in git dir
        servi_run('utils --link_githook')

    subprocess.call('git init .', shell=True)
    assert servi_run('utils --link_githook')

    with pytest.raises(ServiError):  # Already exists
        servi_run('utils --link_githook')


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

<title>aspguidc.service.generation.writer.general</title>
<meta name="date" content="2017-06-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package aspguidc.service.generation.writer.general

Class Summary

Class
Description

GeneralTemplateWriter

Writer class which provides methods for generating general source code files.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
require "pract05/version"

module Pract05
  # = Practica 10
  #
  # Autor::   Bianney Cabrera y David Rodríguez
  # Web::     https://github.com/alu0100505184/practica08
  #
  # == PreguntaGlobal
  #
  # Con esta clase pretendemos:
  # - Crear una estructura para almacenar información
  # - Creación de punteros a otros conjuntos de información
  #
  # === Clase PreguntaGlobal
  #
  # Definición de la clase PreguntaGlobal:
  # * metodo initialize
  # * metodo imprimir_enunciado
  # * metodo to_s
  # ==== Attributes
  #
  # * +enunciado+ - Contiene la pregunta

  class PreguntaGlobal
    # Creado acceso de [Lectura/Escritura]
    attr_accessor :enunciado

    # Método constructor de la clase PreguntaGlobal
    def initialize(enunciado)
         @enunciado=enunciado
    end

     # Método para mostrar por consola un enunciado
     def imprimir_enunciado()
	puts "\nPregunta de examen"
        puts @enunciado
    end

    # Método para convertir la variable es un string
    def to_s()
      @enunciado
    end

  end
end


text: module.exports = require('./lib/browser');


text:
namespace RefactorExamSolutions
{
    using System;

    public class TextToNumber
    {
        private const int LowerCaseLetterMinimumValue = 97;
        private const int LowerCaseLetterMaximumValue = 122;
        private const int UpperCaseLetterMinimumValue = 65;
        private const int UpperCaseLetterMaximumValue = 90;

        public static void Main()
        {
            string textParser = Console.ReadLine();
            long textParserAsNumber = long.Parse(textParser);

            string text = Console.ReadLine();
            long finalResult = 0;

            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] == '@')
                {
                    Console.WriteLine(finalResult);
                    return;
                }
                else if (char.IsDigit(text[i]))
                {
                    finalResult *= text[i] - '0';
                }
                else if ((text[i] >= UpperCaseLetterMinimumValue && text[i] <= UpperCaseLetterMaximumValue) ||
                        (text[i] >= LowerCaseLetterMinimumValue && text[i] <= LowerCaseLetterMaximumValue))
                {
                    if (text[i] >= UpperCaseLetterMinimumValue && text[i] <= UpperCaseLetterMaximumValue)
                    {
                        finalResult += text[i] - UpperCaseLetterMinimumValue;
                    }
                    else if (text[i] >= LowerCaseLetterMinimumValue && text[i] <= LowerCaseLetterMaximumValue)
                    {
                        finalResult += text[i] - LowerCaseLetterMinimumValue;
                    }
                }
                else
                {
                    finalResult %= textParserAsNumber;
                }
            }

            Console.WriteLine(finalResult);
        }
    }
}


text:
function [mask] = atlas_mask(atlas, mri, label, varargin)

% ATLAS_MASK creates a mask that can be used in visualizing a functional
% and/or anatomical MRI volume.
%
% Use as
%   atlas = atlas_init;
%   mask  = atlas_mask(atlas, mri, label, ...);
%
% Optinal input arguments should come in key-value pairs and can include
%   'inputcoord'   = 'mni' or 'tal' (default = []);
%
% Dependent on the input coordinates and the coordinates of the atlas, the
% input MRI is transformed betweem MNI and Talairach-Tournoux coordinates
% See http://www.mrc-cbu.cam.ac.uk/Imaging/Common/mnispace.shtml for more details.
%
% See also ATLAS_INIT, ATLAS_LOOKUP

% Copyright (C) 2005-2008, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: atlas_mask.m 4439 2011-10-12 10:17:09Z roboos $

% get the optional input arguments
inputcoord = ft_getopt(varargin, 'inputcoord');

if isempty(inputcoord)
  error('you must specify inputcoord');
end

if ischar(label)
  label = {label};
end

sel = [];
for i=1:length(label)
  sel = [sel; strmatch(label{i}, atlas.descr.name, 'exact')];
end

fprintf('found %d matching anatomical labels\n', length(sel));

brick = atlas.descr.brick(sel);
value = atlas.descr.value(sel);

if isfield(mri, 'transform') && isfield(mri, 'dim')
  dim = mri.dim;
  % determine location of each anatomical voxel in its own voxel coordinates
  i = 1:dim(1);
  j = 1:dim(2);
  k = 1:dim(3);
  [I, J, K] = ndgrid(i, j, k);
  ijk = [I(:) J(:) K(:) ones(prod(dim),1)]';
  % determine location of each anatomical voxel in head coordinates
  xyz = mri.transform * ijk; % note that this is 4xN
elseif isfield(mri, 'pos')
  % the individual positions of every grid point are specified
  npos = size(mri.pos,1);
  dim  = [npos 1];
  xyz  = [mri.pos ones(npos,1)]';  % note that this is 4xN
else
  error('could not determine whether the input describes a volume or a source');
end

% convert between MNI head coordinates and TAL head coordinates
% coordinates should be expressed compatible with the atlas
if     strcmp(inputcoord, 'mni') && strcmp(atlas.coord, 'tal')
  xyz(1:3,:) = mni2tal(xyz(1:3,:));
elseif strcmp(inputcoord, 'mni') && strcmp(atlas.coord, 'mni')
  % nothing to do
elseif strcmp(inputcoord, 'tal') && strcmp(atlas.coord, 'tal')
  % nothing to do
elseif strcmp(inputcoord, 'tal') && strcmp(atlas.coord, 'mni')
  xyz(1:3,:) = tal2mni(xyz(1:3,:));
end

% determine location of each anatomical voxel in atlas voxel coordinates
ijk = inv(atlas.transform) * xyz;
ijk = round(ijk(1:3,:))';

inside_vol = ijk(:,1)>=1 & ijk(:,1)<=atlas.dim(1) & ...
  ijk(:,2)>=1 & ijk(:,2)<=atlas.dim(2) & ...
  ijk(:,3)>=1 & ijk(:,3)<=atlas.dim(3);
inside_vol = find(inside_vol);

% convert the selection inside the atlas volume into linear indices
ind = sub2ind(atlas.dim, ijk(inside_vol,1), ijk(inside_vol,2), ijk(inside_vol,3));

brick0_val = zeros(prod(dim),1);
brick1_val = zeros(prod(dim),1);
% search the two bricks for the value of each voxel
brick0_val(inside_vol) = atlas.brick0(ind);
brick1_val(inside_vol) = atlas.brick1(ind);

mask = zeros(prod(dim),1);
for i=1:length(sel)
  fprintf('constructing mask for %s\n', atlas.descr.name{sel(i)});
  if brick(i)==0
    mask = mask | (brick0_val==value(i));
  elseif brick(i)==1
    mask = mask | (brick1_val==value(i));
  end
end
mask = reshape(mask, dim);

fprintf('masked %.1f %% of total volume\n', 100*mean(mask(:)));


text:
(function() {
  module.exports.register = function(Handlebars, options) {

    var grunt     = require('grunt');
    var marked     = require('./libs/marked.min.js');
    var SG_ENTRY_TEMPLATE;

    /**
     * Helper name
     * @param  {[type]} str [description]
     * @return {[type]}     [description]
     */
    Handlebars.registerHelper('sgEntry', function() {

      var PATH_PREFIX = 'src/';
      var SG_ENTRY_TEMPLATE = grunt.file.read('assemble-styleguide/helpers/templates/sgEntry.hbs');

      var markdownContent;
      var htmlContent;
      var identifier;
      var pathArray;
      var path;
      var filename;
      var sgEntry;
      var block;

      var options = arguments[arguments.length - 1];
      var modifiers = options.hash.modifiers ? options.hash.modifiers.split(',') : [];
      modifiers.unshift('')

      if (typeof arguments[0] === 'string') {
        path = arguments[0];
        pathArray = path.split('/');
        identifier = pathArray[pathArray.length - 1];
        pathArray.pop();
        path = pathArray.join('/');
        path = PATH_PREFIX + path;
        if(grunt.file.exists( path + '/' + identifier + '.md') || grunt.file.exists( path + '/' + identifier + '.html')) {
          filename = identifier;
        } else if(grunt.file.exists( path + '/_' + identifier + '.md') || grunt.file.exists( path + '/_' + identifier + '.html')) {
          filename = '_' + identifier;
        }
        if (grunt.file.exists( path + '/' + identifier + '.md')) {
          markdownContent = grunt.file.read( path + '/' + filename + '.md');
          markdownContent = Handlebars.compile(markdownContent)();
          markdownContent = marked(markdownContent);
        } else {
          markdownContent = null;
        }
        if (grunt.file.exists( path + '/' + filename + '.html') ) {
          htmlContent = grunt.file.read( path + '/' + filename + '.html').trim();
        } else {
          htmlContent = null;
        }

      } else if (typeof options.fn === 'function') {
        block = options.fn().split('~~~HTML~~~');
        markdownContent = block[0];
        markdownContent = Handlebars.compile(markdownContent)();
        markdownContent = marked(markdownContent);
        htmlContent = block[1] ? block[1].trim() : "";
        identifier = options.hash.identifier;
      }

      sgEntry = Handlebars.compile(SG_ENTRY_TEMPLATE)({
        markdownContent: markdownContent,
        htmlContent: htmlContent,
        identifier: identifier,
        modifiers: modifiers
      });

      return new Handlebars.SafeString(sgEntry);
    });

  };
}).call(this);


text:
package water.util;

import water.Key;

import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * File utilities.
 */
public class FileUtils {

  public static boolean makeSureDirExists(String dir) {
    File f = new File(dir);
    if (!f.exists()) {
      return f.mkdirs();
    } else {
      return true;
    }
  }

  /**
   * Silently close given files.
   *
   * @param closeable files to close
   */
  public static void closeSilently(Closeable...closeable) {
    for(Closeable c : closeable)
      try { if( c != null ) c.close(); } catch( IOException xe ) { }
  }

  /**
   * Closes given files, logging exceptions thrown during the process of closing.
   *
   * @param closeable files to close
   */
  public static void close(Closeable...closeable) {
    for(Closeable c : closeable)
      try { if( c != null ) c.close(); } catch( IOException ex ) {
        Log.err(ex);
      }
  }

  public static void copyStream(InputStream is, OutputStream os, final int buffer_size) {
    try {
      byte[] bytes=new byte[buffer_size];
      while( is.available() > 0 )
      {
        int count=is.read(bytes, 0, buffer_size);
        if(count<=0)
          break;
        os.write(bytes, 0, count);
      }
    }
    catch(EOFException eofe) {
      // no problem
    }
    catch(Exception ex) {
      throw new RuntimeException(ex);
    }
  }

  public static URI getURI(String path) {
    boolean windowsPath = path.matches("^[a-zA-Z]:.*$");
    if (windowsPath) {
      return new File(path).toURI();
    } else if (path.contains(":/")) { // Seems like
      return URI.create(path);
    } else {
      return new File(path).toURI();
    }
  }

  public static boolean delete(File file) {
    if (file.isFile())
      file.delete();
    else if (file.isDirectory()) {
      File[] files = file.listFiles();
      for (File f: files) {
        if (f.isDirectory()) {
          delete(f);
        } else {
          f.delete();
        }
      }
      // Delete top-level directory
      return file.delete();
    }

    return false;
  }

  /** Hunt for files in likely places.  Null if cannot find.
   *  @param fname filename
   *  @return      Found file or null */
  public static File locateFile(String fname) {
    // Search in pre-defined path, when active, overrides all other, including direct file lookup
    final Optional<File> fileInPredefinedPath = findFileInPredefinedPath(fname);
    if (fileInPredefinedPath.isPresent()) return fileInPredefinedPath.get();

    File file = new File(fname);
    if (file.exists()) return file;

    file = new File("target/" + fname);
    if (!file.exists())
      file = new File("../" + fname);
    if (!file.exists())
      file = new File("../../" + fname);
    if (!file.exists())
      file = new File("../../../" + fname);
    if (!file.exists())
      file = new File("../target/" + fname);
    if (!file.exists())
      file = new File(StringUtils.expandPath(fname));
    if (!file.exists())
      file = null;
    return file;
  }

  /**
   * @param fileName File name/path to search for in pre-defined search path
   * @return An {@link Optional} with the file inside, if the H2O_FILES_SEARCH_PATH is defined and the file exists.
   * Otherwise an empty {@link Optional}. Never null.
   */
  private static Optional<File> findFileInPredefinedPath(final String fileName) {
    Objects.requireNonNull(fileName);

    final String searchPath = System.getenv("H2O_FILES_SEARCH_PATH");
    if (searchPath == null) return Optional.empty();

    final StringBuilder localizedFileNameBuilder = new StringBuilder(searchPath);

    if (!searchPath.endsWith("/")) {
      localizedFileNameBuilder.append('/');
    }

    // If the file starts with {"./", ".\", "../", "..\"} (or multiple instances of these), strip it.
    // Does not match relative paths from top of the filesystem tree (starting with "/").
    final Pattern pattern = Pattern.compile("(\\.+[\\/]{1})+(.*)");
    final Matcher matcher = pattern.matcher(fileName);

    if (matcher.matches()) {
      localizedFileNameBuilder.append(matcher.group(2));
    } else if (fileName.startsWith("/")) {
      return Optional.empty(); // The "/" at the beginning indicates absolute path, except for Windows. Do not attempt.
    } else {
      localizedFileNameBuilder.append(fileName);
    }

    final File file = new File(localizedFileNameBuilder.toString());

    if (file.exists()) {
      return Optional.of(file);
    } else {
      return Optional.empty();
    }

  }

  private static void check(boolean cond, String msg) throws IOException {
    if (!cond) throw new IOException(msg);
  }

  private static void checkFileEntry(String name, File file) throws IOException {
    check(file != null, "File not found: " + name);
    check(file.exists(), "File should exist: " + name);
  }

  public static void checkFile(File file, String name) throws IOException {
    checkFileEntry(name, file);
    check(file.isFile(), "Expected a file: " + name);
    check(file.canRead(), "Expected a readable file: " + name);
  }

  public static File getFile(String fname) throws IOException {
    File f = locateFile(fname);
    checkFile(f, fname);
    return f;
  }

  public static File[] contentsOf(File folder, String name) throws IOException {
    checkFileEntry(name, folder);
    if (!folder.isDirectory()) throw new IOException("Expected a folder: " + name);
    File[] files = folder.listFiles();
    if (files == null) throw new IOException("Cannot read folder: " + folder);
    return files;
  }

  /** Transform given key to a string which can be used as a file name. */
  public static String keyToFileName(Key k) {
    return k.toString().replaceAll("[^a-zA-Z0-9_\\-\\.]", "_");
  }
}


text:
module KatelloApi
  module Resources
    class ContentViewFilter < KatelloApi::Base
      def self.doc
        @doc ||= KatelloApi.doc['resources']["content_view_filters"]
      end

      # @param [Hash] params a hash of params to be passed to the service
      # @option params [String] content_view_id  content view identifier
      #
      # @param [Hash] headers additional http headers
      # @return [Array] First item: parsed data; second item: raw body
      def index(params = {}, headers = {})
        perform_call(__method__, params, headers)
      end

      # @param [Hash] params a hash of params to be passed to the service
      # @option params [String] content_view_id  content view identifier
      # @option params [Array] repository_ids  list of repository ids
      # @option params [String] inclusion  specifies if content should be included or excluded, default: inclusion=false
      # @option params [String] name  name of the filter
      # @option params [String] type  type of filter (e.g. rpm, package_group, erratum)
      #
      # @param [Hash] headers additional http headers
      # @return [Array] First item: parsed data; second item: raw body
      def create(params = {}, headers = {})
        perform_call(__method__, params, headers)
      end

      # @param [Hash] params a hash of params to be passed to the service
      # @option params [String] id  filter identifier
      # @option params [String] content_view_id  content view identifier
      #
      # @param [Hash] headers additional http headers
      # @return [Array] First item: parsed data; second item: raw body
      def show(params = {}, headers = {})
        perform_call(__method__, params, headers)
      end

      # @param [Hash] params a hash of params to be passed to the service
      # @option params [String] id  filter identifier
      # @option params [String] content_view_id  content view identifier
      # @option params [Array] repository_ids  list of repository ids
      # @option params [String] inclusion  specifies if content should be included or excluded, default: inclusion=false
      # @option params [String] name  new name for the filter
      #
      # @param [Hash] headers additional http headers
      # @return [Array] First item: parsed data; second item: raw body
      def update(params = {}, headers = {})
        perform_call(__method__, params, headers)
      end

      # @param [Hash] params a hash of params to be passed to the service
      # @option params [String] id  filter identifier
      # @option params [String] content_view_id  content view identifier
      #
      # @param [Hash] headers additional http headers
      # @return [Array] First item: parsed data; second item: raw body
      def destroy(params = {}, headers = {})
        perform_call(__method__, params, headers)
      end

      # @param [Hash] params a hash of params to be passed to the service
      # @option params [String] id  filter identifier
      # @option params [String] content_view_id  content view identifier
      #
      # @param [Hash] headers additional http headers
      # @return [Array] First item: parsed data; second item: raw body
      def available_errata(params = {}, headers = {})
        perform_call(__method__, params, headers)
      end

      # @param [Hash] params a hash of params to be passed to the service
      # @option params [String] id  filter identifier
      # @option params [String] content_view_id  content view identifier
      #
      # @param [Hash] headers additional http headers
      # @return [Array] First item: parsed data; second item: raw body
      def available_package_groups(params = {}, headers = {})
        perform_call(__method__, params, headers)
      end

    end
  end
end


text:
var { createStore, applyMiddleware } = require('redux');
var thunk = require('redux-thunk');
var reducer = require('../reducers');

var createStoreWithMiddleware = applyMiddleware(
  thunk
)(createStore);

module.exports = function configureStore(initialState) {
  return createStoreWithMiddleware(reducer, initialState);
};


text:
var config = require('config'),
    databaseUrl = config.get('databaseUrl'),
    Sequelize = require("sequelize"),
    logging = require('../logging'),
    logger = logging.createLogger('database');

var match = databaseUrl.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/);
var user = match[1];
var password = match[2];
var host = match[3];
var port = match[4];
var dbName = match[5];

logger.info('Initializing Sequelize. Pointing to %s:%d/%s', host, port, dbName);
var sequelize = new Sequelize(dbName, user, password, {
    protocol: 'postgres',
    dialect: 'postgres',
    port: port,
    host: host,
    native: true
});

module.exports = {
    db: sequelize,
    models: {
        Ticket: sequelize.import(__dirname + '/models/ticket')
    }
};

if (config.get('recreateDb')) {
    logger.debug('Dropping database');

    sequelize.drop().then(function () {
        createTables();
    }, function(err) {
        logger.error(err, 'Error dropping tables');
    });
} else {
    createTables();
}

function createTables() {
    logger.debug('Syncing database');

    sequelize.sync().then(function() {
        logger.info('Synced all tables');
    }, function(error) {
        logger.error(error, 'Error syncing tables');
    });
}


text:
title: Analyzing My NYT Crossword Puzzle Data
author: Andrew Flack
date: '2017-10-18'
slug: analyzing-my-nyt-crossword-puzzle-data
categories: []
tags: []
draft: true
---


text:
class AddAlternateOptionToMember < ActiveRecord::Migration[4.2]
  def change
    add_column :members, :alternate, :boolean, default: false, null: false
  end
end


text: Repositorio personal para aprender GitHub.


text:
package com.tsystems.readyapi.plugin.websocket;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Date;

import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.ScrollPaneConstants;

import com.eviware.soapui.support.DateUtil;
import com.eviware.soapui.support.ListDataChangeListener;
import com.eviware.soapui.support.UISupport;
import com.eviware.soapui.support.components.JComponentInspector;
import com.eviware.soapui.support.components.JInspectorPanel;
import com.eviware.soapui.support.components.JInspectorPanelFactory;
import com.eviware.soapui.support.components.JXToolBar;
import com.eviware.soapui.support.components.SimpleBindingForm;
import com.eviware.soapui.support.log.JLogList;
import com.jgoodies.binding.PresentationModel;

public class DropConnectionTestStepPanel extends ConnectedTestStepPanel<DropConnectionTestStep> implements
        ExecutionListener {

    /** serialVersionUID description. */
    private static final long serialVersionUID = -8477527042685376996L;

    private final static String LOG_TAB_TITLE = "Test Step Log (%d)";

    private JInspectorPanel inspectorPanel;
    private JComponentInspector<JComponent> logInspector;
    private JLogList logArea;

    public DropConnectionTestStepPanel(DropConnectionTestStep modelItem) {
        super(modelItem);
        buildUI();
        modelItem.addExecutionListener(this);
    }

    private JComponent buildMainPanel() {
        PresentationModel<DropConnectionTestStep> pm = new PresentationModel<DropConnectionTestStep>(getModelItem());
        SimpleBindingForm form = new SimpleBindingForm(pm);
        buildConnectionSection(form, pm);
        form.appendSeparator();
        form.appendHeading("Settings");
        buildRadioButtonsFromEnum(form, pm, "Drop method", DropConnectionTestStep.DROP_METHOD_BEAN_PROP_NAME,
                DropConnectionTestStep.DropMethod.class);

        JPanel result = new JPanel(new BorderLayout(0, 0));
        result.add(new JScrollPane(form.getPanel(), ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
        result.add(buildToolbar(), BorderLayout.NORTH);

        return result;
    }

    protected JComponent buildLogPanel() {
        logArea = new JLogList("Test Step Log");

        logArea.getLogList().getModel().addListDataListener(new ListDataChangeListener() {

            @Override
            public void dataChanged(ListModel model) {
                logInspector.setTitle(String.format(LOG_TAB_TITLE, model.getSize()));
            }
        });

        return logArea;
    }

    @Override
    public void afterExecution(ExecutableTestStep testStep, ExecutableTestStepResult executionResult) {
        logArea.addLine(DateUtil.formatFull(new Date(executionResult.getTimeStamp())) + " - "
                + executionResult.getOutcome());
    }

    @Override
    protected boolean release() {
        getModelItem().removeExecutionListener(this);
        inspectorPanel.release();
        return super.release();
    }

    private JComponent buildToolbar() {
        JXToolBar toolBar = UISupport.createToolbar();
        addConnectionActionsToToolbar(toolBar);
        return toolBar;
    }

    private void buildUI() {
        JComponent mainPanel = buildMainPanel();
        inspectorPanel = JInspectorPanelFactory.build(mainPanel);

        logInspector = new JComponentInspector<JComponent>(buildLogPanel(), String.format(LOG_TAB_TITLE, 0),
                "Log of the test step executions", true);
        inspectorPanel.addInspector(logInspector);

        inspectorPanel.setDefaultDividerLocation(0.6F);

        add(inspectorPanel.getComponent());
        setPreferredSize(new Dimension(500, 300));

    }
}


text:
package io.cattle.platform.iaas.api.filter.instance;

import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.util.PortSpec;
import io.cattle.platform.iaas.api.filter.common.AbstractDefaultResourceManagerFilter;
import io.cattle.platform.object.util.DataUtils;
import io.github.ibuildthecloud.gdapi.exception.ValidationErrorException;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;
import io.github.ibuildthecloud.gdapi.request.resource.ResourceManager;
import io.github.ibuildthecloud.gdapi.validation.ValidationErrorCodes;

import java.util.List;

public class InstancePortsValidationFilter extends AbstractDefaultResourceManagerFilter {

    @Override
    public String[] getTypes() {
        return new String[] { "container", "virtualMachine" };
    }

    @Override
    public Class<?>[] getTypeClasses() {
        return new Class<?>[] { Instance.class };
    }

    @Override
    public Object create(String type, ApiRequest request, ResourceManager next) {
        List<?> ports = DataUtils.getFieldFromRequest(request, InstanceConstants.FIELD_PORTS, List.class);
        if (ports != null) {
            for (Object port : ports) {
                if (port == null) {
                    throw new ValidationErrorException(ValidationErrorCodes.MISSING_REQUIRED, InstanceConstants.FIELD_PORTS);
                }

                /* This will parse the PortSpec and throw an error */
                new PortSpec(port.toString());
            }
        }

        return super.create(type, request, next);
    }

}


text:
package bits.math3d.func;

/**
 * @author decamp
 */
@Deprecated public final class Gaussians {

    /**
     * Computes the sigma value of a gaussian whose output value
     * at specified distance divided its output value at zero is
     * <tt>falloffAtDist</tt>.
     *

     * For example, if

     * <tt>N(sigma,0)  == 0.5</tt>

     * and

     * <tt>N(sigma,2.0) == 0.05</tt>

     * then
     * <tt>sigma = falloffToSigma( 2.0, 0.1 )</tt>
     */
    public static double falloffToSigma( double dist, double falloffAtDist ) {
        return Math.sqrt( -dist * dist * 0.5 / Math.log( falloffAtDist ) );
    }

    /**
     * Computes distance from the zero at which a gaussian function with specified sigma value
     * will reach a particular attenuation point.
     *

     * For example, if

     * <tt>N(sigma,0) == 0.5</tt>

     * then

     * <tt>x = falloffToDist( sigma, 0.1 )</tt>

     * returns  an <tt>x</tt> such that:

     * <tt>N(sigma,x) == 0.05 == (0.5 * 0.1)</tt>
     */
    public static double falloffToDist( double sigma, double falloffAtDist ) {
        return Math.sqrt( -2.0 * sigma * sigma * Math.log( falloffAtDist ) );
    }

    /**
     * By specifying the sigma of a Gaussian and the desired ratio between the edge of
     * a Gaussian array and the center, this method will compute an appropriate kernel
     * length.
     *
     * @param sigma           The sigma value for the desired Gaussian array.
     * @param edgeCenterRatio The desired ratio between the edge of the calculated array and the center.
     *
     * @return The minimum length of the kernel needed to meet or exceed the provided ratio.
     */
    public static int computeKernalSize( double sigma, double edgeCenterRatio ) {
        double halfSize = falloffToDist( sigma, edgeCenterRatio );
        return (int)Math.ceil( halfSize ) * 2 + 1;
    }

    private Gaussians() {}

    /**
     * By specifying the ratio between the center and edge (not corner) of a Gaussian
     * and the size of the Gaussian array, this method will compute an appropriate
     * sigma.  For example, assume you want a 9x9 holding Gaussian distribution and
     * that you want the value at the edge of the array to be 5% of the highest value
     * in the Gaussian.  To find the appropriate sigma, you would call:
     *
     *  convertRatioToSigma(9, 0.05)
     *
     *  @param kernelLength  The desired length of one edge of a Gaussian array.
     *  @param ratioAtEdge   The desired ratio between the edge of the calculated array and the center.
     *
     *  @return A sigma that may be used for that Gaussian.
     *  @deprecated
     */
    public static double convertRatioToSigma(int kernelLength, double ratioAtEdge) {
        double halfSize = (kernelLength - 1) * 0.5;
        return Math.sqrt(-halfSize * halfSize * 0.5 / Math.log(ratioAtEdge));
    }

}


text:
<?php
if ($_GET['id'] > $user['progress']+1 && $user['permission'] != 1) {
    $question = $user['progress']+1;
    header("Location: ../Thestral/index.php?id=$question");
}


text:
namespace Restract.Contract.Attributes
{
    using System;

    public class ResourceAttribute : Attribute
    {
        public string ResourcePath { get; set; }

        public ResourceAttribute(string resourcePath)
        {
            ResourcePath = resourcePath;
        }
    }
}


text:
'use strict';

module.exports = function (x) {
	return Number.isInteger(+x);
}


text:
package javacommon.datamodifier.modifier;

import javacommon.datamodifier.DataModifier;

/**
 * @author badqiu
 */
public class ShortDataModifier implements DataModifier{
	public Object modify(Object value, String modifierArgument) {
		if(value == null) return null;
		if(value instanceof Short) return value;
		return new Short(value.toString());
	}
}


text:
package ems.idls.alarms;

/**
* ems/idls/alarms/AlarmNotificationSequenceHolder.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from alarms.idl
* Tuesday, January 15, 2015 5:02:23 PM CST
*/

/**
    * Sequence(Vector) of AlarmNotification structures
    */
public final class AlarmNotificationSequenceHolder implements org.omg.CORBA.portable.Streamable
{
  public ems.idls.alarms.AlarmNotification value[] = null;

  public AlarmNotificationSequenceHolder ()
  {
  }

  public AlarmNotificationSequenceHolder (ems.idls.alarms.AlarmNotification[] initialValue)
  {
    value = initialValue;
  }

  public void _read (org.omg.CORBA.portable.InputStream i)
  {
    value = ems.idls.alarms.AlarmNotificationSequenceHelper.read (i);
  }

  public void _write (org.omg.CORBA.portable.OutputStream o)
  {
    ems.idls.alarms.AlarmNotificationSequenceHelper.write (o, value);
  }

  public org.omg.CORBA.TypeCode _type ()
  {
    return ems.idls.alarms.AlarmNotificationSequenceHelper.type ();
  }

}


text:
import { Component, forwardRef, Input, OnInit } from '@angular/core';
import {
  ControlValueAccessor,
  FormBuilder,
  FormControl,
  FormGroup,
  NG_VALIDATORS,
  NG_VALUE_ACCESSOR,
  Validator, Validators
} from '@angular/forms';
import { PageComponent } from '@shared/components/page.component';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { TranslateService } from '@ngx-translate/core';
import {
  PolylineDecoratorSymbol,
  polylineDecoratorSymbolTranslationMap,
  PolylineSettings
} from '@home/components/widget/lib/maps/map-models';
import { WidgetService } from '@core/http/widget.service';

@Component({
  selector: 'tb-trip-animation-path-settings',
  templateUrl: './trip-animation-path-settings.component.html',
  styleUrls: ['./../widget-settings.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => TripAnimationPathSettingsComponent),
      multi: true
    },
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => TripAnimationPathSettingsComponent),
      multi: true
    }
  ]
})
export class TripAnimationPathSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator {

  @Input()
  disabled: boolean;

  functionScopeVariables = this.widgetService.getWidgetScopeVariables();

  private modelValue: PolylineSettings;

  private propagateChange = null;

  public tripAnimationPathSettingsFormGroup: FormGroup;

  polylineDecoratorSymbols = Object.values(PolylineDecoratorSymbol);

  polylineDecoratorSymbolTranslations = polylineDecoratorSymbolTranslationMap;

  constructor(protected store: Store<AppState>,
              private translate: TranslateService,
              private widgetService: WidgetService,
              private fb: FormBuilder) {
    super(store);
  }

  ngOnInit(): void {
    this.tripAnimationPathSettingsFormGroup = this.fb.group({
      color: [null, []],
      strokeWeight: [null, [Validators.min(0)]],
      strokeOpacity: [null, [Validators.min(0), Validators.max(1)]],
      useColorFunction: [null, []],
      colorFunction: [null, []],
      usePolylineDecorator: [null, []],
      decoratorSymbol: [null, []],
      decoratorSymbolSize: [null, [Validators.min(1)]],
      useDecoratorCustomColor: [null, []],
      decoratorCustomColor: [null, []],
      decoratorOffset: [null, []],
      endDecoratorOffset: [null, []],
      decoratorRepeat: [null, []],
    });
    this.tripAnimationPathSettingsFormGroup.valueChanges.subscribe(() => {
      this.updateModel();
    });
    this.tripAnimationPathSettingsFormGroup.get('useColorFunction').valueChanges.subscribe(() => {
      this.updateValidators(true);
    });
    this.tripAnimationPathSettingsFormGroup.get('usePolylineDecorator').valueChanges.subscribe(() => {
      this.updateValidators(true);
    });
    this.tripAnimationPathSettingsFormGroup.get('useDecoratorCustomColor').valueChanges.subscribe(() => {
      this.updateValidators(true);
    });
    this.updateValidators(false);
  }

  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }

  registerOnTouched(fn: any): void {
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
    if (isDisabled) {
      this.tripAnimationPathSettingsFormGroup.disable({emitEvent: false});
    } else {
      this.tripAnimationPathSettingsFormGroup.enable({emitEvent: false});
    }
  }

  writeValue(value: PolylineSettings): void {
    this.modelValue = value;
    this.tripAnimationPathSettingsFormGroup.patchValue(
      value, {emitEvent: false}
    );
    this.updateValidators(false);
  }

  public validate(c: FormControl) {
    return this.tripAnimationPathSettingsFormGroup.valid ? null : {
      tripAnimationPathSettings: {
        valid: false,
      },
    };
  }

  private updateModel() {
    const value: PolylineSettings = this.tripAnimationPathSettingsFormGroup.value;
    this.modelValue = value;
    this.propagateChange(this.modelValue);
  }

  private updateValidators(emitEvent?: boolean): void {
    const useColorFunction: boolean = this.tripAnimationPathSettingsFormGroup.get('useColorFunction').value;
    const usePolylineDecorator: boolean = this.tripAnimationPathSettingsFormGroup.get('usePolylineDecorator').value;
    const useDecoratorCustomColor: boolean = this.tripAnimationPathSettingsFormGroup.get('useDecoratorCustomColor').value;
    if (useColorFunction) {
      this.tripAnimationPathSettingsFormGroup.get('colorFunction').enable({emitEvent});
    } else {
      this.tripAnimationPathSettingsFormGroup.get('colorFunction').disable({emitEvent});
    }
    if (usePolylineDecorator) {
      this.tripAnimationPathSettingsFormGroup.get('decoratorSymbol').enable({emitEvent});
      this.tripAnimationPathSettingsFormGroup.get('decoratorSymbolSize').enable({emitEvent});
      this.tripAnimationPathSettingsFormGroup.get('useDecoratorCustomColor').enable({emitEvent: false});
      if (useDecoratorCustomColor) {
        this.tripAnimationPathSettingsFormGroup.get('decoratorCustomColor').enable({emitEvent});
      } else {
        this.tripAnimationPathSettingsFormGroup.get('decoratorCustomColor').disable({emitEvent});
      }
      this.tripAnimationPathSettingsFormGroup.get('decoratorOffset').enable({emitEvent});
      this.tripAnimationPathSettingsFormGroup.get('endDecoratorOffset').enable({emitEvent});
      this.tripAnimationPathSettingsFormGroup.get('decoratorRepeat').enable({emitEvent});
    } else {
      this.tripAnimationPathSettingsFormGroup.get('decoratorSymbol').disable({emitEvent});
      this.tripAnimationPathSettingsFormGroup.get('decoratorSymbolSize').disable({emitEvent});
      this.tripAnimationPathSettingsFormGroup.get('useDecoratorCustomColor').disable({emitEvent: false});
      this.tripAnimationPathSettingsFormGroup.get('decoratorCustomColor').disable({emitEvent});
      this.tripAnimationPathSettingsFormGroup.get('decoratorOffset').disable({emitEvent});
      this.tripAnimationPathSettingsFormGroup.get('endDecoratorOffset').disable({emitEvent});
      this.tripAnimationPathSettingsFormGroup.get('decoratorRepeat').disable({emitEvent});
    }
    this.tripAnimationPathSettingsFormGroup.get('colorFunction').updateValueAndValidity({emitEvent: false});
    this.tripAnimationPathSettingsFormGroup.get('decoratorSymbol').updateValueAndValidity({emitEvent: false});
    this.tripAnimationPathSettingsFormGroup.get('decoratorSymbolSize').updateValueAndValidity({emitEvent: false});
    this.tripAnimationPathSettingsFormGroup.get('useDecoratorCustomColor').updateValueAndValidity({emitEvent: false});
    this.tripAnimationPathSettingsFormGroup.get('decoratorCustomColor').updateValueAndValidity({emitEvent: false});
    this.tripAnimationPathSettingsFormGroup.get('decoratorOffset').updateValueAndValidity({emitEvent: false});
    this.tripAnimationPathSettingsFormGroup.get('endDecoratorOffset').updateValueAndValidity({emitEvent: false});
    this.tripAnimationPathSettingsFormGroup.get('decoratorRepeat').updateValueAndValidity({emitEvent: false});
  }
}


text:
// Type: Highsoft.Web.Mvc.Charts.AreaSeriesDataLabelsVerticalAlign

namespace Highsoft.Web.Mvc.Charts
{
    public enum AreaSeriesDataLabelsVerticalAlign
    {
        Null,
        Top,
        Middle,
        Bottom,
    }
}