text:
package net.sansa_stack.inference.rules

import scala.collection.mutable
import scalax.collection.Graph
import scalax.collection.edge.LDiEdge
import scalax.collection.mutable.DefaultGraphImpl

import org.apache.jena.reasoner.rulesys.Rule

/**
  * Given a set of rules R, a rule dependency graph (RDG) is a directed graph
  * G = (V, E) such that
  *

  *
each vertex in V represents a rule r_i from R and

  *
each edge (r_i, r_j) in E denotes the dependency between them

  *

  *
  * The dependency between two rules r_i and r_j, denoted as r_i -> r_j,
  * resp. "r_i depends on r_j" indicates that the result of r_j is used as
  * input of r_i. In particular, that means we use the same direction in the
  * graph although one would expect to have an edge from the rule r_j producing
  * the data to the rule r_i consuming the data.
  *
  * Some notes about the types used:
  * The Rule class stems from org.apache.jena.reasoner.rulesys and comprises a
  * list of antecedents (body) and a list of consequents (head), i.e.
  *
  *   consequent [, consequent] <- antecedent [, antecedent]
  *
  * where each consequent or antecedent can be a TriplePattern (i.e. a triple of
  * Nodes, themselves being either variables, wildcards, embedded functors, uri
  * or literal graph nodes), a Functor or a Rule.
  *
  * The Graph and LDiEdge ('labeled directed edge') classes stem from
  * scalax.collection which provides the main graph functionality.
  * Considering a scalax.collection.Graph two kinds of Nodes are distinguished:
  *
  * - Outer Nodes
  *   Outer nodes exist outside of the context of any particular graph and must
  *   be provided by the library user. When added to a graph, they will be
  *   transparently wrapped by a corresponding inner node. Outer nodes must
  *   satisfy the upper bound of the node type parameter of the graph
  * - Inner Nodes
  *   Inner nodes are objects bound to a particular graph. They are
  *   transparently created on graph instantiation or on adding nodes to a
  *   graph. Inner nodes are instances of the inner class NodeT, hence the
  *   term, and are implementing the InnerNodeLike interface. An inner node
  *   acts as a container of the corresponding outer node also providing a
  *   wealth of graph functionality such as diSuccessors or pathTo. Inner nodes
  *   always equal to the contained, user-provided outer node thus facilitating
  *   interchangeability of inner and outer nodes in many situations. Note that
  *   NodeT is a path dependent type such as g.NodeT with g denoting a single
  *   graph instance.
  *
  * (Descriptions taken from http://www.scala-graph.org/guides/core-inner-outer.html)
  *
  * @author Lorenz Buehmann
  * @author Patrick Westphal
  */
class RuleDependencyGraph(iniNodes: Iterable[Rule] = Set[Rule](),
                          iniEdges: Iterable[LDiEdge[Rule]] = Set[LDiEdge[Rule]]())
  extends DefaultGraphImpl[Rule, LDiEdge](iniNodes, iniEdges)(
    implicitly, DefaultGraphImpl.defaultConfig) {

  def this(graph: Graph[Rule, LDiEdge]) = {
    this(graph.nodes.toOuter, graph.edges.toOuter)
  }

  /**
    * This converts the graph-specific inner nodes to its corresponding outer
    * nodes which may exist outside a graph context.
    *
    * @return the set of rules contained in this graph
    */
  def rules(): Set[Rule] = nodes.toOuter

  /**
    * @return a simple string representation of this graph
    */
  def printNodes(): String = rules().map(r => r.getName).mkString("G(", "|", ")")

  /**
    * Applies topological sort and returns the resulting layers.
    * Each layer contains its level and a set of rules.
    *
    * @return the layers
    */
  def layers(): Traversable[(Int, Iterable[Rule])] = topologicalSort.right.get.toLayered
    .map(layer => (
      layer._1,
      layer._2.map(node => node.value
      ))
    )

  /**
    * Returns all nodes that are connected by an edge to itself.
    *
    * @return
    */
  def loopNodes(): mutable.Set[NodeBase] = {
    nodes.filter(n => n.outgoing.map(_.target).contains(n))
  }

  /**
    * Returns true if there is a cycle in the graph, i.e. either
    *
    * - there is a path n1 -> n2 ->  ... -> n1 or
    * - a loop, i.e. an edge that connects a vertex to itself.
    *
    * @return
    */
  def hasCycle(): Boolean = {
    loopNodes().nonEmpty || findCycle.isDefined
  }

}


text:
package natlab.tame.builtin.classprop.ast;

import java.util.List;

import natlab.tame.builtin.classprop.ClassPropMatch;
import natlab.tame.classes.reference.ClassReference;
import natlab.tame.valueanalysis.value.Value;

//begin - matches if the current read-index is 0, emits nothing
public class CPBegin extends CP{
    public String toString() { return "begin"; }
    public ClassPropMatch match(boolean isLeft,
            ClassPropMatch previousMatchResult,
            List<ClassReference> inputClasses, List<? extends Value<?>> inputValues) {
        return (previousMatchResult.getNumMatched() == 0)?previousMatchResult:null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

TRUSS BRIDGE MAKING

To design a "TRUSS BRIDGE" using popsicle stick(ice-cream sticks),white glue according to the stated constraints which can sustain maximum load. Dead weight will be measured and recorded. The weight will be uniformly distributed using plate and hanger arrangement or direct arrangement (By directly putting weights on truss bridge).

Prizes

Certificates of Excellence will be awarded to the winning team.

Contact Us

For more details write to us at hotdaranya9@gmail.com.


text:
package net.mindengine.jeremy.objects;

public class SuperSampleB extends SuperSample{

    private String B;

    public void setB(String b) {
        B = b;
    }

    public String getB() {
        return B;
    }

}


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

    Copyright (C) 2014 Bern University of Applied Sciences..

    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.

-->
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
      <groupId>eu.fusepool.p3.stanbol-launcher</groupId>
      <artifactId>stanbol-launcher-reactor</artifactId>
      <version>1.0.0-SNAPSHOT</version>
      <relativePath>../..</relativePath>
    </parent>

    <artifactId>stanbol-launcher-ld-sites-bundlelist</artifactId>
    <packaging>feature</packaging>

    <name>Fusepool Linked Data Site Bundlelist</name>
    <description>
      Provides Indexes for well known Vocabularies for EntityLinking. Each Site
      already comes with a comprehencive default configuration for Entity Linking
      that can be used wiht the Fusepool Literal Extraction Transformer
    </description>

    <dependencies>
        <dependency>
            <groupId>eu.fusepool.p3.stanbol-launcher</groupId>
            <artifactId>stanbol-data-site-iptc</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
          <groupId>eu.fusepool.p3.stanbol-launcher</groupId>
          <artifactId>stanbol-data-site-stw</artifactId>
          <version>${project.version}</version>
        </dependency>
        <dependency>
          <groupId>eu.fusepool.p3.stanbol-launcher</groupId>
          <artifactId>stanbol-data-site-thesoz</artifactId>
          <version>${project.version}</version>
        </dependency>
        <dependency>
          <groupId>eu.fusepool.p3.stanbol-launcher</groupId>
          <artifactId>stanbol-data-site-gnd</artifactId>
          <version>${project.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.wymiwyg.karaf.tooling</groupId>
                <artifactId>karaf-sling-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


text:
import zeit.cms.generation

def install(root):
    return  # Used to install teasergroup repository, which has been removed.

def evolve(context):
    zeit.cms.generation.do_evolve(context, install)


text:
package org.apache.ambari.server.serveraction.upgrades;

import java.text.MessageFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.actionmanager.HostRoleStatus;
import org.apache.ambari.server.agent.CommandReport;
import org.apache.ambari.server.serveraction.AbstractServerAction;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.Config;

import com.google.inject.Inject;

/**
 * Computes Ranger properties.  This class is only used when moving from
 * HDP-2.2 to HDP-2.3 in that upgrade pack.
 */
public class RangerConfigCalculation extends AbstractServerAction {
  private static final String SOURCE_CONFIG_TYPE = "admin-properties";

  @Inject
  private Clusters m_clusters;

  @Override
  public CommandReport execute(ConcurrentMap<String, Object> requestSharedDataContext)
      throws AmbariException, InterruptedException {

    String clusterName = getExecutionCommand().getClusterName();

    Cluster cluster = m_clusters.getCluster(clusterName);

    Config sourceConfig = cluster.getDesiredConfigByType(SOURCE_CONFIG_TYPE);

    if (null == sourceConfig) {
      return createCommandReport(0, HostRoleStatus.COMPLETED, "{}",
          MessageFormat.format("Source type {0} not found, skipping", SOURCE_CONFIG_TYPE), "");
    }

    String dbProp = "DB_FLAVOR";
    String dbHostProp = "db_host";
    String dbNameProp = "db_name";
    String dbAuditNameProp = "audit_db_name";

    StringBuilder stdout = new StringBuilder();

    String db = sourceConfig.getProperties().get(dbProp);
    if (null == db) {
      return createCommandReport(0, HostRoleStatus.COMPLETED, "{}",
          MessageFormat.format("Target database from {0}/{1} not found, skipping",
              SOURCE_CONFIG_TYPE, dbProp), "");
    }

    stdout.append(MessageFormat.format("Database type is {0}\n", db));

    db = db.toLowerCase();
    if (!"mysql".equals(db) && !"oracle".equals(db)) {
      stdout.append(MessageFormat.format("Target database {0} is not recognized, skipping", db));
      return createCommandReport(0, HostRoleStatus.COMPLETED, "{}", stdout.toString(), "");
    }

    String dbHost = sourceConfig.getProperties().get(dbHostProp);
    String dbName = sourceConfig.getProperties().get(dbNameProp);
    String auditDbName = sourceConfig.getProperties().get(dbAuditNameProp);

    // !!! just in case it's not set
    if (null == auditDbName) {
      auditDbName = dbName;
    }

    stdout.append(MessageFormat.format("Database host: {0}\n", dbHost));
    stdout.append(MessageFormat.format("Database name: {0}\n", dbName));
    stdout.append(MessageFormat.format("Audit database name: {0}\n", auditDbName));

    if (null == dbHost) {
      stdout.append(MessageFormat.format("Hostname must be set using {0}/{1} , skipping", SOURCE_CONFIG_TYPE, dbHostProp));

      return createCommandReport(0, HostRoleStatus.COMPLETED, "{}", stdout.toString(), "");
    }

    String driver = null;
    String url = null;
    String dialect = null;
    String auditUrl = null;

    if ("mysql".equals(db)) {
      if (null == dbName) {
        stdout.append(MessageFormat.format("Target database {0} requires {1} to be set, skipping", db, dbName));

        return createCommandReport(0, HostRoleStatus.COMPLETED, "{}", stdout.toString(), "");
      }
      driver = "com.mysql.jdbc.Driver";
      url = MessageFormat.format("jdbc:mysql://{0}/{1}", dbHost, dbName);
      auditUrl = MessageFormat.format("jdbc:mysql://{0}/{1}", dbHost, auditDbName);
      dialect = "org.eclipse.persistence.platform.database.MySQLPlatform";
    } else if ("oracle".equals(db)) {
      driver = "oracle.jdbc.OracleDriver";
      url = MessageFormat.format("jdbc:oracle:thin:@//{0}", dbHost);
      auditUrl = MessageFormat.format("jdbc:oracle:thin:@//{0}", dbHost);
      dialect = "org.eclipse.persistence.platform.database.OraclePlatform";
    }

    stdout.append(MessageFormat.format("Database driver: {0}\n", driver));
    stdout.append(MessageFormat.format("Database url: {0}\n", url));
    stdout.append(MessageFormat.format("Database audit url: {0}\n", auditUrl));
    stdout.append(MessageFormat.format("Database dialect: {0}", dialect));

    Config config = cluster.getDesiredConfigByType("ranger-admin-site");
    Map<String, String> targetValues = config.getProperties();
    targetValues.put("ranger.jpa.jdbc.driver", driver);
    targetValues.put("ranger.jpa.jdbc.url", url);
    targetValues.put("ranger.jpa.jdbc.dialect", dialect);

    targetValues.put("ranger.jpa.audit.jdbc.driver", driver);
    targetValues.put("ranger.jpa.audit.jdbc.url", auditUrl);
    targetValues.put("ranger.jpa.audit.jdbc.dialect", dialect);

    config.setProperties(targetValues);
    config.persist(false);

    return createCommandReport(0, HostRoleStatus.COMPLETED, "{}", stdout.toString(), "");
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ris.Data.Models;
using SQLite;

namespace Ris.Data
{
    public class RisDbContext
    {
        private const string DatabaseName = "rislocalcache.sqlite";

        private static SQLiteAsyncConnection CreateConnection()
        {
            return new SQLiteAsyncConnection(DatabaseName);
        }

        public static async Task InitializeDatabaseAsync()
        {
            var db = CreateConnection();
            CreateTablesResult result = await db.CreateTableAsync<DbRisQueryParameter>();
            result = await db.CreateTableAsync<DbDownloadedDocument>();
        }

        private readonly SQLiteAsyncConnection _connection;
        public RisDbContext()
        {
            _connection = CreateConnection();
        }

        public async Task InsertSearchHistoryEntry(DbRisQueryParameter rqp)
        {
            int result = await _connection.InsertAsync(rqp);
        }

        public async Task DeleteSearchHistoryEntry(DbRisQueryParameter rqp)
        {
            int result = await _connection.DeleteAsync(rqp);
        }

        public async Task<List<DbRisQueryParameter>> GetSearchHistoryEntries()
        {
            var query = _connection.Table<DbRisQueryParameter>().OrderByDescending(dqp => dqp.Executed);
            var history = await query.ToListAsync();

            return history;
        }

        public async Task<List<string>> GetHistoryEntriesStartingWith(string startsWith)
        {
            var query = _connection.Table<DbRisQueryParameter>()
                .Where(rqp => rqp.FulltextSearchString.StartsWith(startsWith));

            var matched = await query.ToListAsync();

            return matched.Select(rqp => rqp.FulltextSearchString).Distinct().ToList();
        }

        public async Task DeleteSearchHistory()
        {
            var result = await _connection.ExecuteAsync("DELETE FROM DbRisQueryParameter");
        }

        // Downloaded documents

        public async Task<DbDownloadedDocument> GetDownload(int id)
        {
            var doc = await _connection.Table<DbDownloadedDocument>().Where(d => d.Id == id).FirstOrDefaultAsync();
            return doc;
        }

        public async Task InsertDownload(DbDownloadedDocument doc)
        {
            int result = await _connection.InsertAsync(doc);
        }

        public async Task DeleteDownload(DbDownloadedDocument doc)
        {
            int result = await _connection.DeleteAsync(doc);
        }

        public async Task DeleteDownload(int id)
        {
            int result = await _connection.DeleteAsync(new DbDownloadedDocument() { Id = id });
        }

        public async Task RefreshDownload(DbDownloadedDocument doc, int idToReplace)
        {
            // TODO: do it properly in a transaction *or* use InsertOrReplace
            await DeleteDownload(idToReplace);
            await InsertDownload(doc);
        }

        public async Task<List<DbDownloadedDocument>> GetDownloads()
        {
            var query = _connection.Table<DbDownloadedDocument>().OrderByDescending(doc => doc.LastDownloaded);
            var history = await query.ToListAsync();

            return history;
        }

        public async Task DeleteDownloads()
        {
            var result = await _connection.ExecuteAsync("DELETE FROM DbDownloadedDocument");
        }
    }
}


text:
{% extends "layout/base.html" %}
{% load staticfiles i18n flisol_event_tags %}
{% block search %}

<form class="searchplace">

          <input type="text" placeholder="{% trans 'Where is your Flisol?' %}" id="flisol-place">

  </form>

{% endblock %}

{% block content %}

  ×

{% trans 'The planned places' %}

{% trans 'More options' %}

{% basic_forms %}

  {% if days_to_go > 0 %}

{% blocktrans %}{{ days_to_go }} days for Flisol{% endblocktrans %}

  {% elif days_to_go == 0 %}

{% blocktrans %}Today is Flisol, hang on{% endblocktrans %}

  {% endif %}

{{ subscriptions }} {% if subscriptions == 1 %}{%trans 'subscription' %}{% else %}{% trans 'subscriptions' %}{% endif %}

{{ instances }} {% if instances == 1 %}{% trans 'instance' %}{% else %}{% trans 'instances' %}{% endif %}

{{ volunteers }} {% if volunteers == 1 %}{% trans 'volunteer' %}{% else %}{% trans 'volunteers' %}{% endif %}

{% endblock content %}

{% block body_js %}

{% endblock %}


text:
"""Command line tool that wraps Python Duco."""
import logging
import argparse
from duco.const import (PROJECT_PACKAGE_NAME)
from duco.enum_types import (ModuleType, ZoneAction)
from duco.duco import (DucoBox)

_LOGGER = logging.getLogger(PROJECT_PACKAGE_NAME)

def configure_logging():
    """Configure logging for command line."""
    _LOGGER.setLevel(logging.DEBUG)

    # create console handler and set level to debug
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)

    # create formatter
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # add formatter to console
    console.setFormatter(formatter)

    # add console to logger
    _LOGGER.addHandler(console)

def parse_args():
    """Parse command line arguments."""
    description = 'Command line interface to Duco Ventilation System'
    parser = argparse.ArgumentParser(description=description)

    parser.add_argument('--type', dest='modbus_type',
                        default='serial', help='modbus client type; '
                        'supported: serial, tcp')

    parser.add_argument('--port', dest='modbus_port',
                        help='modbus client port ')

    parser.add_argument('--host', dest='modbus_host',
                        default='localhost',
                        help='optional, modbus tcp host')

    return parser.parse_args()

def main():
    """Execute main function."""
    args = parse_args()

    configure_logging()

    with DucoBox(args.modbus_type, args.modbus_port,
                 args.modbus_host) as duco_box:
        for node in duco_box.node_list:
            print(node)
            if node.node_type == ModuleType.USER_CONTROLLER:
                node.action = ZoneAction.ZONE_TO_AUTO
                print(node)

if __name__ == '__main__':
    main()


text:
import socket
import sys

class Server:
    def __init__(self, port=8888, host=''):

        self._host = host
        self._port = port
        self._clients = []
        self._addr = ''
        self._pseudo = ''

        # UDP socket
        try :
            self._s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            print('Socket created')
        except (socket.error, msg):
            print('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
            sys.exit()

        # Bind socket to local host and port
        self._s.bind((self._host, self._port))

        print('Socket bind complete')
        print('listening on ' + self._host + ':' + str(self._port))

    def run(self):
        # now keep talking with the client
        while True:
            # receive data from client (data, addr)
            d = self._s.recvfrom(1024)
            data = d[0]
            self._addr = d[1]

            # don't continue if we didn't receive anything
            if not data:
                break

            err_msg = 'Commande inconnue, écrivez /join pour vous ajouter à la liste des clients disponibles ou /clients pour consulter cette liste.\n'

            if data.decode() == '/join':
                if self._pseudo == '':
                    self._s.sendto('Veuillez définir vortre pseudo avec /pseudo <nom> avant de rejoindre le serveur'.encode(), self._addr)
                else:
                    self._join()
            elif data.decode() == '/clients':
                message = str(self._clients) + '\n'
                self._s.sendto(message.encode(), self._addr)
            elif '/pseudo' in data.decode():
                try:
                    self._pseudo = data.decode().split()[1]
                except:
                    self._s.sendto('Veuillez définir vortre pseudo avec /pseudo <nom>.'.encode(), self._addr)
                confirm = 'Votre pseudo, ' + self._pseudo + ', a bien été enregistré.'
                self._s.sendto(confirm.encode(), self._addr)
            else:
                self._s.sendto(err_msg.encode(), self._addr)

            # log all messages
            print('Message[' + self._addr[0] + ':' + str(self._addr[1]) + '] - ' + data.decode().strip())

    def _join(self):
        if self._pseudo in self._clients:
            reply = 'Vous êtes déjà dans la liste des clients disponibles\nÉcrivez /clients pour voir la liste des clients disponibles\n'
        else:
            self._clients.append(self._pseudo)
            reply = 'Vous avez été ajouté à la liste des clients disponibles\nÉcrivez /clients pour voir la liste des clients disponibles\n'

        self._s.sendto(reply.encode(), self._addr)

if __name__ == '__main__':
    if len(sys.argv) > 1 and type(sys.argv[1]):
        try:
            Server(int(sys.argv[1])).run()
        except:
            print('Please enter a port number')
    else:
        Server().run()


text:
import * as models from '../../models';
import * as importUtil from '../import';
import { getAppVersion } from '../constants';
import { globalBeforeEach } from '../../__jest__/before-each';
import YAML from 'yaml';

describe('exportWorkspacesHAR() and exportRequestsHAR()', () => {
  beforeEach(globalBeforeEach);
  it('exports a single workspace and some requests only as an HTTP Archive', async () => {
    const wrk1 = await models.workspace.create({
      _id: 'wrk_1',
      name: 'Workspace 1',
    });
    const req1 = await models.request.create({
      _id: 'req_1',
      name: 'Request 1',
      parentId: wrk1._id,
      headers: [{ name: 'X-Environment', value: '{{ envvalue }}' }],
      metaSortKey: 0,
    });
    const req2 = await models.request.create({
      _id: 'req_2',
      name: 'Request 2',
      parentId: wrk1._id,
      metaSortKey: 1,
    });
    let env1Base = await models.environment.getOrCreateForWorkspace(wrk1);
    env1Base = await models.environment.update(env1Base, {
      data: {
        envvalue: 'base1',
      },
    });
    const env1Private = await models.environment.create({
      name: 'Private',
      parentId: env1Base._id,
      data: {
        envvalue: 'private1',
      },
    });
    await models.workspaceMeta.create({
      parentId: wrk1._id,
      activeEnvironmentId: env1Private._id,
    });

    const wrk2 = await models.workspace.create({
      _id: 'wrk_2',
      name: 'Workspace 2',
    });
    await models.request.create({
      _id: 'req_3',
      name: 'Request 3',
      parentId: wrk2._id,
    });

    const includePrivateDocs = true;

    // Test export whole workspace.
    const exportWorkspacesJson = await importUtil.exportWorkspacesHAR(wrk1, includePrivateDocs);
    const exportWorkspacesData = JSON.parse(exportWorkspacesJson);
    expect(exportWorkspacesData).toMatchObject({
      log: {
        entries: [
          {
            request: {
              headers: [{ name: 'X-Environment', value: 'private1' }],
            },
            comment: req1.name,
          },
          {
            comment: req2.name,
          },
        ],
      },
    });
    expect(exportWorkspacesData.log.entries.length).toBe(2);

    // Test export some requests only.
    const exportRequestsJson = await importUtil.exportRequestsHAR([req1], includePrivateDocs);
    const exportRequestsData = JSON.parse(exportRequestsJson);
    expect(exportRequestsData).toMatchObject({
      log: {
        entries: [
          {
            request: {
              headers: [{ name: 'X-Environment', value: 'private1' }],
            },
            comment: req1.name,
          },
        ],
      },
    });
    expect(exportRequestsData.log.entries.length).toBe(1);
  });
  it('exports all workspaces as an HTTP Archive', async () => {
    const wrk1 = await models.workspace.create({
      _id: 'wrk_1',
      name: 'Workspace 1',
    });
    const wrk2 = await models.workspace.create({
      _id: 'wrk_2',
      name: 'Workspace 2',
    });
    await models.request.create({
      _id: 'req_1',
      name: 'Request 1',
      parentId: wrk1._id,
      headers: [{ name: 'X-Environment', value: '{{ envvalue }}' }],
    });
    await models.request.create({
      _id: 'req_2',
      name: 'Request 2',
      parentId: wrk2._id,
      headers: [{ name: 'X-Environment', value: '{{ envvalue }}' }],
    });

    let env1Base = await models.environment.getOrCreateForWorkspace(wrk1);
    env1Base = await models.environment.update(env1Base, {
      data: {
        envvalue: 'base1',
      },
    });
    const env1Public = await models.environment.create({
      name: 'Public',
      parentId: env1Base._id,
      data: {
        envvalue: 'public1',
      },
    });
    const env2Base = await models.environment.getOrCreateForWorkspace(wrk2);
    await models.environment.update(env2Base, {
      data: {
        envvalue: 'base2',
      },
    });
    const env2Private = await models.environment.create({
      name: 'Private',
      isPrivate: true,
      parentId: env1Base._id,
      data: {
        envvalue: 'private2',
      },
    });

    await models.workspaceMeta.create({
      parentId: wrk1._id,
      activeEnvironmentId: env1Public._id,
    });
    await models.workspaceMeta.create({
      parentId: wrk2._id,
      activeEnvironmentId: env2Private._id,
    });

    const includePrivateDocs = false;
    const json = await importUtil.exportWorkspacesHAR(null, includePrivateDocs);
    const data = JSON.parse(json);

    expect(data).toMatchObject({
      log: {
        entries: expect.arrayContaining([
          expect.objectContaining({
            request: expect.objectContaining({
              headers: [{ name: 'X-Environment', value: 'public1' }],
            }),
            comment: 'Request 1',
          }),
          expect.objectContaining({
            request: expect.objectContaining({
              headers: [{ name: 'X-Environment', value: 'base2' }],
            }),
            comment: 'Request 2',
          }),
        ]),
      },
    });
  });
});

describe('export', () => {
  beforeEach(globalBeforeEach);
  it('exports all workspaces and some requests only', async () => {
    const w = await models.workspace.create({ name: 'Workspace' });
    const jar = await models.cookieJar.getOrCreateForParentId(w._id);
    const r1 = await models.request.create({
      name: 'Request 1',
      parentId: w._id,
    });
    const f2 = await models.requestGroup.create({
      name: 'Folder 2',
      parentId: w._id,
    });
    const r2 = await models.request.create({
      name: 'Request 2',
      parentId: f2._id,
    });
    const eBase = await models.environment.getOrCreateForWorkspace(w);
    const ePub = await models.environment.create({
      name: 'Public',
      parentId: eBase._id,
    });
    await models.environment.create({
      name: 'Private',
      isPrivate: true,
      parentId: eBase._id,
    });

    // Test export whole workspace.
    const exportedWorkspacesJson = await importUtil.exportWorkspacesData(null, false, 'json');
    const exportedWorkspacesYaml = await importUtil.exportWorkspacesData(null, false, 'yaml');
    const exportWorkspacesDataJson = JSON.parse(exportedWorkspacesJson);
    const exportWorkspacesDataYaml = YAML.parse(exportedWorkspacesYaml);

    // Ensure JSON is the same as YAML
    expect(exportWorkspacesDataJson.resources).toEqual(exportWorkspacesDataYaml.resources);

    expect(exportWorkspacesDataJson).toMatchObject({
      _type: 'export',
      __export_format: 4,
      __export_date: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/),
      __export_source: `insomnia.desktop.app:v${getAppVersion()}`,
      resources: expect.arrayContaining([
        expect.objectContaining({ _id: w._id }),
        expect.objectContaining({ _id: eBase._id }),
        expect.objectContaining({ _id: jar._id }),
        expect.objectContaining({ _id: r1._id }),
        expect.objectContaining({ _id: f2._id }),
        expect.objectContaining({ _id: r2._id }),
        expect.objectContaining({ _id: ePub._id }),
      ]),
    });
    expect(exportWorkspacesDataJson.resources.length).toBe(7);

    // Test export some requests only.
    const exportRequestsJson = await importUtil.exportRequestsData([r1], false, 'json');
    const exportRequestsYaml = await importUtil.exportRequestsData([r1], false, 'yaml');
    const exportRequestsDataJSON = JSON.parse(exportRequestsJson);
    const exportRequestsDataYAML = YAML.parse(exportRequestsYaml);

    expect(exportRequestsDataJSON).toMatchObject({
      _type: 'export',
      __export_format: 4,
      __export_date: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/),
      __export_source: `insomnia.desktop.app:v${getAppVersion()}`,
      resources: expect.arrayContaining([
        expect.objectContaining({ _id: w._id }),
        expect.objectContaining({ _id: eBase._id }),
        expect.objectContaining({ _id: jar._id }),
        expect.objectContaining({ _id: r1._id }),
        expect.objectContaining({ _id: ePub._id }),
      ]),
    });

    expect(exportRequestsDataJSON.resources.length).toBe(5);
    expect(exportRequestsDataYAML.resources.length).toBe(5);

    // Ensure JSON and YAML are the same
    expect(exportRequestsDataJSON.resources).toEqual(exportRequestsDataYAML.resources);
  });
});


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;

public class PlayerControler : MonoBehaviour {

	private Rigidbody rigidBody;
	public float SPEED;
	public Text scoreText;
	public Text gameOverText;
	private int score = 0;

	void Start()
	{
		gameOverText.gameObject.SetActive (false);
		rigidBody = GetComponent<Rigidbody> ();
		score = 0;
		setScore();
	}

	void FixedUpdate()
	{
		float moveHorizontal = Input.GetAxis ("Horizontal");
		float moveVertical = Input.GetAxis ("Vertical");

		Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);

		rigidBody.AddForce (movement * SPEED);
	}

	void OnTriggerEnter(Collider other)
	{
		if(other.gameObject.CompareTag("pickup"))
		{
			other.gameObject.SetActive(false);
			score++;
			setScore();
			if (score >= 17) {
				gameOverText.gameObject.SetActive (true);
			}
		}
	}

	void setScore(){
		scoreText.text = "Score : " + score.ToString();

	}

	void Update() {
		if (transform.position.y < -10) {
			gameOverText.gameObject.SetActive (true);
		}
	}
}


text:
package org.whitestryder.labs.app.activity.inventory;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whitestryder.labs.app.support.ApplicationException;
import org.whitestryder.labs.app.support.AuthenticatedUserContextService;
import org.whitestryder.labs.app.support.EntityNotFoundException;
import org.whitestryder.labs.app.support.InventoryItemQuery;
import org.whitestryder.labs.app.support.InventoryItemRepository;
import org.whitestryder.labs.app.support.UserContext;
import org.whitestryder.labs.core.InventoryItem;

/**
 * Provides a way to update an inventory item for an authenticated 'admin' role user.
 */
public class UpdateInventoryItemImpl implements UpdateInventoryItem {

	/** The log. */
	private static Logger LOG = LoggerFactory.getLogger(UpdateInventoryItemImpl.class);

	/** The repository. */
	private InventoryItemRepository repository;

	/** The query. */
	private InventoryItemQuery query;

	/** The user context service. */
	private AuthenticatedUserContextService userContextService;

	/**
	 * Instantiates a new update inventory item impl.
	 *
	 * @param repository the repository
	 * @param query the query
	 * @param userContextService the user context service
	 */
	public UpdateInventoryItemImpl(InventoryItemRepository repository,
			InventoryItemQuery query,
			AuthenticatedUserContextService userContextService){
		this.repository = repository;
		this.userContextService = userContextService;
		this.query = query;
	}

	@Override
	public InventoryItem execute(InventoryItem item, String refId) throws ApplicationException {

		UserContext user = userContextService.getAuthenticatedUser();

		List<InventoryItem> foundItems = query.findByExternalReferenceId(refId);

		if (foundItems.isEmpty()){
			throw new EntityNotFoundException(
					String.format("The inventory item with refId '%s' does not exist", refId));
		} else if (foundItems.size() > 1){
    		throw new ApplicationException(
    				String.format("More than one item with the refId %s was found!", refId));
    	}

    	InventoryItem itemToUpdate = foundItems.get(0);

    	itemToUpdate.update(item.getDescription(), item.getPrice(), item.getQuantityInStock());

		repository.save(itemToUpdate);

		LOG.info(String.format("User '%s' updated item %s", user.getUsername(), item.toString()));

		return itemToUpdate;
	}

}


text:
package com.shopify.android.beermon.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.TextView;
import com.shopify.android.beermon.R;

/**
 * Created with IntelliJ IDEA.
 * User: carson
 * Date: 2012-10-18
 * Time: 2:10 PM
 * To change this template use File | Settings | File Templates.
 */
public class SlantedTextView extends TextView {
    public int angle;

    private void setupAngle(Context context, AttributeSet attrs) {
        TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.SlantedText);
        this.angle = styledAttrs.getInt(R.styleable.SlantedText_slantedTextAngle, 0);
    }

    public SlantedTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setupAngle(context, attrs);
    }

    public SlantedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setupAngle(context, attrs);
    }

    public SlantedTextView(Context context) {
        super(context);
        angle = 0;
    }

    protected void onDraw(Canvas canvas) {
        //This saves the matrix that the canvas applies to draws, so it can be restored later.
        canvas.save();

        //now we change the matrix
        //We need to rotate around the center of our text
        //Otherwise it rotates around the origin, and that's bad.
        float py = this.getHeight()/2.0f;
        float px = this.getWidth()/2.0f;
        canvas.rotate(angle, px, py);

        //draw the text with the matrix applied.
        super.onDraw(canvas);

        //restore the old matrix.
        canvas.restore();
    }
}


text:
import State, {makeInvalidMessage, isValidDataTypes} from '../../core/State';
import Data, {DataTypes} from '../../core/Data';

export default class ToUpperCase extends State {
  constructor() {
    super(
      makeInvalidMessage("ToUpperCase", ["str"]),
      DataTypes.string
    );
  }

  isValid(childrenNode) {
    const nodesNum = childrenNode.length;
    if (nodesNum == 1) {
      if (isValidDataTypes(childrenNode, [DataTypes.string])) {
        return true;
      }
    }
    return false;
  }

  process(childrenNode) {
    let res = childrenNode[0].data.value;

    res = res.toUpperCase();

    return new Data(res, this.dataType);
  }
}


text:
package org.t246osslab.easybuggy.errors;

import java.io.IOException;
import java.util.Properties;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.t246osslab.easybuggy.core.servlets.AbstractServlet;

@SuppressWarnings("serial")
@WebServlet(urlPatterns = { "/oome4" })
public class OutOfMemoryErrorServlet4 extends AbstractServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        Properties properties = System.getProperties();
        Random r = new Random();
        while (true) {
            properties.put(r.nextInt(), "value");
        }
    }
}


text:
package com.amazonaws.services.budgets.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ApprovalModel {

    AUTOMATIC("AUTOMATIC"),
    MANUAL("MANUAL");

    private String value;

    private ApprovalModel(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ApprovalModel corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static ApprovalModel fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ApprovalModel enumEntry : ApprovalModel.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
package org.apache.kafka.connect.storage;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.common.errors.TimeoutException;
import org.apache.kafka.common.errors.UnknownServerException;
import org.apache.kafka.common.record.TimestampType;
import org.apache.kafka.common.utils.MockTime;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaAndValue;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.runtime.ConnectorStatus;
import org.apache.kafka.connect.runtime.TaskStatus;
import org.apache.kafka.connect.util.ConnectorTaskId;
import org.apache.kafka.connect.util.KafkaBasedLog;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.EasyMockSupport;
import org.easymock.IAnswer;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.newCapture;
import static org.junit.Assert.assertEquals;

@SuppressWarnings("unchecked")
public class KafkaStatusBackingStoreTest extends EasyMockSupport {

    private static final String STATUS_TOPIC = "status-topic";
    private static final String WORKER_ID = "localhost:8083";
    private static final String CONNECTOR = "conn";
    private static final ConnectorTaskId TASK = new ConnectorTaskId(CONNECTOR, 0);

    @Test
    public void putConnectorState() {
        KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
        Converter converter = mock(Converter.class);
        KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

        byte[] value = new byte[0];
        expect(converter.fromConnectData(eq(STATUS_TOPIC), anyObject(Schema.class), anyObject(Struct.class)))
                .andStubReturn(value);

        final Capture<Callback> callbackCapture = newCapture();
        kafkaBasedLog.send(eq("status-connector-conn"), eq(value), capture(callbackCapture));
        expectLastCall()
                .andAnswer(new IAnswer<Void>() {
                    @Override
                    public Void answer() throws Throwable {
                        callbackCapture.getValue().onCompletion(null, null);
                        return null;
                    }
                });
        replayAll();

        ConnectorStatus status = new ConnectorStatus(CONNECTOR, ConnectorStatus.State.RUNNING, WORKER_ID, 0);
        store.put(status);

        // state is not visible until read back from the log
        assertEquals(null, store.get(CONNECTOR));

        verifyAll();
    }

    @Test
    public void putConnectorStateRetriableFailure() {
        KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
        Converter converter = mock(Converter.class);
        KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

        byte[] value = new byte[0];
        expect(converter.fromConnectData(eq(STATUS_TOPIC), anyObject(Schema.class), anyObject(Struct.class)))
                .andStubReturn(value);

        final Capture<Callback> callbackCapture = newCapture();
        kafkaBasedLog.send(eq("status-connector-conn"), eq(value), capture(callbackCapture));
        expectLastCall()
                .andAnswer(new IAnswer<Void>() {
                    @Override
                    public Void answer() throws Throwable {
                        callbackCapture.getValue().onCompletion(null, new TimeoutException());
                        return null;
                    }
                })
                .andAnswer(new IAnswer<Void>() {
                    @Override
                    public Void answer() throws Throwable {
                        callbackCapture.getValue().onCompletion(null, null);
                        return null;
                    }
                });
        replayAll();

        ConnectorStatus status = new ConnectorStatus(CONNECTOR, ConnectorStatus.State.RUNNING, WORKER_ID, 0);
        store.put(status);

        // state is not visible until read back from the log
        assertEquals(null, store.get(CONNECTOR));

        verifyAll();
    }

    @Test
    public void putConnectorStateNonRetriableFailure() {
        KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
        Converter converter = mock(Converter.class);
        KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

        byte[] value = new byte[0];
        expect(converter.fromConnectData(eq(STATUS_TOPIC), anyObject(Schema.class), anyObject(Struct.class)))
                .andStubReturn(value);

        final Capture<Callback> callbackCapture = newCapture();
        kafkaBasedLog.send(eq("status-connector-conn"), eq(value), capture(callbackCapture));
        expectLastCall()
                .andAnswer(new IAnswer<Void>() {
                    @Override
                    public Void answer() throws Throwable {
                        callbackCapture.getValue().onCompletion(null, new UnknownServerException());
                        return null;
                    }
                });
        replayAll();

        // the error is logged and ignored
        ConnectorStatus status = new ConnectorStatus(CONNECTOR, ConnectorStatus.State.RUNNING, WORKER_ID, 0);
        store.put(status);

        // state is not visible until read back from the log
        assertEquals(null, store.get(CONNECTOR));

        verifyAll();
    }

    @Test
    public void putSafeConnectorIgnoresStaleStatus() {
        byte[] value = new byte[0];
        String otherWorkerId = "anotherhost:8083";

        KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
        Converter converter = mock(Converter.class);
        KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

        // the persisted came from a different host and has a newer generation
        Map<String, Object> statusMap = new HashMap<>();
        statusMap.put("worker_id", otherWorkerId);
        statusMap.put("state", "RUNNING");
        statusMap.put("generation", 1L);

        expect(converter.toConnectData(STATUS_TOPIC, value))
                .andReturn(new SchemaAndValue(null, statusMap));

        // we're verifying that there is no call to KafkaBasedLog.send

        replayAll();

        store.read(consumerRecord(0, "status-connector-conn", value));
        store.putSafe(new ConnectorStatus(CONNECTOR, ConnectorStatus.State.UNASSIGNED, WORKER_ID, 0));

        ConnectorStatus status = new ConnectorStatus(CONNECTOR, ConnectorStatus.State.RUNNING, otherWorkerId, 1);
        assertEquals(status, store.get(CONNECTOR));

        verifyAll();
    }

    @Test
    public void putSafeWithNoPreviousValueIsPropagated() {
        final Converter converter = mock(Converter.class);
        final KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
        final KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

        final byte[] value = new byte[0];

        final Capture<Struct> statusValueStruct = newCapture();
        converter.fromConnectData(eq(STATUS_TOPIC), anyObject(Schema.class), capture(statusValueStruct));
        EasyMock.expectLastCall().andReturn(value);

        kafkaBasedLog.send(eq("status-connector-" + CONNECTOR), eq(value), anyObject(Callback.class));
        expectLastCall();

        replayAll();

        final ConnectorStatus status = new ConnectorStatus(CONNECTOR, ConnectorStatus.State.FAILED, WORKER_ID, 0);
        store.putSafe(status);

        verifyAll();

        assertEquals(status.state().toString(), statusValueStruct.getValue().get(KafkaStatusBackingStore.STATE_KEY_NAME));
        assertEquals(status.workerId(), statusValueStruct.getValue().get(KafkaStatusBackingStore.WORKER_ID_KEY_NAME));
        assertEquals(status.generation(), statusValueStruct.getValue().get(KafkaStatusBackingStore.GENERATION_KEY_NAME));
    }

    @Test
    public void putSafeOverridesValueSetBySameWorker() {
        final byte[] value = new byte[0];

        KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
        Converter converter = mock(Converter.class);
        final KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

        // the persisted came from the same host, but has a newer generation
        Map<String, Object> firstStatusRead = new HashMap<>();
        firstStatusRead.put("worker_id", WORKER_ID);
        firstStatusRead.put("state", "RUNNING");
        firstStatusRead.put("generation", 1L);

        Map<String, Object> secondStatusRead = new HashMap<>();
        secondStatusRead.put("worker_id", WORKER_ID);
        secondStatusRead.put("state", "UNASSIGNED");
        secondStatusRead.put("generation", 0L);

        expect(converter.toConnectData(STATUS_TOPIC, value))
                .andReturn(new SchemaAndValue(null, firstStatusRead))
                .andReturn(new SchemaAndValue(null, secondStatusRead));

        expect(converter.fromConnectData(eq(STATUS_TOPIC), anyObject(Schema.class), anyObject(Struct.class)))
                .andStubReturn(value);

        final Capture<Callback> callbackCapture = newCapture();
        kafkaBasedLog.send(eq("status-connector-conn"), eq(value), capture(callbackCapture));
        expectLastCall()
                .andAnswer(new IAnswer<Void>() {
                    @Override
                    public Void answer() throws Throwable {
                        callbackCapture.getValue().onCompletion(null, null);
                        store.read(consumerRecord(1, "status-connector-conn", value));
                        return null;
                    }
                });

        replayAll();

        store.read(consumerRecord(0, "status-connector-conn", value));
        store.putSafe(new ConnectorStatus(CONNECTOR, ConnectorStatus.State.UNASSIGNED, WORKER_ID, 0));

        ConnectorStatus status = new ConnectorStatus(CONNECTOR, ConnectorStatus.State.UNASSIGNED, WORKER_ID, 0);
        assertEquals(status, store.get(CONNECTOR));

        verifyAll();
    }

    @Test
    public void putConnectorStateShouldOverride() {
        final byte[] value = new byte[0];
        String otherWorkerId = "anotherhost:8083";

        KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
        Converter converter = mock(Converter.class);
        final KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

        // the persisted came from a different host and has a newer generation
        Map<String, Object> firstStatusRead = new HashMap<>();
        firstStatusRead.put("worker_id", otherWorkerId);
        firstStatusRead.put("state", "RUNNING");
        firstStatusRead.put("generation", 1L);

        Map<String, Object> secondStatusRead = new HashMap<>();
        secondStatusRead.put("worker_id", WORKER_ID);
        secondStatusRead.put("state", "UNASSIGNED");
        secondStatusRead.put("generation", 0L);

        expect(converter.toConnectData(STATUS_TOPIC, value))
                .andReturn(new SchemaAndValue(null, firstStatusRead))
                .andReturn(new SchemaAndValue(null, secondStatusRead));

        expect(converter.fromConnectData(eq(STATUS_TOPIC), anyObject(Schema.class), anyObject(Struct.class)))
                .andStubReturn(value);

        final Capture<Callback> callbackCapture = newCapture();
        kafkaBasedLog.send(eq("status-connector-conn"), eq(value), capture(callbackCapture));
        expectLastCall()
                .andAnswer(new IAnswer<Void>() {
                    @Override
                    public Void answer() throws Throwable {
                        callbackCapture.getValue().onCompletion(null, null);
                        store.read(consumerRecord(1, "status-connector-conn", value));
                        return null;
                    }
                });
        replayAll();

        store.read(consumerRecord(0, "status-connector-conn", value));

        ConnectorStatus status = new ConnectorStatus(CONNECTOR, ConnectorStatus.State.UNASSIGNED, WORKER_ID, 0);
        store.put(status);
        assertEquals(status, store.get(CONNECTOR));

        verifyAll();
    }

    @Test
    public void readConnectorState() {
        byte[] value = new byte[0];

        KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
        Converter converter = mock(Converter.class);
        KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

        Map<String, Object> statusMap = new HashMap<>();
        statusMap.put("worker_id", WORKER_ID);
        statusMap.put("state", "RUNNING");
        statusMap.put("generation", 0L);

        expect(converter.toConnectData(STATUS_TOPIC, value))
                .andReturn(new SchemaAndValue(null, statusMap));

        replayAll();

        store.read(consumerRecord(0, "status-connector-conn", value));

        ConnectorStatus status = new ConnectorStatus(CONNECTOR, ConnectorStatus.State.RUNNING, WORKER_ID, 0);
        assertEquals(status, store.get(CONNECTOR));

        verifyAll();
    }

    @Test
    public void putTaskState() {
        KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
        Converter converter = mock(Converter.class);
        KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

        byte[] value = new byte[0];
        expect(converter.fromConnectData(eq(STATUS_TOPIC), anyObject(Schema.class), anyObject(Struct.class)))
                .andStubReturn(value);

        final Capture<Callback> callbackCapture = newCapture();
        kafkaBasedLog.send(eq("status-task-conn-0"), eq(value), capture(callbackCapture));
        expectLastCall()
                .andAnswer(new IAnswer<Void>() {
                    @Override
                    public Void answer() throws Throwable {
                        callbackCapture.getValue().onCompletion(null, null);
                        return null;
                    }
                });
        replayAll();

        TaskStatus status = new TaskStatus(TASK, TaskStatus.State.RUNNING, WORKER_ID, 0);
        store.put(status);

        // state is not visible until read back from the log
        assertEquals(null, store.get(TASK));

        verifyAll();
    }

    @Test
    public void readTaskState() {
        byte[] value = new byte[0];

        KafkaBasedLog<String, byte[]> kafkaBasedLog = mock(KafkaBasedLog.class);
        Converter converter = mock(Converter.class);
        KafkaStatusBackingStore store = new KafkaStatusBackingStore(new MockTime(), converter, STATUS_TOPIC, kafkaBasedLog);

        Map<String, Object> statusMap = new HashMap<>();
        statusMap.put("worker_id", WORKER_ID);
        statusMap.put("state", "RUNNING");
        statusMap.put("generation", 0L);

        expect(converter.toConnectData(STATUS_TOPIC, value))
                .andReturn(new SchemaAndValue(null, statusMap));

        replayAll();

        store.read(consumerRecord(0, "status-task-conn-0", value));

        TaskStatus status = new TaskStatus(TASK, TaskStatus.State.RUNNING, WORKER_ID, 0);
        assertEquals(status, store.get(TASK));

        verifyAll();
    }

    private static ConsumerRecord<String, byte[]> consumerRecord(long offset, String key, byte[] value) {
        return new ConsumerRecord<>(STATUS_TOPIC, 0, offset, System.currentTimeMillis(),
                TimestampType.CREATE_TIME, 0L, 0, 0, key, value);
    }

}


text:
use crate::wgpu;
use wgpu::util::{BufferInitDescriptor, DeviceExt};

/// Reshapes a texture from its original size, sample_count and format to the destination size,
/// sample_count and format.
///
/// The `src_texture` must have the `TextureUsage::SAMPLED` enabled.
///
/// The `dst_texture` must have the `TextureUsage::RENDER_ATTACHMENT` enabled.
#[derive(Debug)]
pub struct Reshaper {
    _vs_mod: wgpu::ShaderModule,
    _fs_mod: wgpu::ShaderModule,
    bind_group_layout: wgpu::BindGroupLayout,
    bind_group: wgpu::BindGroup,
    render_pipeline: wgpu::RenderPipeline,
    sampler: wgpu::Sampler,
    uniform_buffer: Option<wgpu::Buffer>,
    vertex_buffer: wgpu::Buffer,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
struct Vertex {
    pub position: [f32; 2],
}

#[repr(C)]
#[derive(Copy, Clone)]
struct Uniforms {
    sample_count: u32,
}

impl Reshaper {
    /// Construct a new `Reshaper`.
    pub fn new(
        device: &wgpu::Device,
        src_texture: &wgpu::TextureViewHandle,
        src_sample_count: u32,
        src_sample_type: wgpu::TextureSampleType,
        dst_sample_count: u32,
        dst_format: wgpu::TextureFormat,
    ) -> Self {
        // Load shader modules.
        let vs_mod = wgpu::shader_from_spirv_bytes(device, include_bytes!("shaders/vert.spv"));
        let fs_mod = match src_sample_count {
            1 => wgpu::shader_from_spirv_bytes(device, include_bytes!("shaders/frag.spv")),
            2 => wgpu::shader_from_spirv_bytes(device, include_bytes!("shaders/frag_msaa2.spv")),
            4 => wgpu::shader_from_spirv_bytes(device, include_bytes!("shaders/frag_msaa4.spv")),
            8 => wgpu::shader_from_spirv_bytes(device, include_bytes!("shaders/frag_msaa8.spv")),
            16 => wgpu::shader_from_spirv_bytes(device, include_bytes!("shaders/frag_msaa16.spv")),
            _ => wgpu::shader_from_spirv_bytes(device, include_bytes!("shaders/frag_msaa.spv")),
        };

        // Create the sampler for sampling from the source texture.
        let sampler_desc = wgpu::SamplerBuilder::new().into_descriptor();
        let sampler_filtering = wgpu::sampler_filtering(&sampler_desc);
        let sampler = device.create_sampler(&sampler_desc);

        // Create the render pipeline.
        let bind_group_layout =
            bind_group_layout(device, src_sample_count, src_sample_type, sampler_filtering);
        let pipeline_layout = pipeline_layout(device, &bind_group_layout);
        let render_pipeline = render_pipeline(
            device,
            &pipeline_layout,
            &vs_mod,
            &fs_mod,
            dst_sample_count,
            dst_format,
        );

        // Create the uniform buffer to pass the sample count if we don't have an unrolled resolve
        // fragment shader for it.
        let uniform_buffer = match unrolled_sample_count(src_sample_count) {
            true => None,
            false => {
                let uniforms = Uniforms {
                    sample_count: src_sample_count,
                };
                let uniforms_bytes = uniforms_as_bytes(&uniforms);
                let usage = wgpu::BufferUsage::UNIFORM;
                let buffer = device.create_buffer_init(&BufferInitDescriptor {
                    label: None,
                    contents: &uniforms_bytes,
                    usage,
                });
                Some(buffer)
            }
        };

        // Create the bind group.
        let bind_group = bind_group(
            device,
            &bind_group_layout,
            src_texture,
            &sampler,
            uniform_buffer.as_ref(),
        );

        // Create the vertex buffer.
        let vertices_bytes = vertices_as_bytes(&VERTICES[..]);
        let vertex_usage = wgpu::BufferUsage::VERTEX;
        let vertex_buffer = device.create_buffer_init(&BufferInitDescriptor {
            label: None,
            contents: vertices_bytes,
            usage: vertex_usage,
        });

        Reshaper {
            _vs_mod: vs_mod,
            _fs_mod: fs_mod,
            bind_group_layout,
            bind_group,
            render_pipeline,
            sampler,
            uniform_buffer,
            vertex_buffer,
        }
    }

    /// Given an encoder, submits a render pass command for writing the source texture to the
    /// destination texture.
    pub fn encode_render_pass(
        &self,
        dst_texture: &wgpu::TextureViewHandle,
        encoder: &mut wgpu::CommandEncoder,
    ) {
        let mut render_pass = wgpu::RenderPassBuilder::new()
            .color_attachment(dst_texture, |color| color)
            .begin(encoder);
        render_pass.set_pipeline(&self.render_pipeline);
        render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
        render_pass.set_bind_group(0, &self.bind_group, &[]);
        let vertex_range = 0..VERTICES.len() as u32;
        let instance_range = 0..1;
        render_pass.draw(vertex_range, instance_range);
    }
}

const VERTICES: [Vertex; 4] = [
    Vertex {
        position: [-1.0, 1.0],
    },
    Vertex {
        position: [-1.0, -1.0],
    },
    Vertex {
        position: [1.0, 1.0],
    },
    Vertex {
        position: [1.0, -1.0],
    },
];

// We provide pre-prepared fragment shaders with unrolled resolves for common sample counts.
fn unrolled_sample_count(sample_count: u32) -> bool {
    match sample_count {
        1 | 2 | 4 | 8 | 16 => true,
        _ => false,
    }
}

fn bind_group_layout(
    device: &wgpu::Device,
    src_sample_count: u32,
    src_sample_type: wgpu::TextureSampleType,
    sampler_filtering: bool,
) -> wgpu::BindGroupLayout {
    let mut builder = wgpu::BindGroupLayoutBuilder::new()
        .texture(
            wgpu::ShaderStage::FRAGMENT,
            src_sample_count > 1,
            wgpu::TextureViewDimension::D2,
            src_sample_type,
        )
        .sampler(wgpu::ShaderStage::FRAGMENT, sampler_filtering);
    if !unrolled_sample_count(src_sample_count) {
        builder = builder.uniform_buffer(wgpu::ShaderStage::FRAGMENT, false);
    }
    builder.build(device)
}
fn bind_group(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    texture: &wgpu::TextureViewHandle,
    sampler: &wgpu::Sampler,
    uniform_buffer: Option<&wgpu::Buffer>,
) -> wgpu::BindGroup {
    let mut builder = wgpu::BindGroupBuilder::new()
        .texture_view(texture)
        .sampler(sampler);
    if let Some(buffer) = uniform_buffer {
        builder = builder.buffer::<Uniforms>(buffer, 0..1);
    }
    builder.build(device, layout)
}

fn pipeline_layout(
    device: &wgpu::Device,
    bind_group_layout: &wgpu::BindGroupLayout,
) -> wgpu::PipelineLayout {
    let desc = wgpu::PipelineLayoutDescriptor {
        label: Some("nannou_reshaper"),
        bind_group_layouts: &[&bind_group_layout],
        push_constant_ranges: &[],
    };
    device.create_pipeline_layout(&desc)
}

fn render_pipeline(
    device: &wgpu::Device,
    layout: &wgpu::PipelineLayout,
    vs_mod: &wgpu::ShaderModule,
    fs_mod: &wgpu::ShaderModule,
    dst_sample_count: u32,
    dst_format: wgpu::TextureFormat,
) -> wgpu::RenderPipeline {
    wgpu::RenderPipelineBuilder::from_layout(layout, vs_mod)
        .fragment_shader(fs_mod)
        .color_format(dst_format)
        .color_blend(wgpu::BlendState::REPLACE)
        .alpha_blend(wgpu::BlendState::REPLACE)
        .add_vertex_buffer::<Vertex>(&wgpu::vertex_attr_array![0 => Float2])
        .primitive_topology(wgpu::PrimitiveTopology::TriangleStrip)
        .sample_count(dst_sample_count)
        .build(device)
}

fn uniforms_as_bytes(uniforms: &Uniforms) -> &[u8] {
    unsafe { wgpu::bytes::from(uniforms) }
}

fn vertices_as_bytes(data: &[Vertex]) -> &[u8] {
    unsafe { wgpu::bytes::from_slice(data) }
}


text:
INSERT INTO role (id, code, label)
VALUES (1, 'ROLE_USER', 'User');
INSERT INTO role (id, code, label)
VALUES (2, 'ROLE_ADMIN', 'Admin');
INSERT INTO role (id, code, label)
VALUES (3, 'ROLE_SYSADMIN', 'System Admin');

INSERT INTO account (username, password, enabled, credentialsexpired, expired, locked)
VALUES ('jane', '$2a$04$oCNqkdWPn77cQ7c4S6ylfe3WGYdf6QXH7AV.wkaDDUjqAFtjt.XyC', true, false, false, false);
INSERT INTO account (username, password, enabled, credentialsexpired, expired, locked)
VALUES ('pete', '$2a$04$iaCt6D1GR2QhQw8wZYyi3Orrzw7m0JwGTLJiz7hGomCtU8R5faeEe', true, false, false, false);
INSERT INTO account (username, password, enabled, credentialsexpired, expired, locked)
VALUES ('shogo', '$2a$04$3NNhArZIGWt5J0WREJAy7eTmUxRC3qVr9qxddJFuvXdegzEeohMQ.', true, false, false, false);
INSERT INTO account (username, password, enabled, credentialsexpired, expired, locked)
VALUES ('kris', '$2a$04$3NNhArZIGWt5J0WREJAy7eTmUxRC3qVr9qxddJFuvXdegzEeohMQ.', true, false, false, false);

INSERT INTO profile (account_id, firstname, lastname, email, phone_number, picture_link, website, facebook,
about, date_of_registration)
VALUES (1, 'Janice', 'Jones', 'jane@example.com', '062/123456',
'https://i.guim.co.uk/img/static/sys-images/Media/Pix/pictures/2011/7/20/1311186215351/Janice-Hadlow-007.
jpg?w=470&q=55&auto=format&usm=12&fit=max&s=dad4c5433205104558516bc23c823f7b',
'http://www.somelink1.rs', 'http://www.facebook/someprofile1',
'My name is Jane','2016-01-19');
INSERT INTO profile (account_id, firstname, lastname, email, phone_number, picture_link, website, facebook,
about, date_of_registration)
VALUES (2, 'Peter', 'Peterson', 'pete@example.com', '062/223456',
'http://www.istanbulexpats.com/wp-content/uploads/2014/11/odd-job-handyman-istanbul.jpg',
'http://www.somelink2.rs', 'http://www.facebook/someprofile2',
'People find me to be an upbeat ', '2015-08-22');
INSERT INTO profile (account_id, firstname, lastname, email, phone_number, picture_link, website, facebook,
about, date_of_registration)
VALUES (3, 'Makishima', 'Shogo', 'shogo@example.com', '062/323456',
'http://www.kicnano.cornell.edu/wp-content/uploads/2010/12/shogo-hamada-pic.jpg',
'http://www.somelink2.rs', 'http://www.facebook/someprofile2',
'I am a dedicated person .', '2014-11-30');
INSERT INTO profile (account_id, firstname, lastname, email, phone_number, picture_link, website, facebook,
about, date_of_registration)
VALUES (4, 'Kristofer', 'Dahl', 'kris@example.com', '062/8053456',
'http://ll-media.tmz.com/2015/10/02/1002-kristofer-buckle-getty-4.jpg',
'http://www.somelink3.rs', 'http://www.facebook/someprofile3',
'I am an experienced professional ', '2014-11-30');

INSERT INTO account_role (account_id, role_id) VALUES (1, 1);
INSERT INTO account_role (account_id, role_id) VALUES (2, 1);
INSERT INTO account_role (account_id, role_id) VALUES (2, 2);
INSERT INTO account_role (account_id, role_id) VALUES (3, 1);
INSERT INTO account_role (account_id, role_id) VALUES (3, 2);
INSERT INTO account_role (account_id, role_id) VALUES (3, 3);
INSERT INTO account_role (account_id, role_id) VALUES (4, 1);

INSERT INTO category (name) VALUES ('Therapy');
INSERT INTO category (name) VALUES ('Technology');
INSERT INTO category (name) VALUES ('Education');
INSERT INTO category (name) VALUES ('Cosmetics');
INSERT INTO category (name) VALUES ('Design');

INSERT INTO service (name, category_id) VALUES ('Massage', 1);
INSERT INTO service (name, category_id) VALUES ('Physiotherapy', 1);
INSERT INTO service (name, category_id) VALUES ('Plumbing', 2);
INSERT INTO service (name, category_id) VALUES ('Electrical maintenance', 2);
INSERT INTO service (name, category_id) VALUES ('Computer repair', 2);
INSERT INTO service (name, category_id) VALUES ('Car mechanics', 2);
INSERT INTO service (name, category_id) VALUES ('English lessons', 3);
INSERT INTO service (name, category_id) VALUES ('Guitar lessons', 3);
INSERT INTO service (name, category_id) VALUES ('Swimming lessons', 3);
INSERT INTO service (name, category_id) VALUES ('Manicure/pedicure', 4);
INSERT INTO service (name, category_id) VALUES ('Hairstyling', 4);
INSERT INTO service (name, category_id) VALUES ('Makeup', 4);
INSERT INTO service (name, category_id) VALUES ('Face treatment', 4);
INSERT INTO service (name, category_id) VALUES ('Graphic design', 5);
INSERT INTO service (name, category_id) VALUES ('Web design', 5);
INSERT INTO service (name, category_id) VALUES ('Interior design', 5);
INSERT INTO service (name, category_id) VALUES ('Tailoring/sewing', 5);

INSERT INTO deal (profile_id, service_id, service_cost, description, long_description)
VALUES (1, 1, 1200.0, 'Shiatsu massage, now on discount!',
'Over four years of physical therapy experience');
INSERT INTO deal (profile_id, service_id, service_cost, description, long_description)
VALUES (2, 3, 950.0, 'All types of plumbing maintenance!',
'Nine years of experience developing.');
INSERT INTO deal (profile_id, service_id, service_cost, description, long_description)
VALUES (3, 7, 500.0, 'Prepare for your IELTS certification!',
'More than six years of advanced English teaching experience');
INSERT INTO deal (profile_id, service_id, service_cost, description, long_description)
VALUES (2, 12, 1000.0, 'Pro makeup for all occasions: weddings, birthdays, parties...',
'A self-motivated and organized professional.');
INSERT INTO deal (profile_id, service_id, service_cost, description, long_description)
VALUES (4, 11, 2400.0, 'Professional hairdresser, for both men and women.',
'I am a professional hairdresser .');

INSERT INTO location (country, city, street, number, latitude, longitude, deal_id)
VALUES ('Serbia', 'Novi Sad', 'Branka Bajica', '46', 45.258327, 19.821259, 1);
INSERT INTO location (country, city, street, number, latitude, longitude, deal_id)
VALUES ('Serbia', 'Novi Sad', 'Todora Toze Jovanovica', '13', 45.254718, 19.804984, 2);
INSERT INTO location (country, city, street, number, latitude, longitude, deal_id)
VALUES ('Serbia', 'Novi Sad', 'Isidore Sekulic', '5',45.249271, 19.799630, 3);
INSERT INTO location (country, city, street, number, latitude, longitude, deal_id)
VALUES ('Serbia', 'Novi Sad', 'Jovana Popovica', '18',45.245052, 19.811276, 4);
INSERT INTO location (country, city, street, number, latitude, longitude, deal_id)
VALUES ('Serbia', 'Novi Sad', 'Bulevar Oslobodjenja', '33',45.259742, 19.832404, 5);

INSERT INTO rating (comment, customer_name, time_of_rating, rating, deal_id)
VALUES ('Awesome! I highly recommend it!', 'CicaMica', now(), 5, 1);
INSERT INTO rating (comment, customer_name, time_of_rating, rating, deal_id)
VALUES ('Not too bad..', 'Anonymous', now(), 4, 2);
INSERT INTO rating (comment, customer_name, time_of_rating, rating, deal_id)
VALUES ('not really that great, tbh...', 'jblnk', now(), 2, 3);
INSERT INTO rating (comment, customer_name, time_of_rating, rating, deal_id)
VALUES ('its really as good as it says', 'Anonymous', now(), 5, 5);


text:
<?php

namespace Raducorp\ValidatorBundle\Validator;

use Raducorp\ValidatorBundle\Aware\RuleAwareInterface;
use Raducorp\ValidatorBundle\Aware\RuleAwareTrait;
use Raducorp\ValidatorBundle\Rule\AbstractRule;

/**
 * @todo Analyze: Should AbstractValidator + RuleAwareInterface become RuleAwareValidator!?
 * Class PasswordValidator
 * @package Raducorp\ValidatorBundle\Validator
 */
class PasswordValidator extends AbstractValidator implements RuleAwareInterface
{
    use RuleAwareTrait; // RuleAwareTrait::addRule()

    const ID = 'password.validator';

    /**
     * Validate password
     * {@inheritdoc}
     */
    public function validate($password)
    {
        // @todo Need a better reset
        $this->setMessages([]); // reset

        $output   = true;
        $fastfail = $this->getOption(AbstractValidator::FASTFAIL_OPTION);
        foreach ($this->getRules() as $rule) {
            /** @var AbstractRule $rule */
            $result = $rule->apply($password);
            if ($result === false) {
                $this->addMessage($rule->getError());
                if ($fastfail === true) {
                    return false;
                }
            }
            $output = $output && $result;
        }
        return $output;
    }
}


text:
/* eslint-disable no-await-in-loop */
const assert = require('assert');
const TestUtils = require('../utils');

/**
 * Logs body to a JSON file. Useful for debug/generating JSON examples for documentation
 * @param {object} body
 */
// eslint-disable-next-line no-unused-vars
function logBody(body) {
  const fs = require('fs');
  const path = require('path');
  fs.writeFileSync(
    path.join(__dirname, '/webhook.json'),
    JSON.stringify(body, null, 2),
    'utf8'
  );
}

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

describe('api/webhooks', function () {
  it('does not fire if not enabled', async function () {
    const hookServer = await TestUtils.makeHookServer();

    const utils = new TestUtils({
      port: 9000,
      publicUrl: 'http://mysqlpad.com',
      baseUrl: '/sqlpad',
      webhookSecret: 'secret',
      webhookUserCreatedUrl: hookServer.url,
    });
    await utils.init(true);

    await utils.post('admin', '/sqlpad/api/users', {
      email: 'user1@test.com',
      name: 'user1',
      role: 'editor',
      data: {
        create: true,
      },
    });

    await wait(200);
    assert.equal(hookServer.responses.length, 0);
  });

  it('userCreated', async function () {
    const hookServer = await TestUtils.makeHookServer();

    const utils = new TestUtils({
      port: 9000,
      publicUrl: 'http://mysqlpad.com',
      baseUrl: '/sqlpad',
      webhookEnabled: true,
      webhookSecret: 'secret',
      webhookUserCreatedUrl: hookServer.url,
    });
    await utils.init(true);

    const user = await utils.post('admin', '/sqlpad/api/users', {
      email: 'user1@test.com',
      name: 'user1',
      role: 'editor',
    });

    await wait(200);

    assert.deepStrictEqual(hookServer.responses[0].body, {
      action: 'user_created',
      sqlpadUrl: 'http://mysqlpad.com:9000/sqlpad',
      user: {
        id: user.id,
        name: user.name,
        role: user.role,
        email: user.email,
        createdAt: user.createdAt,
      },
    });

    // Only need to test this once
    // Ensure headers are sent as expected
    assert.equal(hookServer.responses[0].headers['sqlpad-secret'], 'secret');
    hookServer.server.close();
  });

  it('queryCreated', async function () {
    const hookServer = await TestUtils.makeHookServer();
    const utils = new TestUtils({
      webhookEnabled: true,
      webhookQueryCreatedUrl: hookServer.url,
    });
    await utils.init(true);

    const connection = await utils.post('admin', '/api/connections', {
      name: 'test connection',
      driver: 'sqlite',
      data: {
        filename: './test/fixtures/sales.sqlite',
      },
    });

    const queryWithoutCon = await utils.post('admin', '/api/queries', {
      name: 'test query',
      tags: ['one', 'two'],
      queryText: 'SELECT * FROM some_table',
    });

    await utils.post('admin', '/api/queries', {
      name: 'test query 2',
      tags: ['one', 'two'],
      connectionId: connection.id,
      queryText: 'SELECT * FROM some_table',
    });

    await wait(200);

    // no secret or url headers this time
    assert.equal(hookServer.responses[0].headers['sqlpad-secret'], '');

    const body1 = hookServer.responses[0].body;
    assert.equal(body1.action, 'query_created');
    assert.equal(body1.sqlpadUrl, '');
    assert.equal(body1.query.id, queryWithoutCon.id, 'query r1');
    assert.equal(body1.query.name, queryWithoutCon.name);
    assert.deepStrictEqual(body1.query.tags, queryWithoutCon.tags);
    assert.equal(body1.query.queryText, queryWithoutCon.queryText);
    assert.equal(body1.query.createdAt, queryWithoutCon.createdAt);
    assert.deepEqual(body1.query.createdByUser, queryWithoutCon.createdByUser);
    assert(!body1.connection);

    const body2 = hookServer.responses[1].body;
    assert.equal(body2.connection.id, connection.id, 'connection r2');
    assert.equal(body2.connection.name, connection.name);
    assert.equal(body2.connection.driver, connection.driver);

    hookServer.server.close();
  });

  it('batchCreated / batchFinished / statementCreated / statementFinished', async function () {
    const hookServer = await TestUtils.makeHookServer();
    const utils = new TestUtils({
      webhookEnabled: true,
      webhookBatchCreatedUrl: hookServer.url,
      webhookBatchFinishedUrl: hookServer.url,
      webhookStatementCreatedUrl: hookServer.url,
      webhookStatementFinishedUrl: hookServer.url,
    });
    await utils.init(true);

    const connection = await utils.post('admin', '/api/connections', {
      name: 'test connection',
      driver: 'sqlite',
      data: {
        filename: './test/fixtures/sales.sqlite',
      },
    });

    const queryText = `SELECT 1 AS id, 'blue' AS color UNION ALL SELECT 2 AS id, 'red' AS color`;
    const query = await utils.post('admin', '/api/queries', {
      name: 'test query',
      tags: ['test'],
      connectionId: connection.id,
      queryText,
    });

    let batch = await utils.post('admin', `/api/batches`, {
      connectionId: connection.id,
      queryId: query.id,
      batchText: queryText,
      selectedText: queryText,
    });

    batch = await utils.get('admin', `/api/batches/${batch.id}`);
    while (batch.status !== 'finished' && batch.status !== 'error') {
      await wait(50);
      batch = await utils.get('admin', `/api/batches/${batch.id}`);
    }

    const statements = await utils.get(
      'admin',
      `/api/batches/${batch.id}/statements`
    );
    assert.equal(statements.length, 1);

    const statement1 = statements[0];

    await wait(500);

    const { body: batchCreatedBody } = hookServer.responses.find(
      (r) => r.body.action === 'batch_created'
    );
    assert.equal(batchCreatedBody.batch.id, batch.id);
    assert.equal(batchCreatedBody.user.id, utils.users.admin.id);

    const { body: batchFinishedBody } = hookServer.responses.find(
      (r) => r.body.action === 'batch_finished'
    );
    assert.equal(batchFinishedBody.batch.id, batch.id);
    assert.equal(batchFinishedBody.user.id, utils.users.admin.id);

    const { body: statementCreatedBody } = hookServer.responses.find(
      (r) => r.body.action === 'statement_created'
    );
    assert.equal(statementCreatedBody.statement.id, statement1.id);
    assert.equal(statementCreatedBody.user.id, utils.users.admin.id);
    assert.equal(statementCreatedBody.batch.id, batch.id);
    assert.equal(statementCreatedBody.connection.id, connection.id);

    const { body: statementFinishedBody } = hookServer.responses.find(
      (r) => r.body.action === 'statement_finished'
    );
    assert.equal(statementFinishedBody.statement.id, statement1.id);
    assert.deepEqual(statementFinishedBody.results, [
      [1, 'blue'],
      [2, 'red'],
    ]);
    assert.equal(statementFinishedBody.user.id, utils.users.admin.id);
    assert.equal(statementFinishedBody.batch.id, batch.id);
    assert.equal(statementFinishedBody.connection.id, connection.id);

    // Ensure connection does not have sensitive data
    assert(!statementFinishedBody.connection.data);
    assert(!statementFinishedBody.connection.filename);
  });
});


text:
package io.gravitee.am.repository.mongodb.management.internal.model.oidc;

import java.util.List;

/**
 * @author Alexandre FARIA (contact at alexandrefaria.net)
 * @author GraviteeSource Team
 */
public class ClientRegistrationSettingsMongo {

    private boolean allowLocalhostRedirectUri;
    private boolean allowHttpSchemeRedirectUri;
    private boolean allowWildCardRedirectUri;
    private boolean isDynamicClientRegistrationEnabled;
    private boolean isOpenDynamicClientRegistrationEnabled;
    private List<String> defaultScopes;
    private boolean isAllowedScopesEnabled;
    private List<String> allowedScopes;
    private boolean isClientTemplateEnabled;

    public boolean isAllowLocalhostRedirectUri() {
        return allowLocalhostRedirectUri;
    }

    public void setAllowLocalhostRedirectUri(boolean allowLocalhostRedirectUri) {
        this.allowLocalhostRedirectUri = allowLocalhostRedirectUri;
    }

    public boolean isAllowHttpSchemeRedirectUri() {
        return allowHttpSchemeRedirectUri;
    }

    public void setAllowHttpSchemeRedirectUri(boolean allowHttpSchemeRedirectUri) {
        this.allowHttpSchemeRedirectUri = allowHttpSchemeRedirectUri;
    }

    public boolean isDynamicClientRegistrationEnabled() {
        return isDynamicClientRegistrationEnabled;
    }

    public void setDynamicClientRegistrationEnabled(boolean isDynamicClientRegistrationEnabled) {
        this.isDynamicClientRegistrationEnabled = isDynamicClientRegistrationEnabled;
    }

    public boolean isOpenDynamicClientRegistrationEnabled() {
        return isOpenDynamicClientRegistrationEnabled;
    }

    public void setOpenDynamicClientRegistrationEnabled(boolean isOpenDynamicClientRegistrationEnabled) {
        this.isOpenDynamicClientRegistrationEnabled = isOpenDynamicClientRegistrationEnabled;
    }

    public boolean isAllowWildCardRedirectUri() {
        return allowWildCardRedirectUri;
    }

    public void setAllowWildCardRedirectUri(boolean allowWildCardRedirectUri) {
        this.allowWildCardRedirectUri = allowWildCardRedirectUri;
    }

    public List<String> getDefaultScopes() {
        return defaultScopes;
    }

    public void setDefaultScopes(List<String> defaultScopes) {
        this.defaultScopes = defaultScopes;
    }

    public boolean isAllowedScopesEnabled() {
        return isAllowedScopesEnabled;
    }

    public void setAllowedScopesEnabled(boolean allowedScopesEnabled) {
        isAllowedScopesEnabled = allowedScopesEnabled;
    }

    public List<String> getAllowedScopes() {
        return allowedScopes;
    }

    public void setAllowedScopes(List<String> allowedScopes) {
        this.allowedScopes = allowedScopes;
    }

    public boolean isClientTemplateEnabled() {
        return isClientTemplateEnabled;
    }

    public void setClientTemplateEnabled(boolean clientTemplateEnabled) {
        isClientTemplateEnabled = clientTemplateEnabled;
    }
}


text:
class Spree::Allegro::ShopCategory < ActiveRecord::Base
  belongs_to :parent, class_name: 'Spree::Allegro::ShopCategory', foreign_key: 'parent_id'
  has_many :children, class_name: 'Spree::Allegro::ShopCategory', foreign_key: 'parent_id'
  has_many :store_products, class_name: 'Spree::Allegro::StoreProduct'
  belongs_to :store, class_name: 'Spree::Store'
end


text:
    <meta charset="utf-8">
    <link rel="stylesheet" href="bootstrap.min.css">
    <link rel="stylesheet" href="bootstrap-theme.min.css">
    <link rel='stylesheet' href='onepage-scroll.css' type='text/css'>
    <link rel="stylesheet" href="style.css">

                Where's Our Sound?

                #DoYouHaveTheGUTS 2014

                    Collabarative music composition using the SendGrid API

                    Team Where's-Our-Food

                Drum Beat Choices

                Listen to the following drum loops

                A

                Play
                Stop

                B

                Play
                Stop

                C

                Play
                Stop

                D

                Play
                Stop

                Select Your Preferred Beat

                Email wts@bymail.in

                A

                B

                C

                D

                Open Voting

                Now It's Time For Melodies

                Email your melody chains to wts@bymail.in

                    A melody chain is an 8 digit number, each digit representing half a beat. 1 - 8 represent different notes ascending in pitch and 0 represents a break.

                    Example String: 64565434

                    Listen

                Where's Our Sound?

                wts@bymail.in
                Go


text:
begin
  require "bundler"
rescue LoadError => e
  STDERR.puts e.message
  STDERR.puts "Run `gem install bundler` to install Bundler."
  exit e.status_code
end

begin
  Bundler.setup(:default, :development, :test)
rescue Bundler::BundlerError => e
  STDERR.puts e.message
  STDERR.puts "Run `bundle install` to install missing gems."
  exit e.status_code
end

require "color_cat"

require "minitest/autorun"
require "vcr"
require "minitest-vcr"
require "webmock"
require "mocha/setup"
require "faraday"
require "pry"
require "pry-debugger"

VCR.configure do |c|
  c.cassette_library_dir = 'test/cassettes'
  c.hook_into :webmock
end


text:
package com.marcobehler.saito.core.files;

import com.marcobehler.saito.core.BaseInMemoryFSTest;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * @author Marco Behler <marco@marcobehler.com>
 */
public class LayoutTest extends BaseInMemoryFSTest {

    @Test
    public void getLayoutName() throws IOException {
        Path image = Files.write(fs.getPath("/myLayout.ftl"), "myContent".getBytes());
        Layout layout = new Layout(image.getParent(), image.getFileName());
        assertThat(layout.getName()).isEqualTo("myLayout");
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Vietnam Cambodia Laos Thailand Myanmar China Tours, Travel Guide  & Holidays || Asianventure Tours</title>
<meta name="description" content="Offering Vietnam Cambodia Laos Thailand Myanmar China tours, travel guide, Flights, booking hotels for holidays in Vietnam Cambodia Laos Thailand Myanmar China"/>
<meta name="keywords" content="Vietnam Tours, Laos Tours, Cambodia tours, Thailand Tours, Myanmar Tours, China Tours, Vietnam and Cambodia tours,Vietnam and Laos tours,Cambodia and Laos tours,Thailand and Myanmar tours"/>
<meta name="robots" content="index,follow"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7"/>

<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/social.css">
<link rel="stylesheet" href="css/prettyphoto.css">
<link rel="stylesheet" href="css/domtab_test.css">
<link rel="stylesheet" href="Font-Awesome-master/css/font-awesome.css">

<link href="css/freelancer.css" rel="stylesheet">
<link href="css/freelancer_mobile.css" rel="stylesheet">

<link href="css/slider.css" rel="stylesheet">

FANTASTIC TOURS IN VIETNAM

Best Seller

Indochina Tours

 Photo

 Map

Grand Indochina

21 DAYS | FROM  US$ 2154

The major places of interest in Cambodia, Vietnam and Laos are all included in this three journey.  You explore Angkor Temples including,...

 Vietnam, Laos, Cambodia

Culture Tours

 Photo

 Map

Hidden North Vietnam

8 DAYS | FROM  US$ 105

Starting from Hanoi we take a cyclo ride through its old quarter  streets and board a drive to Halong Bay where we unwind in a scenic cruise,...

 Vietnam

Special Offer

Indochina Tours

 Photo

 Map

Essence Vietnam And Laos

14 DAYS | FROM  US$ 1449

This trip is carefully is designed for those who are keen to explore the most interesting places of Vietnam and Laos. Travelling from the bustling,...

 Vietnam, Laos

Culture Tours

 Photo

 Map

Central Vietnam Stopver

4 DAYS | FROM  US$ 707

Starting in Hue, we spend our time exploring various outlying mausoleums on a cruise along the scenic Perfume River plus the Imperial Citadel,...

 Vietnam

Best Seller

Culture Tours

 Photo

 Map

Renaissance Of Cambodia

9 DAYS | FROM  US$ 594

With a rich and ancient history, smiling people and beautiful nature, Cambodia is a wonderful country to explore. This  impressive trip takes you right around the country,...

 Cambodia

Overland Tours

 Photo

 Map

Laos Spendour

6 DAYS | FROM  US$ 597

This fascinating combination of ancient cultures, river journeys, stunning scenery and culminating makes Laos one of the beautiful and unspoiled parts in Indochina is,...

 Laos

Special Offer

Culture Tours

 Photo

 Map

Passion Of Myanmar

8 DAYS | FROM  US$ 1008

This exciting  trip designed for individual traveller who is keen to explore all aspects of Burma. Running from charming Yangon to tranquil Inle Lake, this itinerary,...

 Myanmar

Best Seller

Overland Tours

 Photo

 Map

Hill Tribe Encounter

21 DAYS | FROM  US$ 1489

Travelling on 4 WD car you explore in depth the unequalled northern scenery of the north and see plenty of hill tribe groups living in remote mountainous regions of Muang,...

 Vietnam

Best Seller

Culture Tours

 Photo

 Map

Renaissance Of Cambodia

9 DAYS | FROM  US$ 594

With a rich and ancient history, smiling people and beautiful nature, Cambodia is a wonderful country to explore. This  impressive trip takes you right around the country,...

 Cambodia

Overland Tours

 Photo

 Map

Laos Spendour

6 DAYS | FROM  US$ 597

This fascinating combination of ancient cultures, river journeys, stunning scenery and culminating makes Laos one of the beautiful and unspoiled parts in Indochina is,...

 Laos

Special Offer

Culture Tours

 Photo

 Map

Passion Of Myanmar

8 DAYS | FROM  US$ 1008

This exciting  trip designed for individual traveller who is keen to explore all aspects of Burma. Running from charming Yangon to tranquil Inle Lake, this itinerary,...

 Myanmar

Best Seller

Overland Tours

 Photo

 Map

Hill Tribe Encounter

21 DAYS | FROM  US$ 1489

Travelling on 4 WD car you explore in depth the unequalled northern scenery of the north and see plenty of hill tribe groups living in remote mountainous regions of Muang,...

 Vietnam

Read More


text:
namespace chrono {
namespace vehicle {

/// @addtogroup vehicle_wheeled_tire
/// @{

/// Rigid tire constructed with data from file (JSON format).
class CH_VEHICLE_API RigidTire : public ChRigidTire {
  public:
    RigidTire(const std::string& filename);
    RigidTire(const rapidjson::Document& d);
    ~RigidTire() {}

    virtual double getRadius() const override { return m_radius; }
    virtual double getWidth() const override { return m_width; }

  private:
    void Create(const rapidjson::Document& d);

    double m_radius;
    double m_width;
};

/// @} vehicle_wheeled_tire

}  // end namespace vehicle
}  // end namespace chrono

#endif


text:
const fs = require('fs');
const utils = require("./require/utils.js");
const AI = require("./require/Core.js");
const EventHandler = require("./require/EventHandler.js");

//Parses the config file
let configFile;
try {
    configFile = fs.readFileSync("DiscordJS.config");
} catch (err) {
    utils.logErr("Error, could not find DiscordJS.config.");
    process.exit();
}
const config = JSON.parse(configFile);
const token = config.token;
const debug = config.debug;
const api = "discord.js";

//Initialises the Logic
const botAI = new AI(api, debug);
botAI.moduleHandler.registerAll("./require/modules/");

//Initialises Discord.js API Client
const Discord = require('discord.js');
const discordbot = new Discord.Client();

discordbot.on("ready", function() {
    utils.logDone("Connected.");
    botAI.moduleHandler.loadAll();
    botAI.moduleHandler.initData("./data_" + discordbot.user.id + ".json");
    utils.logDone("ARIMA Bot started up succesfully!"); //HAL 9001
    utils.logInfo("Attched to user " + discordbot.user.id + " with the name " + discordbot.user.username + ".");
});

discordbot.on("message", function(ev) {
    const eventPacket = new EventHandler.EventPacket(api, "message", ev, discordbot);

    botAI.moduleHandler.send(eventPacket);

});

discordbot.login(token).then().catch(err => console.error(err));
utils.log("Connecting to discord...");


text:
<?php

namespace Atos\MissionRecensementBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class AtosMissionRecensementBundle extends Bundle
{
}


text:
exception
=========

HTTP based Exception to simulate bubbling of events in PHP (extends default PHP Exception class)


text:
package org.robolectric.shadows;

import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.view.animation.LinearInterpolator;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;

@Implements(ValueAnimator.class)
public class ShadowValueAnimator extends ShadowAnimator {
  private TimeInterpolator interpolator;

  @Implementation
  public void setInterpolator(TimeInterpolator value) {
    if (value != null) {
      interpolator = value;
    } else {
      interpolator = new LinearInterpolator();
    }
  }

  @Implementation
  public TimeInterpolator getInterpolator() {
    return interpolator;
  }

  @Implementation
  public static ValueAnimator ofInt (int... values){
    return new ValueAnimator();
  }

  @Implementation
  public boolean isRunning() {
    return false;
  }

  @Implementation @Override
  public long getDuration() {
    return super.getDuration();
  }
}


text:
var common = require('../common');
var assert = require('assert');
var cluster = require('cluster');
var fork = require('child_process').fork;
var http = require('http');

var id = process.argv[2];

if (!id) {
  var a = fork(__filename, ['one']);
  var b = fork(__filename, ['two']);

  a.on('exit', function(c) {
    if (c) {
      b.send('QUIT');
      throw new Error('A exited with ' + c);
    }
  });

  b.on('exit', function(c) {
    if (c) {
      a.send('QUIT');
      throw new Error('B exited with ' + c);
    }
  });

  a.on('message', function(m) {
    if (typeof m === 'object') return;
    assert.equal(m, 'READY');
    b.send('START');
  });

  var ok = false;

  b.on('message', function(m) {
    if (typeof m === 'object') return; // ignore system messages
    assert.equal(m, 'EADDRINUSE');
    ok = true;
    a.send('QUIT');
    b.send('QUIT');
  });

  process.on('exit', function() {
    assert(ok);
  });
}
else if (id === 'one') {
  if (cluster.isMaster) return startWorker();

  var server = http.createServer(assert.fail).listen(common.PORT, function() {
    process.send('READY');
  });

  process.on('message', function(m) {
    if (m === 'QUIT') process.exit();
  });
}
else if (id === 'two') {
  if (cluster.isMaster) return startWorker();

  var ok = false;
  process.on('exit', function() {
    assert(ok);
  });

  var server = http.createServer(assert.fail);
  process.on('message', function(m) {
    if (typeof m === 'object') return; // ignore system messages
    if (m === 'QUIT') process.exit();
    assert.equal(m, 'START');
    server.listen(common.PORT, assert.fail);
    server.on('error', function(e) {
      assert.equal(e.code, 'EADDRINUSE');
      process.send(e.code);
      ok = true;
    });
  });
}
else {
  assert(0); // bad command line argument
}

function startWorker() {
  var worker = cluster.fork();
  worker.on('exit', process.exit);
  worker.on('message', process.send.bind(process));
  process.on('message', worker.send.bind(worker));
}


text:
BAMTOOLS_ROOT = $(realpath ../../src/include/bamtools)
CXXFLAGS+=-Wl,-rpath,$(BAMTOOLS_ROOT)/lib -Wall -O3 -I $(BAMTOOLS_ROOT)/include -L $(BAMTOOLS_ROOT)/lib
CXXFLAGS+=-I../../src/include/utils

bin = ./
obj = utility.o sam.o
DistinguishReads: $(obj) DistinguishReads.cpp anchor_variation.h
	$(CXX) $(CXXFLAGS) DistinguishReads.cpp anchor_variation.h $(obj) -lbamtools -o $(bin)/DistinguishReads -lz

utility.o: ../../src/include/utils/utility.cpp
	$(CXX) -c -o utility.o ../../src/include/utils/utility.cpp

sam.o: ../../src/include/utils/sam.cpp ../../src/include/utils/sam.h
	$(CXX) -c -o sam.o ../../src/include/utils/sam.cpp

clean:
	rm -f $(obj)

.PHONY: clean


text:
package software.amazon.awssdk.codegen.model.intermediate;

public class EndpointDiscovery {

    private boolean required;

    public boolean isRequired() {
        return required;
    }

    public void setRequired(boolean required) {
        this.required = required;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Dichrotrichum minus Kraenzl.

### Remarks
null


text:
namespace NExpect.Interfaces;

/// <summary>
/// Provides the .Less grammar continuation
/// </summary>
/// <typeparam name="T">Type of the continuation</typeparam>
public interface ILessContinuation<T> : ICanAddMatcher<T>
{
    /// <summary>
    /// Starts the .Less.Than.Or.Equal.To
    /// </summary>
    ILessThan<T> Than { get; }
}


text:
/***************************************************************************
 *   CommandObject.cs
 *   -------------------
 *   begin                : November 14, 2006
 *   website              : http://www.codeplex.com/CslaVSTemplates
 *   template by          : Keith Smith
 *   email                : mobile5guy@gmail.com
 *
 *   Change History:
 *      11/14/2006 Created
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program 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 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

using Csla;
using Csla.Data;

namespace $rootnamespace$
{
    [Serializable()]
    public class $safeitemrootname$ : CommandBase
    {
        //Friendly name for the business object.
        [NonSerialized]
        const string BUSINESS_OBJECT_NAME = "$safeitemrootname$";

        //replace "configkey" with your key attribute from the application configuration file.
        [NonSerialized]
        const string DATABASE_NAME = "configkey";

        #region Authorization Methods
        //Can't use string.Format() on a const.
        [NonSerialized]
        const string NOT_AUTHORIZED_UPDATE = "User not authorized to update " + BUSINESS_OBJECT_NAME + ".";
        [NonSerialized]
        const string NOT_AUTHORIZED_DELETE = "User not authorized to delete " + BUSINESS_OBJECT_NAME + ".";
        [NonSerialized]
        const string NOT_AUTHORIZED_INSERT = "User not authorized to insert " + BUSINESS_OBJECT_NAME + ".";
        [NonSerialized]
        const string NOT_AUTHORIZED_VIEW = "User not authorized to view " + BUSINESS_OBJECT_NAME + ".";

        public static bool CanExecuteCommand()
        {
            // TODO: customize to check user role
            //return ApplicationContext.User.IsInRole("");
            return true;
        }
        #endregion
        #region Client-side Code
        // TODO: add your own fields and properties
        bool _result;
        public bool Result
        {
            get
            {
                return _result;
            }
        }
        private void BeforeServer()
        {
            // TODO: implement code to run on client
            // before server is called
        }
        private void AfterServer()
        {
            // TODO: implement code to run on client
            // after server is called
        }
        #endregion
        #region Factory Methods
        public static bool Execute()
        {
            $safeitemrootname$ cmd = new $safeitemrootname$();
            cmd.BeforeServer();
            cmd = DataPortal.Execute<$safeitemrootname$>( cmd );
            cmd.AfterServer();
            return cmd.Result;
        }
        private $rootnamespace$()
        { /* require use of factory methods */
        }
        #endregion
        #region Server-side Code
        protected override void DataPortal_Execute()
        {
            // TODO: implement code to run on server
            // and set result value(s)
            _result = true;
        }
        #endregion
    }
}


text: git push origin master && git push heroku master