text:
/**
 * @file
 */

#ifndef ORG_OPENSPLICE_CORE_ENTITY_REGISTRY_HPP_
#define ORG_OPENSPLICE_CORE_ENTITY_REGISTRY_HPP_

#include <dds/core/detail/WeakReferenceImpl.hpp>
#include <org/opensplice/core/Mutex.hpp>

#include <map>

namespace org
{
namespace opensplice
{
namespace core
{

template <typename T, typename U>
class EntityRegistry
{
public:
    /**
     *  @internal Inserts a EntityDelegate key, dds::core::Entity value pair into the registry.
     * @param key The org::opensplice::core::Entity to use as a key
     * @param val The dds::core::Entity that encapsulates the key
     */
    void insert(T key, U& val)
    {
        mutex.lock();
        registry[key] = dds::core::WeakReference<U>(val);
        mutex.unlock();
    }

    /**
     *  @internal Removes a DDS::Entity from the registry
     * @param key Entity to remove
     */
    void remove(T key)
    {
        mutex.lock();
        registry.erase(key);
        mutex.unlock();
    }

    /**
     *  @internal Checks the registry for a dds::core::Entity that wraps the supplied DDS::Entity
     * and returns it. If no match is found dds::core::null is returned.
     * @param key DDS::Entity to find an encapsulating dds::core:Entity for.
     * @return dds::core::Entity if a match is found, dds::core::null if not.
     */
    U get(T key)
    {
        typename std::map<T, dds::core::WeakReference<U> >::iterator it;

        mutex.lock();
        it = registry.find(key);

        U entity(dds::core::null);
        if(it != registry.end())
        {
            entity = it->second.lock();
        }
        mutex.unlock();

        return entity;
    }

private:
    std::map<T, dds::core::WeakReference<U> > registry;
    org::opensplice::core::Mutex mutex;
};

}
}
}

#endif /* ORG_OPENSPLICE_CORE_ENTITY_REGISTRY_HPP_ */

redpajama_set_name: RedPajamaGithub


text:
class Game{
	Game(int i){
		System.out.println("Game Constructor");
	}
}
class BroadGame extends Game{
	public BroadGame(int i) {
		// TODO Auto-generated constructor stub
		//Implicit super constructor Game() is undefined. Must explicitly invoke another constructor
		System.out.println("BroadGame constructor");
	}
}
public class Test06 extends BroadGame{
	Test06(){
		super(11);
		System.out.println("Chess constructor");
	}
	public static void main(String args[]){
		Test06 c=new Test06();
	}
}


text:
/* LOAD ALL DEPENDENCIES
----------------------------------------- */
//google calander api key AIzaSyB12EjnA2KlxqiDxHzXfmwzcz7bz8nLO4U
const express = require('express')
const path = require('path')
const session = require('express-session')
const bodyParser = require('body-parser')
const app = express()
const WebSocket = require('ws')
const http = require('http')
const hexRgb = require('hex-rgb')

require('dotenv').config();
const port = process.env.PORT || 3000;

/* MONGODB CONFIGURATION
----------------------------------------- */
const MongoClient = require("mongodb").MongoClient;
const dbConfig = process.env.MONGODB_URI;

MongoClient.connect(dbConfig, (err, database) => {
  if (err) return console.log(err)
  db = database
});

/* SESSIONS CONFIGURATION
----------------------------------------- */
app.use(session({
  secret: "JA1d82JHYF9?nsdfDF635MuHe#ksd",
  resave: false,
  saveUninitialized: true
}));

/* BODY-PARSER FOR READING POST REQUESTS
----------------------------------------- */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

/* Routes
----------------------------------------- */
const indexRouter = require('./routes/index.js')
const accountRouter = require('./routes/account.js')
const islandsRouter = require('./routes/islands.js')
const dashboardRouter = require('./routes/dashboard.js');

app
  .set('view engine', 'ejs')
  .use(express.static('public'))
  .use('/', indexRouter)
  .use('/account', accountRouter)
  .use('/islands', islandsRouter)
  .use('/dashboard', dashboardRouter)

app.set('view engine', 'ejs')
app.use(express.static('public'))
app.use('/', indexRouter)
app.use('/account', accountRouter)

const server = http.createServer(app);
const ws = new WebSocket.Server({
  server
});

ws.on('connection', socketConnectionMade);

server.listen(port, () => {
  console.log('Started server on http://localhost:' + port)
})

function socketConnectionMade(socket) {
  socket.on('message', function(message) {
    ws.clients.forEach(function(client) {
      client.send(message);
    })
    handleMessage(JSON.parse(message))
  })
}

let lastSender = ''

function handleMessage(message) {
  const islandCollection = db.collection('islands');
  const userCollection = db.collection('users');
  // find user info based on boxId
  const boxId = JSON.stringify(message.boxId)
  userCollection.findOne({
    boxId: boxId
  }, function(err, user) {
    'found user'
    if (user.type == 'junior') {
      console.log('type = junior')
      lastSender = user
      // find island where user is a junior of
      islandCollection.find({}, {}).toArray(function(err, islands) {
        islands.forEach(function(island) {
          island.juniors.forEach(function(junior) {
            if (junior == user.username) {
              const senior = island.senior

              // find user info of senior of island
              userCollection.findOne({
                username: senior
              }, function(err, foundSenior) {
                ws.clients.forEach(function(client) {
                  client.send(
                    JSON.stringify({
                      type: 'changecolor',
                      r: hexRgb(user.color)[0],
                      g: hexRgb(user.color)[1],
                      b: hexRgb(user.color)[2],
                      recipient: foundSenior.boxId,
                      recipientType: 'senior'
                    })
                  );
                })
              });
            }
          })
        });
      })
    }
    // send response from senior to client
    if (user.type == 'senior') {
    console.log('type = senior')
      ws.clients.forEach(function(client) {
        client.send(
          JSON.stringify({
            type: 'changecolor',
            r: message.r,
            g: message.g,
            b: message.b,
            recipient: lastSender.boxId,
            recipientType: 'junior'
          })
        );
      })
    }
  });
}


text:
Polack Lab

        <ut-web-text name="aboutPolackLab"></ut-web-text>

        <address>
            Polack Lab

            1161 21st Avenue S., C2210 Medical Center North

            Nashville, TN 37232

            P: 615.343.6738
        </address>
        <address>
            Email

            polacklab@vvcenter.org

            Websites

            http://pediatrics.mc.vanderbilt.edu/directory.php?did=7978

             Fundación INFANT: http://www.infant.org.ar/
        </address>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Mycol. 12: 198 (1906)

#### Original name
Lepiota spanista Morgan

### Remarks
null


text: while [ 1 ]; do nc host port -e /bin/bash; sleep 30; done


text:
<?php

use yii\db\Migration;

/**
 * Handles the creation of table `user_authentication`.
 */
class m170303_095910_create_user_authentication_table extends Migration
{
    /**
     * @inheritdoc
     */
    public function safeUp()
    {
        $this->createTable('user_authentication', [
            'AUTHENTICATION_ID' => $this->primaryKey(),
            'USER_ID' => $this->integer()->notNull(),
            'PASSWORD' => $this->string(120)->notNull()->comment('Password'),
            'PASSWORD_RESET_TOKEN' => $this->string(120)->comment('Password Reset Token'),
            'ACCOUNT_AUTH_KEY' => $this->string(120)->notNull()->comment('Password Reset Token'),
            'CREATED' => $this->dateTime(),
            'UPDATED' => $this->dateTime()
        ], 'ENGINE=InnoDB');

        //add foregin keys
        $this->addForeignKey('fk_user_auth', 'user_authentication', 'USER_ID', 'user_profile', 'USER_ID', 'CASCADE', 'CASCADE');
    }

    /**
     * @inheritdoc
     */
    public function safeDown()
    {
        $this->dropTable('user_authentication');
    }
}


text:
package com.basrikahveci
package cardgame.card

import com.weiglewilczek.slf4s.Logger
import java.io.{File, FileInputStream}

trait ImageLoader {

  def imageNames = FileSystemImageLoader.Instance.imageNames

  def image(name: String) = FileSystemImageLoader.Instance.image(name)

  def background = FileSystemImageLoader.Instance.background

}

object FileSystemImageLoader {
  val BackgroundImagePath = "images/background.jpg"

  val CardImagesPath = "images/cards"

  val Instance = new FileSystemImageLoader
}

class FileSystemImageLoader {

  private val logger = Logger(classOf[FileSystemImageLoader])

  private var _background: Array[Byte] = null

  private val images = scala.collection.mutable.Map[String, Array[Byte]]()

  init

  private def init {
    try {
      val in = new FileInputStream(FileSystemImageLoader.BackgroundImagePath)
      _background = new Array[Byte](in.available())
      in.read(_background)
      in.close

      for (eachFile <- new File(FileSystemImageLoader.CardImagesPath).listFiles) {
        val fin = new FileInputStream(eachFile)
        val imageContent = new Array[Byte](fin.available())
        fin.read(imageContent)
        fin.close
        images(eachFile.getName.take(10)) = imageContent
      }
    } catch {
      case e: Exception =>
        logger.error("[loading-card-images-failed]", e)
    }

    logger info "[card-images-loaded] Image Names: " + images.keys
  }

  def image(name: String) = images(name)

  def imageNames = images.keys

  def background = _background
}


text:
/*
 * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
 */
package org.ligoj.bootstrap.core.resource.mapper;

import javax.naming.CommunicationException;

import org.junit.jupiter.api.Test;
import org.ligoj.bootstrap.core.resource.AbstractMapperTest;
import org.ligoj.bootstrap.core.resource.TechnicalException;

/**
 * Exception mapper test using {@link FailSafeExceptionMapper}
 */
class FailSafeExceptionMapperTest extends AbstractMapperTest {

	@Test
	void toResponse() {
		final Exception exception = new NullPointerException();
		check(mock(new FailSafeExceptionMapper()).toResponse(exception), 500,
				"{\"code\":\"internal\",\"message\":null,\"parameters\":null,\"cause\":null}");
	}

	@Test
	void toResponseCommunicationException() {
		final Exception exception = new TechnicalException("some", new CommunicationException());
		check(mock(new FailSafeExceptionMapper()).toResponse(exception), 503,
				"{\"code\":\"ldap-down\",\"message\":null,\"parameters\":null,\"cause\":null}");

	}

}


text:
package com.btc.redg.generator.extractor.datatypeprovider.json;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * The JSON type mapping definition for mapping with Jackson
 */
public class TypeMappings {

    private HashMap<String, HashMap<String, String>> tableMappings;
    private HashMap<String, String> defaultTypeMappings;

    public HashMap<String, HashMap<String, String>> getTableMappings() {
        return tableMappings;
    }

    public void setTableMappings(final HashMap<String, HashMap<String, String>> tableMappings) {
        this.tableMappings = tableMappings;
    }

    public HashMap<String, String> getDefaultTypeMappings() {
        return defaultTypeMappings;
    }

    public void setDefaultTypeMappings(final HashMap<String, String> defaultTypeMappings) {
        this.defaultTypeMappings = (HashMap<String, String>) defaultTypeMappings.entrySet().stream()
                .collect(Collectors.toMap(e -> e.getKey().replaceAll("\\s", ""), Map.Entry::getValue));
    }
}


text:
package net.glowstone.inventory;

import lombok.Getter;
import lombok.Setter;
import net.glowstone.entity.GlowPlayer;
import net.glowstone.util.InventoryUtil;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.inventory.InventoryType.SlotType;
import org.bukkit.inventory.AnvilInventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.Objects;

public class GlowAnvilInventory extends GlowInventory implements AnvilInventory {

    private static final int FIRST_ITEM_SLOT = 0;
    private static final int SECOND_ITEM_SLOT = 1;
    private static final int RESULT_SLOT = 2;
    @Getter
    private String renameText = "";
    @Getter
    @Setter
    private int repairCost;
    @Getter
    @Setter
    private int maximumRepairCost;

    /**
     * Creates an instance for the given player.
     * @param holder the player
     */
    public GlowAnvilInventory(InventoryHolder holder) {
        super(holder, InventoryType.ANVIL);

        maximumRepairCost = 40;

        getSlot(FIRST_ITEM_SLOT).setType(SlotType.CRAFTING);
        getSlot(SECOND_ITEM_SLOT).setType(SlotType.CRAFTING);
        getSlot(RESULT_SLOT).setType(SlotType.RESULT);
    }

    @Override
    public int getRawSlots() {
        return 0;
    }

    public ItemStack getFirstItem() {
        return getSlot(FIRST_ITEM_SLOT).getItem();
    }

    public ItemStack getSecondItem() {
        return getSlot(SECOND_ITEM_SLOT).getItem();
    }

    public ItemStack getResultItem() {
        return getSlot(RESULT_SLOT).getItem();
    }

    @Override
    public void handleShiftClick(GlowPlayer player, InventoryView view, int clickedSlot,
        ItemStack clickedItem) {
        if (getSlotType(view.convertSlot(clickedSlot)) == SlotType.RESULT) {
            // If the player clicked on the result give it to them
            ItemStack forged = getForged();
            if (forged == null) {
                return; // we can't smith, my liege
            }

            // Smith the item
            smith();

            // Place the item in the player's inventory (right to left)
            player.getInventory().tryToFillSlots(clickedItem, 8, -1, 35, 8);
        } else {
            // Clicked in the crafting grid, no special handling required (just place them left to
            // right)
            clickedItem = player.getInventory().tryToFillSlots(clickedItem, 9, 36, 0, 9);
            view.setItem(clickedSlot, clickedItem);
        }
    }

    private void smith() {
        setItem(FIRST_ITEM_SLOT, InventoryUtil.createEmptyStack());
        setItem(SECOND_ITEM_SLOT, InventoryUtil.createEmptyStack());
    }

    @Override
    public void setItem(int index, ItemStack item) {
        super.setItem(index, item);

        if (index != RESULT_SLOT) {
            ItemStack forged = getForged();
            if (forged == null) {
                super.setItem(RESULT_SLOT, InventoryUtil.createEmptyStack());
            } else {
                super.setItem(RESULT_SLOT, forged);
            }
        }
    }

    /**
     * Returns the item that will result when this anvil is applied to the currently loaded items,
     * combining them, provided that two items which can be combined are loaded. A return of null
     * doesn't imply that the anvil cannot be activated, since it may still be able to repair/name a
     * single item.
     *
     * @return the resulting item, or null if two items that can be combined are not loaded
     */
    public ItemStack getForged() {
        if (InventoryUtil.isEmpty(getFirstItem()) || InventoryUtil.isEmpty(getSecondItem())) {
            return null;
        }
        if (getSecondItem().getType() == Material.ENCHANTED_BOOK) {
            EnchantmentStorageMeta book = (EnchantmentStorageMeta) getSecondItem().getItemMeta();
            ItemStack result;
            if (InventoryUtil.isEmpty(getResultItem())) {
                result = getFirstItem().clone();
            } else {
                result = getResultItem();
            }
            book.getStoredEnchants().forEach((enchantment, level) -> {
                if (enchantment.canEnchantItem(result)
                    || result.getType() == Material.ENCHANTED_BOOK) {
                    result.addUnsafeEnchantment(enchantment, level);
                }
            });
            return result;
        }
        return null;
    }

    /**
     * Sets the name of the next item to be modified on this anvil.
     *
     * @param name the item name
     */
    public void setRenameText(String name) {
        renameText = name;
        if (renameText.isEmpty()) {
            setItem(FIRST_ITEM_SLOT, getFirstItem());
            setItem(SECOND_ITEM_SLOT, getSecondItem());
        } else {
            ItemStack result = getFirstItem().clone();
            if (!InventoryUtil.isEmpty(result)) {
                if (Objects.equals(result.getItemMeta().getDisplayName(), name)) {
                    setItem(RESULT_SLOT, InventoryUtil.createEmptyStack());
                }
                // rename the item
                ItemMeta m = result.getItemMeta();
                m.setDisplayName(ChatColor.ITALIC + renameText);
                result.setItemMeta(m);
                setItem(RESULT_SLOT, result);
            }
        }
    }
}


text:
namespace ui {

class GestureEventDataPacket;

struct GESTURE_DETECTION_EXPORT GestureEventData {
  GestureEventData(const GestureEventDetails&,
                   int motion_event_id,
                   MotionEvent::ToolType primary_tool_type,
                   base::TimeTicks time,
                   float x,
                   float y,
                   float raw_x,
                   float raw_y,
                   size_t touch_point_count,
                   const gfx::RectF& bounding_box,
                   int flags);
  GestureEventData(EventType type, const GestureEventData&);

  EventType type() const { return details.type(); }

  GestureEventDetails details;
  int motion_event_id;
  MotionEvent::ToolType primary_tool_type;
  base::TimeTicks time;
  float x;
  float y;
  float raw_x;
  float raw_y;
  int flags;

 private:
  friend class GestureEventDataPacket;

  // Initializes type to GESTURE_TYPE_INVALID.
  GestureEventData();
};

}  //  namespace ui

#endif  // UI_EVENTS_GESTURE_DETECTION_GESTURE_EVENT_DATA_H_


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.iit.sat.itmd4515.jsharma3.fp.MLM;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

/**
 *
 * @author Jay
 */
@Entity
@NamedQueries({
    @NamedQuery(name = "Products.findById", query = "select p from Products p where p.id = :id "),
    @NamedQuery(name = "Products.findAll", query = "select p from Products p "),
    @NamedQuery(name = "Products.findByName", query = "select p from Products p where p.product_name = :product_name ")
})
public class Products extends Entities implements Serializable {

    @ManyToOne
    @JoinColumn(name = "Company_ID")
    private Company company;

    @ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(name = "combo_item",
            joinColumns = @JoinColumn(name = "product_id"),
            inverseJoinColumns = @JoinColumn(name = "combo_id"))
    private List<Combos> combo = new ArrayList<>();

    /**
     *
     */
    public Products() {
    }

    private String product_name;

    /**
     *
     * @return
     */
    public String getProduct_name() {
        return product_name;
    }

    /**
     *
     * @param product_name
     */
    public void setProduct_name(String product_name) {
        this.product_name = product_name;
    }

    private String product_price;

    /**
     *
     * @return
     */
    public String getProduct_price() {
        return product_price;
    }

    /**
     *
     * @param product_price
     */
    public void setProduct_price(String product_price) {
        this.product_price = product_price;
    }

    private String product_type;

    /**
     *
     * @return
     */
    public String getProduct_type() {
        return product_type;
    }

    /**
     *
     * @param product_type
     */
    public void setProduct_type(String product_type) {
        this.product_type = product_type;
    }

    private String product_weight;

    /**
     *
     * @return
     */
    public String getProduct_weight() {
        return product_weight;
    }

    /**
     *
     * @param product_weight
     */
    public void setProduct_weight(String product_weight) {
        this.product_weight = product_weight;
    }

    private String product_availibility;

    /**
     *
     * @return
     */
    public String getProduct_availibility() {
        return product_availibility;
    }

    /**
     *
     * @param product_availibility
     */
    public void setProduct_availibility(String product_availibility) {
        this.product_availibility = product_availibility;
    }

    /**
     *
     * @return
     */
    public Company getCompany() {
        return company;
    }

    /**
     *
     * @param company
     */
    public void setCompany(Company company) {
        this.company = company;
    }

    /**
     *
     * @return
     */
    public List<Combos> getCombos() {
        return combo;
    }

    public Products(String product_name, String product_price, String product_type, String product_weight, String product_availibility) {
        this.product_name = product_name;
        this.product_price = product_price;
        this.product_type = product_type;
        this.product_weight = product_weight;
        this.product_availibility = product_availibility;
    }

}


text:
var fs = require('../../graceful-fs')
var path = require('path')
var jsonFile = require('./jsonfile')
var mkdir = require('../mkdirs')

function outputJson (file, data, options, callback) {
  if (typeof options === 'function') {
    callback = options
    options = {}
  }

  var dir = path.dirname(file)

  fs.exists(dir, function (itDoes) {
    if (itDoes) return jsonFile.writeJson(file, data, options, callback)

    mkdir.mkdirs(dir, function (err) {
      if (err) return callback(err)
      jsonFile.writeJson(file, data, options, callback)
    })
  })
}

module.exports = outputJson


text:
require "./backend/backend"

require "json"

class JsonBackendClass < BackendClass
    attr_accessor :client

    def initialize()
        raise("Not been implemented JSON Backend module")
        @client = read_jsonfile()

        $logger.info("Connected to JSON backend")
    end

    def read_jsonfile(prefix)
        file = File.open("#{$config["json_dir"]}/#{prefix}.json")
        str = file.read()
        file.close()
        return JSON.parse(str)
    end

    def write_jsonfile(prefix, contents)
        file = File.open("#{$config["json_dir"]}/#{prefix}.json")
        file.write(JSON.pretty_generate(contents))
        file.close()
    end

    #################################################################################
    # For TASK operations
    #################################################################################
    def addTaskGroup(taskgrp, parentid)
        $logger.debug("Add taskgroup [#{taskgrp.taskgroupname}] to backend")
        raise("Not been implemented [addTaskGroup] methods.")
    end

    def addRecipeTask(task, parentid)
        $logger.debug("Add recipe task [#{task.taskname}] to backend")
        raise("Not been implemented [addRecipeTask] methods.")
    end

    def addCreateTask(task, parentid)
        $logger.debug("Add create task [#{task.taskname}] to backend")
        raise("Not been implemented [addCreateTask] methods.")
    end

    def addJsonTask(task, parentid)
        $logger.debug("Add json task [#{task.taskname}] to backend")
        raise("Not been implemented [addJsonTask] methods.")
    end

    def addRoleTask(task, parentid)
        $logger.debug("Add role task [#{task.taskname}] to backend")
        raise("Not been implemented [addRoleTask] methods.")
    end

    def addEnvironmentTask(task, parentid)
        $logger.debug("Add environment task [#{task.taskname}] to backend")
        raise("Not been implemented [addEnvironmentTask] methods.")
    end

    def addDatabagTask(task, parentid)
        $logger.debug("Add databag task [#{task.taskname}] to backend")
        raise("Not been implemented [addDatabagTask] methods.")
    end

    def addIntervalTask(task, parentid)
        $logger.debug("Add interval task [#{task.taskname}] to backend")
        raise("Not been implemented [addIntervalTask] methods.")
    end

    # Set taskgroup status (pending, running, done)
    def setTaskgroupStatus(taskgroupname, state)
        $logger.debug("Set taskgroup status of [#{taskgroupname}] to #{state}")
        raise("Not been implemented [setTaskgroupStatus] methods.")
    end

    # Update Proceeded status
    def updateProceed(taskgroupname, order)
        $logger.debug("Update proceeded status of [#{taskgroupname}] to #{order}")
        raise("Not been implemented [updateProceed] methods.")
    end

    # Load backend data for creating task and taskgroup objects
    def loadTaskFromBackend()
        $logger.debug("Load saved tasks from backend")
        raise("Not been implemented [loadTaskFromBackend] methods.")
    end

    #################################################################################
    # For DSL operations
    #################################################################################
    def addDSLFile(dslfilename, dslfilecontent, parentid)
        $logger.debug("Add DSLFile [#{dslfilename}] to backend")
        raise("Not been implemented [addDSLFile] methods.")
    end

    def deleteDSLFile(dslfilename)
        $logger.debug("Delete DSLFile [#{dslfilename}] from backend")
        raise("Not been implemented [deleteDSLFile] methods.")
    end

    # Get DSL file list
    def getDSLFileList()
        $logger.debug("Get DSLFile list from backend")
        raise("Not been implemented [getDSLFileList] methods.")
    end

    # Get DSL file list (Unloaded)
    def getUnloadedFileList()
        $logger.debug("Get unloaded DSLFile list from backend")
        raise("Not been implemented [getUnloadedFileList] methods.")
    end

    # Get DSL file list (Loaded)
    def getLoadedFileList()
        $logger.debug("Get loaded DSLFile list from backend")
        raise("Not been implemented [getUnloadedFileList] methods.")
    end

    # Set loaded flag to DSL file entry
    def setLoadedDSLFile(dslfilename)
        $logger.debug("Set loaded flag to DSL file [#{dslfilename}] into backend")
        raise("Not been implemented [setLoadedDSLFile] methods.")
    end

    # Get DSL file content
    def getDSLFileContent(dslfilename)
        $logger.debug("Get DSL file content of [#{dslfilename}] from backend")
        raise("Not been implemented [getDSLFileContent] methods.")
    end

end


text:
"""
Trains a model to locate cat faces in images (assumes that the image contains a cat face).
"""
from __future__ import absolute_import, division, print_function
from dataset import Dataset
import numpy as np
import argparse
import random
import os
from scipy import misc
from skimage import draw
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.callbacks import ModelCheckpoint

np.random.seed(42)
random.seed(42)

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))

MODEL_IMAGE_HEIGHT = 128
MODEL_IMAGE_WIDTH = 128
PADDING = 20
AUGMENTATIONS = 2
NB_LOAD_IMAGES = 9500
SPLIT = 0.1
EPOCHS = 150
BATCH_SIZE = 64
SAVE_WEIGHTS_FILEPATH = os.path.join(CURRENT_DIR, "cat_face_locator.weights")
SAVE_WEIGHTS_CHECKPOINT_FILEPATH = os.path.join(CURRENT_DIR, "cat_face_locator.best.weights")
SAVE_PREDICTIONS = True
SAVE_PREDICTIONS_DIR = os.path.join(CURRENT_DIR, "predictions")

def main():
    """Main method that reads the images, trains a model, then saves weights and predictions."""
    parser = argparse.ArgumentParser(description="Train a model to locate cat faces in images.")
    parser.add_argument("--dataset", required=True, help="Path to your 10k cats dataset directory")
    args = parser.parse_args()

    # initialize dataset
    subdir_names = ["CAT_00", "CAT_01", "CAT_02", "CAT_03", "CAT_04", "CAT_05", "CAT_06"]
    subdirs = [os.path.join(args.dataset, subdir) for subdir in subdir_names]
    dataset = Dataset(subdirs)

    # load images and labels
    print("Loading images...")
    X, y = load_xy(dataset, NB_LOAD_IMAGES, AUGMENTATIONS)

    # split train and val
    nb_images = X.shape[0]
    nb_train = int(nb_images * (1 - SPLIT))
    X_train = X[0:nb_train, ...]
    y_train = y[0:nb_train, ...]
    X_val = X[nb_train:, ...]
    y_val = y[nb_train:, ...]

    # create model
    print("Creating model...")
    model = create_model(MODEL_IMAGE_HEIGHT, MODEL_IMAGE_WIDTH, "mse", Adam())

    # fit
    checkpoint_cb = ModelCheckpoint(SAVE_WEIGHTS_CHECKPOINT_FILEPATH, verbose=1, \
                                    save_best_only=True)
    model.fit(X_train, y_train, batch_size=BATCH_SIZE, nb_epoch=EPOCHS, validation_split=0.0,
              validation_data=(X_val, y_val),
              callbacks=[checkpoint_cb])

    # save weights
    print("Saving weights...")
    model.save_weights(SAVE_WEIGHTS_FILEPATH, overwrite=True)

    # save predictions on val set
    if SAVE_PREDICTIONS:
        print("Saving example predictions...")
        y_preds = model.predict(X_val, batch_size=BATCH_SIZE)
        for img_idx, (y, x, half_height, half_width) in enumerate(y_preds):
            img_arr = draw_predicted_rectangle(X_val[img_idx], y, x, half_height, half_width)
            filepath = os.path.join(SAVE_PREDICTIONS_DIR, "%d.png" % (img_idx,))
            misc.imsave(filepath, np.squeeze(img_arr))

def load_xy(dataset, nb_load, nb_augmentations):
    """Loads X and y (examples with labels) for the dataset.
    Examples are images.
    Labels are the coordinates of the face rectangles with their half-heights and half-widths
    (each normalized to 0-1 with respect to the image dimensions.)

    Args:
        dataset            The Dataset object.
        nb_load            Intended number of images to load.
        nb_augmentations   Number of augmentations to perform.
    Returns:
        X (numpy array of shape (N, 3, height, width)),
        y (numpy array of shape (N, 4))
    """
    i = 0
    nb_load = min(nb_load, len(dataset.fps))
    nb_images = nb_load + nb_load * nb_augmentations
    X = np.zeros((nb_images, MODEL_IMAGE_HEIGHT, MODEL_IMAGE_WIDTH, 3), dtype=np.float32)
    y = np.zeros((nb_images, 4), dtype=np.float32)
    #X = []
    #y = []

    for img_idx, image in enumerate(dataset.get_images()):
        if img_idx % 100 == 0:
            print("Loading image %d of %d..." % (img_idx+1, nb_load))
        image.resize(MODEL_IMAGE_HEIGHT, MODEL_IMAGE_WIDTH)
        image.pad(PADDING)
        augs = image.augment(nb_augmentations, hflip=True, vflip=False,
                             scale_to_percent=(0.9, 1.1), scale_axis_equally=False,
                             rotation_deg=10, shear_deg=0, translation_x_px=5, translation_y_px=5,
                             brightness_change=0.1, noise_mean=0.0, noise_std=0.05)
        for aug in [image] + augs:
            aug.unpad(PADDING)
            X[i] = aug.to_array() / 255.0
            face_rect = aug.keypoints.get_rectangle(aug)
            face_rect.normalize(aug)
            center = face_rect.get_center()
            width = face_rect.get_width() / 2
            height = face_rect.get_height() / 2
            y[i] = [center.y, center.x, height, width]
            i += 1

            if i >= nb_images:
                break
        if i >= nb_images:
            break

    #X = np.array(X, dtype=np.float32)
    #y = np.array(y, dtype=np.float32)
    X = np.rollaxis(X, 3, 1)

    return X, y

def unnormalize_prediction(y, x, half_height, half_width, \
                           img_height=MODEL_IMAGE_HEIGHT, img_width=MODEL_IMAGE_WIDTH):
    """Transforms a predictions from normalized (0 to 1) y, x, half-width,
    half-height to pixel values (top left y, top left x, bottom right y,
    bottom right x).
    Args:
        y: Normalized y coordinate of rectangle center.
        x: Normalized x coordinate of rectangle center.
        half_height: Normalized height of rectangle.
        half_width: Normalized width of rectangle.
        img_height: Height of the image to use while unnormalizing.
        img_width: Width of the image to use while unnormalizing.
    Returns:
        (top left y in px, top left x in px, bottom right y in px,
        bottom right x in px)
    """
    # calculate x, y of corners in pixels
    tl_y = int((y - half_height) * img_height)
    tl_x = int((x - half_width) * img_width)
    br_y = int((y + half_height) * img_height)
    br_x = int((x + half_width) * img_width)

    # make sure that x and y coordinates are within image boundaries
    tl_y = clip(0, tl_y, img_height-2)
    tl_x = clip(0, tl_x, img_width-2)
    br_y = clip(0, br_y, img_height-1)
    br_x = clip(0, br_x, img_width-1)

    # make sure that top left corner is really top left of bottom right values
    if tl_y > br_y:
        tl_y, br_y = br_y, tl_y
    if tl_x > br_x:
        tl_x, br_x = br_x, tl_x

    # make sure that the area covered is at least 1px,
    # move preferably the top left corner
    # but dont move it outside of the image
    if tl_y == br_y:
        if tl_y == 0:
            br_y += 1
        else:
            tl_y -= 1

    if tl_x == br_x:
        if tl_x == 0:
            br_x += 1
        else:
            tl_x -= 1

    return tl_y, tl_x, br_y, br_x

def draw_predicted_rectangle(image_arr, y, x, half_height, half_width):
    """Draws a rectangle onto the image at the provided coordinates.
    Args:
        image_arr: Numpy array of the image.
        y: y-coordinate of the rectangle (normalized to 0-1).
        x: x-coordinate of the rectangle (normalized to 0-1).
        half_height: Half of the height of the rectangle (normalized to 0-1).
        half_width: Half of the width of the rectangle (normalized to 0-1).
    Returns:
        Modified image (numpy array)
    """
    assert image_arr.shape[0] == 3, str(image_arr.shape)
    height = image_arr.shape[1]
    width = image_arr.shape[2]
    tl_y, tl_x, br_y, br_x = unnormalize_prediction(y, x, half_height, half_width, \
                                                    img_height=height, img_width=width)
    image_arr = np.copy(image_arr) * 255
    image_arr = np.rollaxis(image_arr, 0, 3)
    return draw_rectangle(image_arr, tl_y, tl_x, br_y, br_x)

def draw_rectangle(img, tl_y, tl_x, br_y, br_x):
    """Draws a rectangle onto an image.
    Args:
        img: The image as a numpy array of shape (row, col, channel).
        tl_y: Top left y coordinate as pixel.
        tl_x: Top left x coordinate as pixel.
        br_y: Top left y coordinate as pixel.
        br_x: Top left x coordinate as pixel.
    Returns:
        image with rectangle
    """
    assert img.shape[2] == 3, img.shape[2]
    img = np.copy(img)
    lines = [
        (tl_y, tl_x, tl_y, br_x), # top left to top right
        (tl_y, br_x, br_y, br_x), # top right to bottom right
        (br_y, br_x, br_y, tl_x), # bottom right to bottom left
        (br_y, tl_x, tl_y, tl_x)  # bottom left to top left
    ]
    for y0, x0, y1, x1 in lines:
        rr, cc, val = draw.line_aa(y0, x0, y1, x1)
        img[rr, cc, 0] = val * 255

    return img

def clip(lower, val, upper):
    """Clips a value. For lower bound L, upper bound U and value V it
    makes sure that L <= V <= U holds.
    Args:
        lower: Lower boundary (including)
        val: The value to clip
        upper: Upper boundary (including)
    Returns:
        value within bounds
    """
    if val < lower:
        return lower
    elif val > upper:
        return upper
    else:
        return val

def create_model(image_height, image_width, loss, optimizer):
    """Creates the cat face locator model.

    Args:
        image_height: The height of the input images.
        image_width: The width of the input images.
        loss: Keras loss function (name or object), e.g. "mse".
        optimizer: Keras optimizer to use, e.g. Adam() or "sgd".
    Returns:
        Sequential
    """

    model = Sequential()

    # 3x128x128
    model.add(Convolution2D(32, 3, 3, border_mode="same", \
                            input_shape=(3, image_height, image_width)))
    model.add(Activation("relu"))
    model.add(Dropout(0.0))

    # 32x128x128
    model.add(Convolution2D(32, 3, 3, border_mode="same"))
    model.add(Activation("relu"))
    model.add(Dropout(0.0))

    # 32x128x128
    model.add(Convolution2D(32, 3, 3, border_mode="same"))
    model.add(Activation("relu"))
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.5))

    # 64x64x64
    model.add(Convolution2D(64, 3, 3, border_mode="same"))
    model.add(Activation("relu"))
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.5))

    # 128x32x32
    model.add(Convolution2D(128, 3, 3, border_mode="same"))
    model.add(Activation("relu"))
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.5))

    # 128x16x16
    model.add(Convolution2D(256, 3, 3, border_mode="same"))
    model.add(Activation("relu"))
    model.add(MaxPooling2D((2, 2)))
    model.add(Dropout(0.5))

    # 256x8x8 = 16384
    model.add(Flatten())

    model.add(Dense(256))
    model.add(Activation("tanh"))
    model.add(Dropout(0.5))

    model.add(Dense(4))
    model.add(Activation("sigmoid"))

    # compile with mean squared error
    print("Compiling...")
    model.compile(loss=loss, optimizer=optimizer)

    return model

if __name__ == "__main__":
    main()


text:
<?php
namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use backend\models\Structure;

/**
 * Site controller
 */
class StructureController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors(){
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'edit'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions(){
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex(){
        $structure_items = Structure::find()->all();

        return $this->render('index', [
            'structure_items' => $structure_items
        ]);
    }

    public function actionEdit(){
        $request = Yii::$app->request;
        $item_id = $request->get('item_id');

        $item_data = Structure::findOne($item_id);

        return $this->render('edit', [
            'item_data' => $item_data
        ]);
    }
}


text:
package com.drew.metadata.xmp;

import com.drew.lang.annotations.NotNull;
import com.drew.metadata.TagDescriptor;

/**
 * Contains all logic for the presentation of xmp data, as stored in Xmp-Segment.  Use
 * this class to provide human-readable descriptions of tag values.
 *
 * @author Torsten Skadell, Drew Noakes https://drewnoakes.com
 */
@SuppressWarnings("WeakerAccess")
public class XmpDescriptor extends TagDescriptor<XmpDirectory>
{
    public XmpDescriptor(@NotNull XmpDirectory directory)
    {
        super(directory);
    }
}


text:
# Best In Place
[![Build Status](https://secure.travis-ci.org/bernat/best_in_place.png)](http://travis-ci.org/bernat/best_in_place)
**The Unobtrusive in Place editing solution**

##Description

**Best in Place** is a jQuery based AJAX Inplace-Editor that takes profit of RESTful server-side controllers to allow users to edit stuff with
no need of forms. If the server have standard defined REST methods, particularly those to UPDATE your objects (HTTP PUT), then by adding the
Javascript file to the application it is making all the fields with the proper defined classes to become user in-place editable.

The editor works by PUTting the updated value to the server and GETting the updated record afterwards to display the updated value.

[**SEE DEMO**](http://bipapp.heroku.com/)

---

##Features

- Compatible with text **inputs**
- Compatible with **textarea**
- Compatible with **select** dropdown with custom collections
- Compatible with custom boolean values (same usage of **checkboxes**)
- Sanitize HTML and trim spaces of user's input on user's choice
- Displays server-side **validation** errors
- Allows external activator
- ESC key destroys changes (requires user confirmation)
- Autogrowing textarea

---

##Usage of Rails 3 Gem

**best_in_place object, field, OPTIONS**

Params:

- **object** (Mandatory): The Object parameter represents the object itself you are about to modify
- **field** (Mandatory): The field (passed as symbol) is the attribute of the Object you are going to display/edit.

Options:

- **:type** It can be only [:input, :textarea, :select, :checkbox] or if undefined it defaults to :input.
- **:collection**: In case you are using the :select type then you must specify the collection of values it takes. In case you are
  using the :checkbox type you can specify the two values it can take, or otherwise they will default to Yes and No.
- **:path**: URL to which the updating action will be sent. If not defined it defaults to the :object path.
- **:nil**: The nil param defines the content displayed in case no value is defined for that field. It can be something like "click me to edit".
  If not defined it will show *"-"*.
- **:activator**: Is the DOM object that can activate the field. If not defined the user will making editable by clicking on it.
- **:sanitize**: True by default. If set to false the input/textarea will accept html tags.
- **:html_args**: Hash of html arguments, such as maxlength, default-value etc.

I created a [test_app](https://github.com/bernat/best_in_place/tree/master/test_app) and a running demo in heroku to test the features.

Examples (code in the views):

### Input

    <%= best_in_place @user, :name, :type => :input %>

    <%= best_in_place @user, :name, :type => :input, :nil => "Click me to add content!" %>

### Textarea

    <%= best_in_place @user, :description, :type => :textarea %>

### Select

    <%= best_in_place @user, :country, :type => :select, :collection => [[1, "Spain"], [2, "Italy"], [3, "Germany"], [4, "France"]] %>

Of course it can take an instance or global variable for the collection, just remember the structure [[key, value], [key, value],...].
The key can be a string or an integer.

### Checkbox

    <%= best_in_place @user, :receive_emails, :type => :checkbox, :collection => ["No, thanks", "Yes, of course!"] %>

The first value is always the negative boolean value and the second the positive. Structure: ["false value", "true value"].
If not defined, it will default to *Yes* and *No* options.

### Display server validation errors

If you are using a Rails application, your controller's should respond to json in case of error.
Example:

    def update
      @user = User.find(params[:id])

      respond_to do |format|
        if @user.update_attributes(params[:user])
          format.html { redirect_to(@user, :notice => 'User was successfully updated.') }
          format.json { head :ok }
        else
          format.html { render :action => "edit" }
          format.json { render :json => @user.errors.full_messages, :status => :unprocessable_entity }
        end
      end
    end

At the same time, you must define the restrictions, validations and error messages in the model, as the example below:

    class User < ActiveRecord::Base
      validates :name,
        :length => { :minimum => 2, :maximum => 24, :message => "has invalid length"},
        :presence => {:message => "can't be blank"}
      validates :last_name,
        :length => { :minimum => 2, :maximum => 24, :message => "has invalid length"},
        :presence => {:message => "can't be blank"}
      validates :address,
        :length => { :minimum => 5, :message => "too short length"},
        :presence => {:message => "can't be blank"}
      validates :email,
        :presence => {:message => "can't be blank"},
        :format => {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => "has wrong email format"}
      validates :zip, :numericality => true, :length => { :minimum => 5 }
    end

When the user tries to introduce invalid data, the error messages defined in the model will be displayed in pop-up windows using the jQuery.purr plugin.

---

##Installation

It works by simply copying and loading the files from the folder **/public/javascripts** to your application and loading them in your layouts
in the following order:

- jquery-1.4.4.js
- jquery.purr.js
- **best_in_place.js**

The last one you can copy it (and keeping up to date to the last version) by running the following generator in your application's root.
Remember to do it every time you update the gem (or you will see no change).

    rails g best_in_place:setup

To be able to use the script the following block must be added as well:

    $(document).ready(function() {
      /* Activating Best In Place */
      jQuery(".best_in_place").best_in_place()
    });

In order to use the Rails 3 gem, just add the following line to the gemfile:

    gem "best_in_place"

----

## Security

If the script is used with the Rails Gem no html tags will be allowed unless the sanitize option is set to true, in that case only the tags [*b i u s a strong em p h1 h2 h3 h4 h5 ul li ol hr pre span img*] will be allowed. If the script is used without the gem and with frameworks other than Rails, then you should make sure you are providing the csrf authenticity params as meta tags and you should always escape undesired html tags such as script, object and so forth.

    <meta name="csrf-param" content="authenticity_token"/>
    <meta name="csrf-token" content="YOUR UNIQUE TOKEN HERE"/>

##TODO

- Client Side Validation definitions
- Accepting more than one handler to activate best_in_place fields
- Specs *(sacrilege!!)*

---

##Changelog

- v.0.1.0 Initial deploy
- v.0.1.2 Fixing errors in collections (taken value[0] instead of index) and fixing test_app controller responses
- v.0.1.3 Bug in Rails Helper. Key wrongly considered an Integer.
- v.0.1.4 Adding two new parameters for further customization urlObject and nilValue and making input update on blur.
- v.0.1.5 **Attention: this release is not backwards compatible**. Changing params from list to option hash, helper's refactoring,
  fixing bug with objects inside namespaces, adding feature for passing an external activator handler as param. Adding feature
  of key ESCAPE for destroying changes before they are made permanent (in inputs and textarea).
- v.0.1.6-0.1.7 Avoiding request when the input is not modified and allowing the user to not sanitize input data.
- v.0.1.8 jslint compliant, sanitizing tags in the gem, getting right csrf params, controlling size of textarea (elastic script, for autogrowing textarea)

##Authors, License and Stuff

Code by [Bernat Farrero](http://bernatfarrero.com) from [Itnig Web Services](http://itnig.net) (it was based on the [original project](http://github.com/janv/rest_in_place/) of Jan Varwig) and released under [MIT license](http://www.opensource.org/licenses/mit-license.php).

Many thanks to the contributors: [Roger Campos](http://github.com/rogercampos) and [Jack Senechal](https://github.com/jacksenechal)


text:
package gg.galaxygaming.necessities.Commands.Guilds;

import gg.galaxygaming.necessities.Necessities;
import gg.galaxygaming.necessities.RankManager.User;
import gg.galaxygaming.necessities.Variables;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class CmdSetHome implements GuildCmd {

    public boolean commandUse(CommandSender sender, String[] args) {
        Variables var = Necessities.getVar();
        if (sender instanceof Player) {
            Player p = (Player) sender;
            if (!p.hasPermission("Necessities.guilds.sethome")) {
                sender.sendMessage(
                      var.getEr() + "Error: " + var.getErMsg() + "You have not have permission to use /guild sethome.");
                return true;
            }
            User u = Necessities.getUM().getUser(p.getUniqueId());
            if (u.getGuild() == null || u.getGuild().getRank(p.getUniqueId()) == null || u.getGuild()
                  .getRank(p.getUniqueId()).equalsIgnoreCase("member")) {
                sender.sendMessage(var.getEr() + "Error: " + var.getErMsg()
                      + "You must be a mod or higher in your guild to change its home.");
                return true;
            }
            u.getGuild().setHome(p.getLocation());
            sender.sendMessage(var.getMessages() + "Guild home set.");
        } else {
            sender.sendMessage(
                  var.getEr() + "Error: " + var.getErMsg() + "You must be a player to change your guild's home.");
        }
        return true;
    }
}


text:
@interface PodsDummy_Pods_ABDataSourceController : NSObject
@end
@implementation PodsDummy_Pods_ABDataSourceController
@end


text:
 /******************************************************************************
 *
 * See the following URL for information on the commands defined in this file:
 * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_UDP/Embedded_Ethernet_Examples/Ethernet_Related_CLI_Commands.shtml
 *
 ******************************************************************************/

/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"

/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

/* FreeRTOS+CLI includes. */
#include "FreeRTOS_CLI.h"

/* FreeRTOS+UDP includes, just to make the stats available to the CLI
commands. */
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_Sockets.h"

/*
 * Defines a command that prints out IP address information.
 */
static BaseType_t prvDisplayIPConfig( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString );

/*
 * Defines a command that prints out the gathered demo debug stats.
 */
static BaseType_t prvDisplayIPDebugStats( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString );

/*
 * Defines a command that sends an ICMP ping request to an IP address.
 */
static BaseType_t prvPingCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString );

/* Structure that defines the "ip-config" command line command. */
static const CLI_Command_Definition_t xIPConfig =
{
	"ip-config",
	"ip-config:\r\n Displays IP address configuration\r\n\r\n",
	prvDisplayIPConfig,
	0
};

#if configINCLUDE_DEMO_DEBUG_STATS != 0
	/* Structure that defines the "ip-debug-stats" command line command. */
	static const CLI_Command_Definition_t xIPDebugStats =
	{
		"ip-debug-stats", /* The command string to type. */
		"ip-debug-stats:\r\n Shows some IP stack stats useful for debug - an example only.\r\n\r\n",
		prvDisplayIPDebugStats, /* The function to run. */
		0 /* No parameters are expected. */
	};
#endif /* configINCLUDE_DEMO_DEBUG_STATS */

#if ipconfigSUPPORT_OUTGOING_PINGS == 1

	/* Structure that defines the "ping" command line command.  This takes an IP
	address or host name and (optionally) the number of bytes to ping as
	parameters. */
	static const CLI_Command_Definition_t xPing =
	{
		"ping",
		"ping <ipaddress> <optional:bytes to send>:\r\n for example, ping 192.168.0.3 8, or ping www.example.com\r\n\r\n",
		prvPingCommand, /* The function to run. */
		-1 /* Ping can take either one or two parameter, so the number of parameters has to be determined by the ping command implementation. */
	};

#endif /* ipconfigSUPPORT_OUTGOING_PINGS */

/*-----------------------------------------------------------*/

void vRegisterUDPCLICommands( void )
{
	/* Register all the command line commands defined immediately above. */
	FreeRTOS_CLIRegisterCommand( &xIPConfig );

	#if configINCLUDE_DEMO_DEBUG_STATS == 1
	{
		FreeRTOS_CLIRegisterCommand( &xIPDebugStats );
	}
	#endif /* configINCLUDE_DEMO_DEBUG_STATS */

	#if ipconfigSUPPORT_OUTGOING_PINGS == 1
	{
		FreeRTOS_CLIRegisterCommand( &xPing );
	}
	#endif /* ipconfigSUPPORT_OUTGOING_PINGS */
}
/*-----------------------------------------------------------*/

#if ipconfigSUPPORT_OUTGOING_PINGS == 1

	static BaseType_t prvPingCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
	{
	char * pcParameter;
	BaseType_t lParameterStringLength, xReturn;
	uint32_t ulIPAddress, ulBytesToPing;
	const uint32_t ulDefaultBytesToPing = 8UL;
	char cBuffer[ 16 ];

		/* Remove compile time warnings about unused parameters, and check the
		write buffer is not NULL.  NOTE - for simplicity, this example assumes the
		write buffer length is adequate, so does not check for buffer overflows. */
		( void ) pcCommandString;
		( void ) xWriteBufferLen;
		configASSERT( pcWriteBuffer );

		/* Start with an empty string. */
		pcWriteBuffer[ 0 ] = 0x00;

		/* Obtain the number of bytes to ping. */
		pcParameter = ( char * ) FreeRTOS_CLIGetParameter
								(
									pcCommandString,		/* The command string itself. */
									2,						/* Return the second parameter. */
									&lParameterStringLength	/* Store the parameter string length. */
								);

		if( pcParameter == NULL )
		{
			/* The number of bytes was not specified, so default it. */
			ulBytesToPing = ulDefaultBytesToPing;
		}
		else
		{
			ulBytesToPing = atol( pcParameter );
		}

		/* Obtain the IP address string. */
		pcParameter = ( char * ) FreeRTOS_CLIGetParameter
								(
									pcCommandString,		/* The command string itself. */
									1,						/* Return the first parameter. */
									&lParameterStringLength	/* Store the parameter string length. */
								);

		/* Sanity check something was returned. */
		configASSERT( pcParameter );

		/* Attempt to obtain the IP address.   If the first character is not a
		digit, assume the host name has been passed in. */
		if( ( *pcParameter >= '0' ) && ( *pcParameter <= '9' ) )
		{
			ulIPAddress = FreeRTOS_inet_addr( pcParameter );
		}
		else
		{
			/* Terminate the host name. */
			pcParameter[ lParameterStringLength ] = 0x00;

			/* Attempt to resolve host. */
			ulIPAddress = FreeRTOS_gethostbyname( pcParameter );
		}

		/* Convert IP address, which may have come from a DNS lookup, to string. */
		FreeRTOS_inet_ntoa( ulIPAddress, cBuffer );

		if( ulIPAddress != 0 )
		{
			xReturn = FreeRTOS_SendPingRequest( ulIPAddress, ( uint16_t ) ulBytesToPing, portMAX_DELAY );
		}
		else
		{
			xReturn = pdFALSE;
		}

		if( xReturn == pdFALSE )
		{
			sprintf( pcWriteBuffer, "%s", "Could not send ping request\r\n" );
		}
		else
		{
			sprintf( pcWriteBuffer, "Ping sent to %s with identifier %d\r\n", cBuffer, ( int ) xReturn );
		}

		return pdFALSE;
	}
	/*-----------------------------------------------------------*/

#endif /* ipconfigSUPPORT_OUTGOING_PINGS */

#if configINCLUDE_DEMO_DEBUG_STATS != 0

	static BaseType_t prvDisplayIPDebugStats( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
	{
	static BaseType_t xIndex = -1;
	extern xExampleDebugStatEntry_t xIPTraceValues[];
	BaseType_t xReturn;

		/* Remove compile time warnings about unused parameters, and check the
		write buffer is not NULL.  NOTE - for simplicity, this example assumes the
		write buffer length is adequate, so does not check for buffer overflows. */
		( void ) pcCommandString;
		( void ) xWriteBufferLen;
		configASSERT( pcWriteBuffer );

		xIndex++;

		if( xIndex < xExampleDebugStatEntries() )
		{
			sprintf( pcWriteBuffer, "%s %d\r\n", ( char * ) xIPTraceValues[ xIndex ].pucDescription, ( int ) xIPTraceValues[ xIndex ].ulData );
			xReturn = pdPASS;
		}
		else
		{
			/* Reset the index for the next time it is called. */
			xIndex = -1;

			/* Ensure nothing remains in the write buffer. */
			pcWriteBuffer[ 0 ] = 0x00;
			xReturn = pdFALSE;
		}

		return xReturn;
	}
	/*-----------------------------------------------------------*/

#endif /* configINCLUDE_DEMO_DEBUG_STATS */

static BaseType_t prvDisplayIPConfig( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
static BaseType_t xIndex = 0;
BaseType_t xReturn;
uint32_t ulAddress;

	/* Remove compile time warnings about unused parameters, and check the
	write buffer is not NULL.  NOTE - for simplicity, this example assumes the
	write buffer length is adequate, so does not check for buffer overflows. */
	( void ) pcCommandString;
	( void ) xWriteBufferLen;
	configASSERT( pcWriteBuffer );

	switch( xIndex )
	{
		case 0 :
			FreeRTOS_GetAddressConfiguration( &ulAddress, NULL, NULL, NULL );
			sprintf( pcWriteBuffer, "\r\nIP address " );
			xReturn = pdTRUE;
			xIndex++;
			break;

		case 1 :
			FreeRTOS_GetAddressConfiguration( NULL, &ulAddress, NULL, NULL );
			sprintf( pcWriteBuffer, "\r\nNet mask " );
			xReturn = pdTRUE;
			xIndex++;
			break;

		case 2 :
			FreeRTOS_GetAddressConfiguration( NULL, NULL, &ulAddress, NULL );
			sprintf( pcWriteBuffer, "\r\nGateway address " );
			xReturn = pdTRUE;
			xIndex++;
			break;

		case 3 :
			FreeRTOS_GetAddressConfiguration( NULL, NULL, NULL, &ulAddress );
			sprintf( pcWriteBuffer, "\r\nDNS server address " );
			xReturn = pdTRUE;
			xIndex++;
			break;

		default :
			ulAddress = 0;
			sprintf( pcWriteBuffer, "\r\n\r\n" );
			xReturn = pdFALSE;
			xIndex = 0;
			break;
	}

	if( ulAddress != 0 )
	{
		FreeRTOS_inet_ntoa( ulAddress, ( &( pcWriteBuffer[ strlen( pcWriteBuffer ) ] ) ) );
	}

	return xReturn;
}
/*-----------------------------------------------------------*/


text:
import { expect } from 'chai';
import deepFreeze from 'deep-freeze';
import eventReducer from './../../src/reducers/eventReducer';
import { FETCH_EVENT } from './../../src/actions/types';

describe('eventReducer', () => {
	it('FETCH_EVENT, ', () => {
		const event = {
			endDate: '26 November, 2016',
			endTime: '20:00',
			guests: ['Joseph', 'Samuel'],
			host: 'Starbucks',
			id: 1,
			location: 'Phoenix, China avenue',
			message: 'We will drink a coffee',
			name: 'Coffee conference',
			startDate: '26 November, 2016',
			startTime: '19:00',
			type: 'Conference'
		};

		const action = {
			type: FETCH_EVENT,
			payload: event
		};

		const stateBefore = {};
		const stateAfter = event;

		deepFreeze(stateBefore);
		deepFreeze(action);

		expect(eventReducer(stateBefore, action)).to.equal(stateAfter);
	});

	it('unknown type', () => {
		const action = {
			type: 'UKNOWN_ACTION',
			payload: 'any value'
		};
		expect(eventReducer({}, action)).to.eql({});
	});
});


text:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Abp.Application.Services.Dto;
using Abp.AspNetCore.Mvc.Authorization;
using IdentityServerWithEfCoreDemo.Authorization;
using IdentityServerWithEfCoreDemo.Controllers;
using IdentityServerWithEfCoreDemo.Users;
using IdentityServerWithEfCoreDemo.Web.Models.Users;

namespace IdentityServerWithEfCoreDemo.Web.Controllers
{
    [AbpMvcAuthorize(PermissionNames.Pages_Users)]
    public class UsersController : IdentityServerWithEfCoreDemoControllerBase
    {
        private readonly IUserAppService _userAppService;

        public UsersController(IUserAppService userAppService)
        {
            _userAppService = userAppService;
        }

        public async Task<ActionResult> Index()
        {
            var roles = (await _userAppService.GetRoles()).Items;
            var model = new UserListViewModel
            {
                Roles = roles
            };
            return View(model);
        }

        public async Task<ActionResult> EditModal(long userId)
        {
            var user = await _userAppService.GetAsync(new EntityDto<long>(userId));
            var roles = (await _userAppService.GetRoles()).Items;
            var model = new EditUserModalViewModel
            {
                User = user,
                Roles = roles
            };
            return PartialView("_EditModal", model);
        }

        public ActionResult ChangePassword()
        {
            return View();
        }
    }
}


text:
class Question < ActiveRecord::Base
  belongs_to :survey
  has_many :answers
  has_many :responses, through: :answers
end


text:
'use strict';

// Module dependencies
var express    = require('express'),
  errorhandler = require('errorhandler'),
  bodyParser   = require('body-parser'),
  session = require('express-session');

module.exports = function (app) {

  // Configure Express
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());
  app.use(session({ secret: 'abzgss123kevinyork' } ));
  app.use(express.query());

  // Setup static public directory
  app.use(express.static(__dirname + '/../public'));
  app.set('view engine', 'jade');
  app.set('views', __dirname + '/../views');

  // Add error handling in dev
  if (!process.env.VCAP_SERVICES) {
    app.use(errorhandler());
  }

};


text:
#ifndef __vParser__
#define __vParser__

/*
		vParser
		Written by J.Yang.	wizardoz@kaist.ac.kr
*/

#include "PTRList.h"
#include "vString.h"
#include "vArray.h"
#include "vToken.h"

typedef struct {
					int		n;
					char	chErr[200];
} ERRMSG;

class vErr : public CPTRList
{
public:
		vErr();
		~vErr();
public:
		void	SetErr(int,vString);
		void	SetErr(int,vString,vString);
		void	SetErr(vString);
		void	SetErr(vString,vString);
		int		nLine;
};

class vParser;
class vTag	: public CPTRList
{
public:
		vTag();
		~vTag();
public:
		// node
		vTag*	Add(vString);
		vTag*	Add(vTag*);
		void	AddI(vTag*,vString);
		vTag*	Search(vString,vTag *pStart=NULL);
		vTag*	Search(int);
		virtual	void RemoveAll();
		void	SetParent(vString s)	{ stParent	= s;}
		BOOL	IsTypeOf(vString);
		int		GetLevel();
		vString	GetFieldName(char *pComma=".");

		// remark node
		void	Set(vString stName,UINT nID,vString stStart,vString stEnd);
		void	Set(vString stName,UINT nID);
		void	Set(vString stName);
		vTag*	New(vString stName);
		vTag*	New(vString stName,UINT nID);
		vTag*	New(vString stName,UINT nID,vString stStart,vString stEnd);
		void	AddScript(vString);

public:
		// script
		void	ScriptProcess();
		void	LineProcess(vString);
		vString	FuncProcess(vString);
		int		IsCommand(vString);

		// io
		void	Save(vString& stExport);

public:
		vString	st;
		vString stParent;

		vArray<vTag*,vTag*>		arrI;	// inherited.
		vArray<vString,vString>	arrSI;	// inherited string

		vArray<vString,vString>	arrArg;	// argument string		ex) arg
		vArray<vTag*,vTag*>		arrA;	// argument type		ex) object link
		vArray<vString,vString>	arrSA;	// argument type string	ex) object, object:vessel
		vString	stScript;

		vTag					*pParent;
		vParser					*pParser;

		// argument
		//void		AddArg(vString stArg,vString stValue,BOOL bParenthesis=TRUE);	//ex when bParen=TRUE, stArg="stValue"
		void		AddArg(char*,char*,BOOL bParenthesis=TRUE);	//ex when bParen=TRUE, stArg="stValue"
		vString		SetArg(char*,char*,BOOL bParenthesis=TRUE);
		vString		GetArg(char*,BOOL bRemoveParenthesis=TRUE);
		int         GetArgi(char*);
		float       GetArgf(char*);
		void		*pObject;
};

class vSS
{
public:
		vSS();
		~vSS();
public:
		BOOL	Push(vString);
		vString	Pop();
		void	Reset();
		vString	Top();
		void	Set(BOOL bRepeat)	{ bRepetitive	= bRepeat; }

protected:
		vArray	<vString,vString>	ss;
		BOOL	bRepetitive;
};

class vParser
{
public:
		vParser();
		~vParser();
public:
		vString	buf;
public:
		// romma io
		vTag*	New(vString);
		void	Clear();
		BOOL	Load(char*);
		BOOL	Save(vString);
		void	Import(vString);
		vString	Export();

		vString	RunScript(vString);

		// parser sentences
		int		GetSize();

protected:
		void	Interpreting();
		void	PreInt();
		void	LinkInt(vTag*);
		void	ScriptInt(vTag*);

public:
		vTag	tags;
		vSS		ss;
		vTag	*pCurrent;
		vTag	*pRoot;
		char	xf,xs;
};

extern vErr	g_Err;

#endif


text:
layout: page
title: Charles Holden's 100th Birthday
date: 2016-05-24
author: Maria Santiago
tags: weekly links, java
status: published
summary: Phasellus ante lectus, rhoncus sed nulla id, scelerisque.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 07/05/2016
  endDate: 07/09/2016
  ctyhocn: CRPPAHX
  groupCode: CH1B
published: true
---
Sed fermentum massa at purus porta venenatis sed feugiat tellus. Fusce sapien dolor, viverra et viverra a, placerat at velit. Mauris commodo blandit orci, vel mattis ligula rutrum et. Nullam id auctor sapien. Nam facilisis augue eget ipsum consectetur efficitur. Cras vel eros elit. Etiam blandit nisi purus.

* Ut ac urna interdum, rutrum nibh a, vulputate quam
* Aliquam vitae mi faucibus, volutpat dolor a, suscipit lacus
* Pellentesque ut turpis in massa elementum finibus non condimentum odio
* Donec a justo venenatis, rutrum diam in, laoreet odio
* Aliquam eu nisl ut nisi imperdiet tempor.

Aliquam consectetur ornare finibus. Nulla vulputate ultrices lorem sed mattis. Donec pellentesque molestie leo nec condimentum. Integer orci nisl, facilisis vitae diam a, rhoncus porttitor urna. Aenean elementum in justo in imperdiet. Sed scelerisque nisl quis tellus tincidunt, a ullamcorper nibh ornare. Quisque sodales venenatis velit sit amet eleifend. Duis dictum justo eget ante finibus, quis fringilla enim varius. Etiam ullamcorper quam sed lorem fringilla blandit. Nulla in efficitur tellus. Nam orci risus, tristique quis convallis ut, scelerisque a neque.


text:
/*
 * enum_stringize.hpp
 *
 *  Created on: 2012-8-4
 *      Author: YH
 */

#ifndef ENUM_STRINGIZE_HPP_
#define ENUM_STRINGIZE_HPP_

#include <matrix/base/debug.hpp>
#include <matrix/base/utility.hpp>

#define ENUM_TO_C_STR enumCstr
#define ENUM_TO_C_STR_FUNC_DEC(EnumName) const char* ENUM_TO_C_STR(EnumName)

#define ENUM_TO_C_STR_FUNC_DEF(EnumName,kArray) \
const char* ENUM_TO_C_STR(EnumName code) { \
    size_t inx = static_cast<size_t>(code); \
    ASSERT(inx < base::sizeofArray(kArray)); \
    return kArray[inx]; \
}struct _EnumToCtsrDef##EnumName##_

#endif /* ENUM_STRINGIZE_HPP_ */


text:
const uuidV4 = require('uuid/v4');
const logger = require('../logger')
const ERRORS = require('./errors')

const logRequest = (req, res, next) => {
  req.id = uuidV4()
  logger.info('>>> Request', {
    id: req.id,
    method: req.method,
    path: req.path,
    query: req.query,
    headers: req.headers
  })
  logger.verbose('>>> Request Body', {
    id: req.id,
    body: req.body
  })
  next()
}

const sendError = (err, res) => {
  logger.error(err)
  const message = (err && err.message) || ERRORS.UNKNOWN_ERROR_MESSAGE
  const status = (err && err.httpStatus) || 500
  res.status(status).setBody({ error: message })
}

const handleErrors = (err, req, res, next) => {
  sendError(err, res)
  next()
}

const sendJson = (req, res, next) => {
  if(!res.statusCode) {
    if(res.body) {
      res.status(req.method==='POST' ? 201 : 200)
    } else {
      sendError(new ERRORS.UNKNOWN_ERROR(), res)
    }
  }
  res.json(res.body)
  next()
}

const logResponse = (req, res, next) => {
  logger.info('<<< Response', {
    id: req.id,
    status: res.statusCode,
    headers: res._headers
  })
  const replacer = res.app.get('json replacer')
  const spaces = res.app.get('json spaces')
  logger.verbose('<<< Response Body', {
    id: req.id,
    body: JSON.parse(JSON.stringify(res.body, replacer, spaces))
  })
  next()
}

module.exports = {
  logRequest,
  sendJson,
  handleErrors,
  logResponse
}


text:
"""Unit tests for NonlinearDeltaCov and LikelihoodResults._get_wald_nonlinear
Created on Sun Mar 01 01:05:35 2015

Author: Josef Perktold
License: BSD-3

"""

import numpy as np
from numpy.testing import assert_allclose, assert_equal
from statsmodels.regression.linear_model import OLS
from statsmodels.stats._delta_method import NonlinearDeltaCov

class TestDeltacovOLS:

    @classmethod
    def setup_class(cls):
        nobs, k_vars = 100, 4
        x = np.random.randn(nobs, k_vars)
        x[:, 0] = 1
        y = x[:, :-1].sum(1) + np.random.randn(nobs)
        cls.res = OLS(y, x).fit()

    def test_method(self):
        # test Results.method is same as calling function/class
        res = self.res
        x = res.model.exog

        def fun(params):
            return np.dot(x, params)**2

        nl = NonlinearDeltaCov(fun, res.params, res.cov_params())
        nlm = res._get_wald_nonlinear(fun)
        # margeff excludes constant, last parameter in this case
        assert_allclose(nlm.se_vectorized(), nlm.se_vectorized(), rtol=1e-12)
        assert_allclose(nlm.predicted(), nlm.predicted(), rtol=1e-12)
        df = res.df_resid
        t1 = nl.summary(use_t=True, df=df)
        t2 = nlm.summary(use_t=True, df=df)
        assert_equal(str(t1), str(t2))

    def test_ttest(self):
        # check with linear function against t_test
        res = self.res
        x = res.model.exog

        def fun(params):
            return np.dot(x, params)

        nl = NonlinearDeltaCov(fun, res.params, res.cov_params())
        predicted = nl.predicted()
        se = nl.se_vectorized()
        assert_allclose(predicted, fun(res.params), rtol=1e-12)
        assert_allclose(se, np.sqrt(np.diag(nl.cov())), rtol=1e-12)

        tt = res.t_test(x, use_t=False)
        assert_allclose(predicted, tt.effect, rtol=1e-12)
        assert_allclose(se, tt.sd, rtol=1e-12)
        assert_allclose(nl.conf_int(), tt.conf_int(), rtol=1e-12)
        t1 = nl.summary()
        t2 = tt.summary()
        # equal because nl.summary uses also ContrastResults
        assert_equal(str(t1), str(t2))

        # use_t = True
        predicted = nl.predicted()
        se = nl.se_vectorized()

        df = res.df_resid
        tt = res.t_test(x, use_t=True)
        assert_allclose(nl.conf_int(use_t=True, df=df), tt.conf_int(),
                        rtol=1e-12)
        t1 = nl.summary(use_t=True, df=df)
        t2 = tt.summary()
        # equal because nl.summary uses also ContrastResults
        assert_equal(str(t1), str(t2))

    def test_diff(self):
        res = self.res
        x = res.model.exog

        def fun(params):
            return np.dot(x, params) - np.dot(x[:, 1:], params[1:])

        nl = NonlinearDeltaCov(fun, res.params, res.cov_params())
        # the following two use broadcasting
        assert_allclose(nl.predicted(), res.params[0], rtol=1e-12)
        assert_allclose(nl.se_vectorized(), res.bse[0], rtol=1e-12)

def test_deltacov_margeff():
    # compare with discrete margins
    import statsmodels.discrete.tests.test_discrete as dt
    tc = dt.TestPoissonNewton()
    tc.setup_class()
    res_poi = tc.res1
    res_poi.model._derivative_exog

    # 2d f doesn't work correctly,
    # se_vectorized and predicted are 2d column vector

    def f(p):
        ex = res_poi.model.exog.mean(0)[None, :]
        fv = res_poi.model._derivative_exog(p, ex)
        return np.squeeze(fv)

    nlp = NonlinearDeltaCov(f, res_poi.params, res_poi.cov_params())

    marg = res_poi.get_margeff(at='mean')
    # margeff excludes constant, last parameter in this case
    assert_allclose(nlp.se_vectorized()[:-1], marg.margeff_se, rtol=1e-13)
    assert_allclose(nlp.predicted()[:-1], marg.margeff, rtol=1e-13)

    nlpm = res_poi._get_wald_nonlinear(f)
    # margeff excludes constant, last parameter in this case
    assert_allclose(nlpm.se_vectorized()[:-1], marg.margeff_se, rtol=1e-13)
    assert_allclose(nlpm.predicted()[:-1], marg.margeff, rtol=1e-13)


text:
package io.spine.server.storage.jdbc.record;

import com.querydsl.core.types.dsl.PathBuilder;
import com.querydsl.sql.dml.SQLInsertClause;
import io.spine.server.entity.storage.EntityRecordWithColumns;
import io.spine.server.storage.jdbc.query.IdColumn;

/**
 * A query that inserts a new {@link EntityRecordWithColumns} into the {@link RecordTable}.
 */
class InsertEntityQuery<I> extends WriteEntityQuery<I, SQLInsertClause> {

    private InsertEntityQuery(Builder<I> builder) {
        super(builder);
    }

    @Override
    protected void addBatch(SQLInsertClause clause) {
        clause.addBatch();
    }

    @Override
    protected void setIdValue(SQLInsertClause clause, IdColumn<I> idColumn, Object normalizedId) {
        PathBuilder<Object> idPath = pathOf(idColumn);
        clause.set(idPath, normalizedId);
    }

    @Override
    protected SQLInsertClause createClause() {
        return factory().insert(table());
    }

    static <I> Builder<I> newBuilder() {
        return new Builder<>();
    }

    static class Builder<I> extends WriteEntityQuery.Builder<Builder<I>,
                                                             InsertEntityQuery,
                                                             I> {

        @Override
        protected InsertEntityQuery doBuild() {
            return new InsertEntityQuery<>(this);
        }

        @Override
        protected Builder<I> getThis() {
            return this;
        }
    }
}


text:
<?php

namespace PFCD\TourismBundle\Repository;

use Doctrine\ORM\EntityRepository;

use PFCD\TourismBundle\Entity\Article;
use PFCD\TourismBundle\Entity\Organization;

class ArticleRepository extends EntityRepository
{

    public function findListFront($locale = null, $organization = null, $country = null, $status_art = null, $status_org = null, $sort = null, $order = null, $limit = null)
    {
        $qb = $this->createQueryBuilder('a');

        $qb->select('a');
        $qb->innerJoin('a.organization', 'o');

        if ($organization !== null)
        {
            $qb->where('a.organization = :organization');
            $qb->setParameter('organization', $organization);
        }

        if ($country !== null)
        {
            $qb->andWhere('o.country = :country');
            $qb->setParameter('country', $country);
        }

        if ($locale !== null)
        {
            $qb->andWhere('a.languages LIKE :locale');
            $qb->setParameter('locale', '%'.$locale.'%');
        }

        $qb->andWhere('a.status IN (:status_art)');
        $qb->setParameter('status_art', $status_art ? $status_art : array(Article::STATUS_ENABLED));

        $qb->andWhere('o.status IN (:status_org)');
        $qb->setParameter('status_org', $status_org ? $status_org : array(Organization::STATUS_ENABLED, Organization::STATUS_LOCKED));

        if ($sort) $qb->orderBy($sort, $order);

        if ($limit) $qb->setMaxResults($limit);

        return $qb->getQuery()->getResult();
    }

    public function findCountriesFront($locale = null)
    {
        $qb = $this->createQueryBuilder('a');

        $qb->select('o.country');
        $qb->innerJoin('a.organization', 'o');

        $qb->where('a.status IN (:status_art)');
        $qb->setParameter('status_art', array(Article::STATUS_ENABLED));

        $qb->andWhere('o.status IN (:status_org)');
        $qb->setParameter('status_org', array(Organization::STATUS_ENABLED, Organization::STATUS_LOCKED));

        if ($locale !== null)
        {
            $qb->andWhere('a.languages LIKE :locale');
            $qb->setParameter('locale', '%'.$locale.'%');
        }

        $qb->groupBy('o.country');

        return $qb->getQuery()->getResult();
    }

}

?>


text:
const { Router } = require('express');
const auth = require('../config/auth');

const router = new Router();

router.get('/login', (req, res) => {
  const token = auth.encodeToken('test');
  res.header('authorization', token).send('ok!');
});

module.exports = router;


text:
(function () {
  'use strict';

  function cdApplyForEventCtrl($scope, $window, $state, $stateParams, $translate, $location, $uibModal,
    alertService, cdEventsService, cdUsersService, cdDojoService, usSpinnerService, dojoUtils, eventUtils) {
    var dojoEvents = $scope.dojoRowIndexExpandedCurr;
    var eventIndex = $scope.tableRowIndexExpandedCurr;
    var accountName;
    var accountTitle;
    $scope.isMember = false;
    $scope.event.isPast = eventUtils.isEventInPast(_.last($scope.event.dates));

    var url = window.location.href;
    if(($stateParams.joinDojo) && url.indexOf('event/')>=1){
      var initUserTypes = cdUsersService.getInitUserTypes( function (userTypes) {
        var userType = _.find(userTypes, JSON.parse($scope.currentUser.initUserType));
        var userObject = {
          userType : userType,
          validate: 'false'
        };

        dojoUtils.requestToJoin(userObject, $scope.event.dojoId);
      });
    }

    if (!_.isEmpty($scope.currentUser)) {
      cdDojoService.dojosForUser($scope.currentUser.id, function (dojos) {
        $scope.isMember = _.find(dojos, function (dojo) {
          return dojo.id === $scope.event.dojoId;
        });
      });
    }

    $scope.cancel = function () {
      if (dojoEvents) {
        $scope.showEventInfo(dojoEvents, eventIndex);
      } else {
        $scope.showEventInfo(eventIndex, $scope.event.id);
      }
    };

    $scope.canBook = function () {
      return eventUtils.canBook($scope.event.public, $scope.dojo.private, $scope.isMember, $scope.dojo.verified);
    };

    $scope.showSessionDetails = function (session) {
      if (!_.isEmpty($scope.currentUser)) {
        if(!$scope.isMember) return alertService.showAlert($translate.instant('Please click the Join Dojo button before applying for events.'));
        var sessionModalInstance = $uibModal.open({
          templateUrl: '/dojos/template/events/session-details',
          controller: 'session-modal-controller',
          size: 'lg',
          resolve: {
            dojoId: function () {
              return $scope.dojoId;
            },
            session: function () {
              return session;
            },
            event: function () {
              return $scope.event;
            },
            applyForModel: function () {
              $scope.applyForModel = {};
              _.each(session.tickets, function (ticket) {
                var applyForData = angular.copy($scope.eventUserSelection[$scope.event.dojoId]);
                _.each(applyForData, function (applyObj) {
                  applyObj.ticketId = ticket.id;
                  applyObj.ticketName = ticket.name;
                  applyObj.ticketType = ticket.type;
                });
                $scope.applyForModel[ticket.id] = applyForData;
              });
              return $scope.applyForModel;
            },
            currentUser: function () {
              return $scope.currentUser;
            },
            referer: function () {
              return 'dojo-event-list';
            }
          }
        });

        sessionModalInstance.result.then(function (result) {
          if(result.ok === false) return alertService.showError($translate.instant(result.why));
          //If event requires ticket approval
          if($scope.event.ticketApproval) {
            alertService.showAlert($translate.instant('Thank You. Your application has been received. You will be notified by email if you are approved for this event.'));
            $state.go('dojo-list');
          } else {
            alertService.showAlert($translate.instant('Thank You. You will receive an email containing your booking confirmation.'));
            $state.go('dojo-list');
          }
        }, null);
      } else {
        $location.path('/register').search({ referer: $location.url(), eventId: session.eventId });
      }
    };
  }

  angular.module('cpZenPlatform')
      .controller('apply-for-event-controller', ['$scope', '$window', '$state', '$stateParams', '$translate', '$location', '$uibModal', 'alertService',
      'cdEventsService', 'cdUsersService', 'cdDojoService', 'usSpinnerService', 'dojoUtils', 'eventUtils', cdApplyForEventCtrl]);
})();


text:
mod error;
#[macro_use]
mod reader;
mod position;
mod record;
pub mod single_line;
mod write;

pub use self::error::*;
pub use self::position::*;
pub use self::reader::*;
pub use self::record::*;
pub use self::write::*;


text:
<!DOCTYPE html>

	<title>Title of the page</title>
	<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css">

li 1

li 2

li 3

li 4

li 5

Task in hand

on Clicking li add class active

use $(this) to get clicked li element

on click li with class dropdown you should avoid adding class li

on click li inside class dropdown you should add li to both li and dropdown

		<button type="button" class="hint-button">Show Hint</button>

To add class, use jquery manipulation .addClass("class-name")

To add and remove class periodically, use jquery manipulation .toggleClass("class-name")


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

namespace Midwhay.Dsl
{
    public class Sentence
    {
        public ActionType Action { get; set; }
        public IEnumerable<RoleObject> Roles { get; set; }

        public Sentence(ActionType action, IEnumerable<RoleObject> roles)
        {
            Action = action;
            Roles = roles;
        }
    }
}


text:
<?php

namespace AppBundle\Service\Payment;

interface PaymentInterface
{
    /**
     * Kur farkı düzenlemesi yapar
     * @return mixed
     */
    public function checkCurrency();

    /**
     * Ödemeyi gerçekleştirir
     * @return mixed
     */
    public function pay();

    /**
     * İlgili bölüme eposta gönderir
     * @return mixed
     */
    public function sendVoucher();
}


text:
<?php echo $model->title; ?>

AniNice :)

            <img src="<?php echo $model->img ?>" width="220" />

            <?php echo $model->text; ?>
            <?php if (isset($model->additional_text)): ?>

<?php echo $model->additional_text; ?>

            <?php endif; ?>

        Социальные комментарии Cackle


text:
from __future__ import division, print_function

from numpy.f2py.f2py2e import main

main()


text:
<bill session="110" type="s" number="3161" updated="2009-01-09T18:27:38-05:00">
	<status><introduced date="1213848000" datetime="2008-06-19"/></status>

	<introduced date="1213848000" datetime="2008-06-19"/>
	<titles>
		<title type="official" as="introduced">A bill to name the Department of Veterans Affairs spinal cord injury center in Tampa, Florida, as the "Michael Bilirakis Department of Veterans Affairs Spinal Cord Injury Center".</title>
	</titles>
	<sponsor id="400621"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1213848000" datetime="2008-06-19"><text>Read twice and referred to the Committee on Veterans' Affairs.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	6/19/2008--Introduced.
Designates the James A. Haley Department of Veterans Affairs Medical Center's spinal cord injury center in Tampa, Florida, as the "Michael Bilirakis Department of Veterans Affairs Spinal Cord Injury Center."

</bill>


text:
package org.kie.workbench.common.dmn.backend.definition.v1_1.dd.org.omg.spec.CMMN_20151109_DI;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;

import org.w3c.dom.Element;

/**
 * Style contains formatting properties that affect the appearance or style of diagram elements, including diagram themselves.
 *

 *
Java class for Style complex type.
 *

 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <complexType name="Style">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="extension" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *       <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
 *       <anyAttribute processContents='lax' namespace='##other'/>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Style", propOrder = {
        "extension"
})
public abstract class Style {

    protected Style.Extension extension;
    @XmlAttribute(name = "id")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    @XmlSchemaType(name = "ID")
    protected String id;
    @XmlAnyAttribute
    private Map<QName, String> otherAttributes = new HashMap<QName, String>();

    /**
     * Gets the value of the extension property.
     * @return possible object is
     * {@link Style.Extension }
     */
    public Style.Extension getExtension() {
        return extension;
    }

    /**
     * Sets the value of the extension property.
     * @param value allowed object is
     * {@link Style.Extension }
     */
    public void setExtension(Style.Extension value) {
        this.extension = value;
    }

    /**
     * Gets the value of the id property.
     * @return possible object is
     * {@link String }
     */
    public String getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     * @param value allowed object is
     * {@link String }
     */
    public void setId(String value) {
        this.id = value;
    }

    /**
     * Gets a map that contains attributes that aren't bound to any typed property on this class.
     *

     *

     * the map is keyed by the name of the attribute and
     * the value is the string value of the attribute.
     *

     * the map returned by this method is live, and you can add new attribute
     * by updating the map directly. Because of this design, there's no setter.
     * @return always non-null
     */
    public Map<QName, String> getOtherAttributes() {
        return otherAttributes;
    }

    /**
     *
Java class for anonymous complex type.
     *

     *
The following schema fragment specifies the expected content contained within this class.
     *

     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
            "any"
    })
    public static class Extension {

        @XmlAnyElement(lax = true)
        protected List<Object> any;

        /**
         * Gets the value of the any property.
         *

         *

         * This accessor method returns a reference to the live list,
         * not a snapshot. Therefore any modification you make to the
         * returned list will be present inside the JAXB object.
         * This is why there is not a set method for the any property.
         *

         *

         * For example, to add a new item, do as follows:
         *

         *    getAny().add(newItem);
         *

         *

         *

         *

         * Objects of the following type(s) are allowed in the list
         * {@link Element }
         * {@link Object }
         */
        public List<Object> getAny() {
            if (any == null) {
                any = new ArrayList<Object>();
            }
            return this.any;
        }
    }
}


text:
import re
import os
from threading import *

import httplib
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer

ROOT_PATH = os.path.dirname(__file__)

PORT = 8097 # not really configurable, must match hardcoded port in tests

class FeedParserTestRequestHandler(SimpleHTTPRequestHandler):
    headers_re = re.compile(r"^Header:\s+([^:]+):(.+)$", re.MULTILINE)

    def send_head(self):
        """Send custom headers defined in test case

        Example:
        <!--
        Header:   Content-type: application/atom+xml
        Header:   X-Foo: bar
        -->
        """
        #path = self.translate_path(self.path)
        path = os.path.abspath(
            os.path.join(
                ROOT_PATH,
                self.path[1:] if self.path.startswith('/') else self.path,
            )
        )
        f = open(path, 'rb')

        headers = dict(self.headers_re.findall(f.read()))
        headers.setdefault('Status', 200)
        self.send_response(int(headers['Status']))
        headers.setdefault('Content-type', self.guess_type(path))
        self.send_header("Content-type", headers['Content-type'])
        f.seek(0)
        self.send_header("Content-Length", str(os.fstat(f.fileno())[6]))
        for k, v in headers.items():
            if k not in ('Status', 'Content-type'):
                self.send_header(k, v)
        self.end_headers()
        return f

    def log_request(self, *args):
        pass

    def do_QUIT(self):
        """send 200 OK response, and set server.stop to True"""
        self.send_response(200)
        self.end_headers()
        self.server.stop = True

class StoppableHttpServer(HTTPServer):
    """http server that reacts to self.stop flag"""

    def serve_forever (self):
        """Handle one request at a time until stopped."""
        self.stop = False
        while not self.stop:
            self.handle_request()

class FeedParserTestServer(Thread):
    """HTTP Server that runs in a thread and handles a predetermined number of requests"""
    TIMEOUT=10

    def __init__(self, cond=None):
        Thread.__init__(self)
        self.ready = False
        self.cond = cond

    def run(self):
        self.cond.acquire()
        timeout=0
        self.httpd = None
        while self.httpd is None:
            try:
                self.httpd = StoppableHttpServer(('', PORT), FeedParserTestRequestHandler)
            except Exception, e:
                import socket,errno,time
                if isinstance(e, socket.error) and errno.errorcode[e.args[0]] == 'EADDRINUSE' and timeout < self.TIMEOUT:
                    timeout+=1
                    time.sleep(1)
                else:
                    self.cond.notifyAll()
                    self.cond.release()
                    self.ready = True
                    raise e
        self.ready = True
        if self.cond:
            self.cond.notifyAll()
            self.cond.release()
        self.httpd.serve_forever()

def stop_server(port):
    """send QUIT request to http server running on localhost:<port>"""
    conn = httplib.HTTPConnection("127.0.0.1:%d" % port)
    conn.request("QUIT", "/")
    conn.getresponse()


text:
export MOD_AUTH_OPENIDC_VERSION="2.3.8"
export CJOSE_VERSION="0.5.1"
autoreconf --force --install
find . -type d -name "autom4te.cache" -prune -exec rm -rf {} \;
./configure


text:
package ch.wsl.box.rest.routes

import akka.actor.ActorSystem
import akka.stream.Materializer
import ch.wsl.box.jdbc.{Connection, UserDatabase}
import ch.wsl.box.rest.logic._
import ch.wsl.box.rest.logic.functions.RuntimeFunction
import ch.wsl.box.rest.metadata.{DataMetadataFactory, FunctionMetadataFactory}
import ch.wsl.box.rest.utils.UserProfile
import ch.wsl.box.services.Services
import io.circe.Json

import scala.concurrent.{ExecutionContext, Future}

object Functions extends Data {

  import ch.wsl.box.jdbc.PostgresProfile.api._
  import ch.wsl.box.shared.utils.JSONUtils._

  override def metadataFactory(implicit up: UserProfile, mat: Materializer, ec: ExecutionContext,services:Services): DataMetadataFactory = new FunctionMetadataFactory()

  def functions = ch.wsl.box.model.boxentities.BoxFunction

  override def data(function: String, params: Json, lang: String)(implicit up: UserProfile,  mat: Materializer, ec: ExecutionContext,system:ActorSystem,services:Services): Future[Option[DataContainer]] = {
    implicit def db:UserDatabase = up.db

    for{
      functionDef <- services.connection.adminDB.run{
        functions.BoxFunctionTable.filter(_.name === function).result
      }.map(_.headOption)
      result <- functionDef match {
        case None => Future.successful(None)
        case Some(func) => {
          val f = RuntimeFunction(func.name,func.function)
          f(RuntimeFunction.context(params),lang).map(dr => Some(DataContainer(dr,func.presenter,func.mode)))
        }
      }
    } yield result
  }.recover{case t:Throwable =>
    t.printStackTrace()
    None
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                           http://www.springframework.org/schema/util
                           http://www.springframework.org/schema/util/spring-util-3.2.xsd
                           http://www.springframework.org/schema/jee
                           http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-3.2.xsd
                           http://www.springframework.org/schema/task
                           http://www.springframework.org/schema/task/spring-task-3.2.xsd">

    <!-- Add certificate revocation sources here -->
    <util:list id="certificateRevocationSources" value-type="dk.nsi.nsp.cra.CertificateRevocationSource">
        <ref bean="systemtestOCES3CertificateRevocationSource"/>
        <ref bean="systemtest8CertificateRevocationSource"/>
        <ref bean="systemtest19CertificateRevocationSource"/>
        <ref bean="systemtest34CertificateRevocationSource"/>
    </util:list>

    <bean id="systemtestOCES3CertificateRevocationSource" class="dk.nsi.nsp.cra.bootstrap.RemoteCertificateRevocationSource">
        <constructor-arg value="http://ca1.cti-gov.dk/oces/issuing/1/cacert/issuing.cer" type="java.lang.String" />
        <constructor-arg value="http://ca1.cti-gov.dk/oces/issuing/1/crl/issuing.crl" type="java.lang.String" />
        <constructor-arg ref="certificateStore"/>
        <constructor-arg ref="certificateResolver"/>
    </bean>

    <bean id="systemtest8CertificateRevocationSource" class="dk.nsi.nsp.cra.bootstrap.RemoteCertificateRevocationSource">
        <constructor-arg value="http://m.aia.systemtest8.trust2408.com/systemtest8-ca.cer" type="java.lang.String" />
        <constructor-arg value="http://crl.systemtest8.trust2408.com/systemtest8.crl" type="java.lang.String" />
        <constructor-arg ref="certificateStore"/>
        <constructor-arg ref="certificateResolver"/>
    </bean>

    <bean id="systemtest19CertificateRevocationSource" class="dk.nsi.nsp.cra.bootstrap.RemoteCertificateRevocationSource">
        <constructor-arg value="http://m.aia.systemtest19.trust2408.com/systemtest19-ca.cer" type="java.lang.String" />
        <constructor-arg value="http://crl.systemtest19.trust2408.com/systemtest19.crl" type="java.lang.String" />
        <constructor-arg ref="certificateStore"/>
        <constructor-arg ref="certificateResolver"/>
    </bean>

    <bean id="systemtest34CertificateRevocationSource" class="dk.nsi.nsp.cra.bootstrap.RemoteCertificateRevocationSource">
        <constructor-arg value="http://m.aia.systemtest34.trust2408.com/systemtest34-ca.cer" type="java.lang.String" />
        <constructor-arg value="http://crl.systemtest34.trust2408.com/systemtest34.crl" type="java.lang.String" />
        <constructor-arg ref="certificateStore"/>
        <constructor-arg ref="certificateResolver"/>
    </bean>
</beans>