text:
<?
/**
 * Session.php
 *
 * The Session class is meant to simplify the task of keeping
 * track of logged in users and also guests.
 *
 * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC)
 * Last Updated: August 19, 2004
 */

include("database.php");
include("mailer.php");
include("form.php");

class Session
{
   var $username;     //Username given on sign-up
   var $userid;       //Random value generated on current login
   var $userlevel;    //The level to which the user pertains
   var $time;         //Time user was last active (page loaded)
   var $logged_in;    //True if user is logged in, false otherwise
   var $userinfo = array();  //The array holding all user info
   var $url;          //The page url current being viewed
   var $referrer;     //Last recorded site page viewed
   /**
    * Note: referrer should really only be considered the actual
    * page referrer in process.php, any other time it may be
    * inaccurate.
    */

   /* Class constructor */
   function Session(){
      $this->time = time();
      $this->startSession();
   }

   /**
    * startSession - Performs all the actions necessary to
    * initialize this session object. Tries to determine if the
    * the user has logged in already, and sets the variables
    * accordingly. Also takes advantage of this page load to
    * update the active visitors tables.
    */
   function startSession(){
      global $database;  //The database connection
      session_start();   //Tell PHP to start the session

      /* Determine if user is logged in */
      $this->logged_in = $this->checkLogin();
      /**
       * Set guest value to users not logged in, and update
       * active guests table accordingly.
       */
      if(!$this->logged_in){
         $this->username = $_SESSION['username'] = GUEST_NAME;
         $this->userlevel = GUEST_LEVEL;
         $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
      }
      /* Update users last active timestamp */
      else{
         $database->addActiveUser($this->username, $this->time);
      }

      /* Remove inactive visitors from database */
      $database->removeInactiveUsers();
      $database->removeInactiveGuests();

      /* Set referrer page */
      if(isset($_SESSION['url'])){
         $this->referrer = $_SESSION['url'];
      }else{
         $this->referrer = "/";
      }
      /* Set current url */

      $qs = "?";
      foreach($_GET as $k => $v) {
        $qs .= $k . "=" . $v."&";
      }
      $qs = substr($qs, 0, -1);

      $this->url = $_SESSION['url'] = $_SERVER['PHP_SELF'].$qs;

   }

   /**
    * checkLogin - Checks if the user has already previously
    * logged in, and a session with the user has already been
    * established. Also checks to see if user has been remembered.
    * If so, the database is queried to make sure of the user's
    * authenticity. Returns true if the user has logged in.
    */
   function checkLogin(){
      global $database;  //The database connection
      /* Check if user has been remembered */
      if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
         $this->username = $_SESSION['username'] = $_COOKIE['cookname'];
         $this->userid   = $_SESSION['userid']   = $_COOKIE['cookid'];
      }

      /* Username and userid have been set and not guest */
      if(isset($_SESSION['username']) && isset($_SESSION['userid']) &&
         $_SESSION['username'] != GUEST_NAME){
         /* Confirm that username and userid are valid */
         if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0){
            /* Variables are incorrect, user not logged in */
            unset($_SESSION['username']);
            unset($_SESSION['userid']);
            return false;
         }

         /* User is logged in, set class variables */
         $this->userinfo  = $database->getUserInfo($_SESSION['username']);
         $this->username  = $this->userinfo['username'];
         $this->userid    = $this->userinfo['userid'];
         $this->userlevel = $this->userinfo['userlevel'];
         return true;
      }
      /* User not logged in */
      else{
         return false;
      }
   }

   /**
    * login - The user has submitted his username and password
    * through the login form, this function checks the authenticity
    * of that information in the database and creates the session.
    * Effectively logging in the user if all goes well.
    */
   function login($subuser, $subpass, $subremember){
      global $database, $form;  //The database and form object

      /* Username error checking */
      $field = "user";  //Use field name for username
      if(!$subuser || strlen($subuser = trim($subuser)) == 0){
         $form->setError($field, "* Username not entered");
      }
      else{
         /* Check if username is not alphanumeric */
         if(!eregi("^([0-9a-z])*$", $subuser)){
            // $form->setError($field, "* Username not alphanumeric");
         }
      }

      /* Password error checking */
      $field = "pass";  //Use field name for password
      if(!$subpass){
         $form->setError($field, "* Password not entered");
      }

      /* Return if form errors exist */
      if($form->num_errors > 0){
         return false;
      }

      /* Checks that username is in database and password is correct */
      $subuser = stripslashes($subuser);
      $result = $database->confirmUserPass($subuser, md5($subpass));

      /* Check error codes */
      if($result == 1){
         $field = "user";
         $form->setError($field, "* Username not found");
      }
      else if($result == 2){
         $field = "pass";
         $form->setError($field, "* Invalid password");
      }

      /* Return if form errors exist */
      if($form->num_errors > 0){
         return false;
      }

      /* Username and password correct, register session variables */
      $this->userinfo  = $database->getUserInfo($subuser);
      $this->username  = $_SESSION['username'] = $this->userinfo['username'];
      $this->userid    = $_SESSION['userid']   = $this->generateRandID();
      $this->userlevel = $this->userinfo['userlevel'];

      /* Insert userid into database and update active users table */
      $database->updateUserField($this->username, "userid", $this->userid);
      $database->addActiveUser($this->username, $this->time);
      $database->removeActiveGuest($_SERVER['REMOTE_ADDR']);

      /**
       * This is the cool part: the user has requested that we remember that
       * he's logged in, so we set two cookies. One to hold his username,
       * and one to hold his random value userid. It expires by the time
       * specified in constants.php. Now, next time he comes to our site, we will
       * log him in automatically, but only if he didn't log out before he left.
       */
      if($subremember){
         setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
         setcookie("cookid",   $this->userid,   time()+COOKIE_EXPIRE, COOKIE_PATH);
      }

      /* Login completed successfully */
      return true;
   }

   /**
    * logout - Gets called when the user wants to be logged out of the
    * website. It deletes any cookies that were stored on the users
    * computer as a result of him wanting to be remembered, and also
    * unsets session variables and demotes his user level to guest.
    */
   function logout(){
      global $database;  //The database connection
      /**
       * Delete cookies - the time must be in the past,
       * so just negate what you added when creating the
       * cookie.
       */
      if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
         setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
         setcookie("cookid",   "", time()-COOKIE_EXPIRE, COOKIE_PATH);
      }

      /* Unset PHP session variables */
      unset($_SESSION['username']);
      unset($_SESSION['userid']);

      /* Reflect fact that user has logged out */
      $this->logged_in = false;

      /**
       * Remove from active users table and add to
       * active guests tables.
       */
      $database->removeActiveUser($this->username);
      $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);

      /* Set user level to guest */
      $this->username  = GUEST_NAME;
      $this->userlevel = GUEST_LEVEL;
   }

   /**
    * register - Gets called when the user has just submitted the
    * registration form. Determines if there were any errors with
    * the entry fields, if so, it records the errors and returns
    * 1. If no errors were found, it registers the new user and
    * returns 0. Returns 2 if registration failed.
    */
   function register($subfirst, $sublast, $subpass, $subemail, $lnk){
      global $database, $form, $mailer;  //The database, form and mailer object

      /* Username error checking */
      $field = "first";  //Use field name for username

      if(!$subfirst || strlen($subfirst = trim($subfirst)) == 0){
         $form->setError($field, "* First name not entered");
      }
      else{
         /* Spruce up username, check length */
         $subfirst = stripslashes($subfirst);
         if(!eregi("^([0-9a-z])+$", $subfirst)){
            $form->setError($field, "* First name not alphanumeric");
         }
         /* Check if username is reserved */
         else if(strcasecmp($subfirst, GUEST_NAME) == 0){
            $form->setError($field, "* First name reserved word");
         }
         /* Check if First name is already in use */
         else if($database->usernameTaken($subfirst)){
            $form->setError($field, "* First name already in use");
         }
         /* Check if First name is banned */
         else if($database->usernameBanned($subfirst)){
            $form->setError($field, "* First name banned");
         }
      }

      $field = "last";  //Use field name for username
      if(!$sublast || strlen($sublast = trim($sublast)) == 0){
         $form->setError($field, "* Last name not entered");
      }
      else{
         /* Spruce up username, check length */
         $sublast = stripslashes($sublast);
         if(!eregi("^([0-9a-z])+$", $sublast)){
            $form->setError($field, "* Last name not alphanumeric");
         }
         /* Check if username is reserved */
         else if(strcasecmp($sublast, GUEST_NAME) == 0){
            $form->setError($field, "* Last name reserved word");
         }
         /* Check if Last name is already in use */
         else if($database->usernameTaken($sublast)){
            $form->setError($field, "* Last name already in use");
         }
         /* Check if Last name is banned */
         else if($database->usernameBanned($sublast)){
            $form->setError($field, "* Last name banned");
         }
      }

      /* Password error checking */
      $field = "pass";  //Use field name for password
      if(!$subpass){
         $form->setError($field, "* Password not entered");
      }
      else{
         /* Spruce up password and check length*/
         $subpass = stripslashes($subpass);
         if(strlen($subpass) < 4){
            $form->setError($field, "* Password too short");
         }
         /* Check if password is not alphanumeric */
         else if(!eregi("^([0-9a-z])+$", ($subpass = trim($subpass)))){
            // $form->setError($field, "* Password not alphanumeric");
         }
         /**
          * Note: I trimmed the password only after I checked the length
          * because if you fill the password field up with spaces
          * it looks like a lot more characters than 4, so it looks
          * kind of stupid to report "password too short".
          */
      }

      /* Email error checking */
      $field = "email";  //Use field name for email
      if(!$subemail || strlen($subemail = trim($subemail)) == 0){
         $form->setError($field, "* Email not entered");
      }
      else{
         /* Check if valid email address */
         $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
                 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
                 ."\.([a-z]{2,}){1}$";
         if(!eregi($regex,$subemail)){
            $form->setError($field, "* Email invalid");
         }
         $subemail = stripslashes($subemail);
      }

      /* Errors exist, have user correct them */
      if($form->num_errors > 0){
         return 1;  //Errors with form
      }
      /* No errors, add the new account to the */
      else{
        echo $lnk;
         if($database->addNewUser($subfirst, $sublast, md5($subpass), $subemail)){
            if(EMAIL_WELCOME){
               $mailer->sendWelcome($subfirst,$subemail,$subpass);
            }
            if ($lnk > 0) {
              // echo $database->recent_insert;
             $database->copyFromLink($lnk,$database->recent_insert);
            }
            return 0;  //New user added succesfully
         }else{
            return 2;  //Registration attempt failed
         }
      }
   }

   /**
    * editAccount - Attempts to edit the user's account information
    * including the password, which it first makes sure is correct
    * if entered, if so and the new password is in the right
    * format, the change is made. All other fields are changed
    * automatically.
    */
   function editAccount($subcurpass, $subnewpass, $subemail){
      global $database, $form;  //The database and form object
      /* New password entered */
      if($subnewpass){
         /* Current Password error checking */
         $field = "curpass";  //Use field name for current password
         if(!$subcurpass){
            $form->setError($field, "* Current Password not entered");
         }
         else{
            /* Check if password too short or is not alphanumeric */
            $subcurpass = stripslashes($subcurpass);
            if(strlen($subcurpass) < 4 ||
               !eregi("^([0-9a-z])+$", ($subcurpass = trim($subcurpass)))){
               $form->setError($field, "* Current Password incorrect");
            }
            /* Password entered is incorrect */
            if($database->confirmUserPass($this->username,md5($subcurpass)) != 0){
               $form->setError($field, "* Current Password incorrect");
            }
         }

         /* New Password error checking */
         $field = "newpass";  //Use field name for new password
         /* Spruce up password and check length*/
         $subpass = stripslashes($subnewpass);
         if(strlen($subnewpass) < 4){
            $form->setError($field, "* New Password too short");
         }
         /* Check if password is not alphanumeric */
         else if(!eregi("^([0-9a-z])+$", ($subnewpass = trim($subnewpass)))){
            // $form->setError($field, "* New Password not alphanumeric");
         }
      }
      /* Change password attempted */
      else if($subcurpass){
         /* New Password error reporting */
         $field = "newpass";  //Use field name for new password
         $form->setError($field, "* New Password not entered");
      }

      /* Email error checking */
      $field = "email";  //Use field name for email
      if($subemail && strlen($subemail = trim($subemail)) > 0){
         /* Check if valid email address */
         $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
                 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
                 ."\.([a-z]{2,}){1}$";
         if(!eregi($regex,$subemail)){
            $form->setError($field, "* Email invalid");
         }
         $subemail = stripslashes($subemail);
      }

      /* Errors exist, have user correct them */
      if($form->num_errors > 0){
         return false;  //Errors with form
      }

      /* Update password since there were no errors */
      if($subcurpass && $subnewpass){
         $database->updateUserField($this->username,"password",md5($subnewpass));
      }

      /* Change Email */
      if($subemail){
         $database->updateUserField($this->username,"email",$subemail);
      }

      /* Success! */
      return true;
   }

   /**
    * isAdmin - Returns true if currently logged in user is
    * an administrator, false otherwise.
    */
   function isAdmin(){
      return ($this->userlevel == ADMIN_LEVEL ||
              $this->username  == ADMIN_NAME);
   }

   //////////////////////////////////////////////////////////////
   // linkInfo - Gets info on the account that will be linked  //
   //////////////////////////////////////////////////////////////
   function linkInfo($id){
      global $database;
      $id = mysql_real_escape_string($id);
      return $database->getUserInfoById($id);
   }

   /**
    * generateRandID - Generates a string made up of randomized
    * letters (lower and upper case) and digits and returns
    * the md5 hash of it to be used as a userid.
    */
   function generateRandID(){
      return md5($this->generateRandStr(16));
   }

   /**
    * generateRandStr - Generates a string made up of randomized
    * letters (lower and upper case) and digits, the length
    * is a specified parameter.
    */
   function generateRandStr($length){
      $randstr = "";
      for($i=0; $i<$length; $i++){
         $randnum = mt_rand(0,61);
         if($randnum < 10){
            $randstr .= chr($randnum+48);
         }else if($randnum < 36){
            $randstr .= chr($randnum+55);
         }else{
            $randstr .= chr($randnum+61);
         }
      }
      return $randstr;
   }
};

/**
 * Initialize session object - This must be initialized before
 * the form object because the form uses session variables,
 * which cannot be accessed unless the session has started.
 */
$session = new Session;
/* Initialize form object */
$form = new Form;


text:
namespace FLIGHT {
class Sprite {
    std::weak_ptr<Texture> m_texture;
    std::weak_ptr<Model> m_model;
    glm::vec3 m_position;
    glm::vec3 m_rotation;
    glm::vec3 m_scale;
    std::weak_ptr<Material> m_material;

public:
    Sprite();
    void SetTexture(std::shared_ptr<Texture> texture);
    void SetModel(std::shared_ptr<Model> model);
    std::shared_ptr<Model> GetModel() const;
    void Display(const glm::mat4 & parentContext, ShaderProgram & shader) const;
    void SetPosition(const glm::vec3 & position);
    void SetRotation(const glm::vec3 & vec);
    const glm::vec3 & GetRotation() const;
    void SetScale(const glm::vec3 & scale);
    void SetMaterial(std::shared_ptr<Material> material);
    AABB GetAABB();
    OBB GetOBB();
};
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef PRETTY_PRINTER
#define PRETTY_PRINTER

#include "jrt.h"
#ifdef JERRY_ENABLE_PRETTY_PRINTER
#include "bytecode-data.h"
#include "vm.h"
#include "scopes-tree.h"

void pp_op_meta (const bytecode_data_header_t *, vm_instr_counter_t, op_meta, bool);
#endif // JERRY_ENABLE_PRETTY_PRINTER

#endif // PRETTY_PRINTER


text:
@interface Constants : NSObject
- (nonnull instancetype)initWithSomeInteger:(int32_t)someInteger
                                 someString:(nonnull NSString *)someString;
+ (nonnull instancetype)constantsWithSomeInteger:(int32_t)someInteger
                                      someString:(nonnull NSString *)someString;

@property (nonatomic, readonly) int32_t someInteger;

@property (nonatomic, readonly, nonnull) NSString * someString;

@end

extern BOOL const ConstantsBoolConstant;
extern int8_t const ConstantsI8Constant;
extern int16_t const ConstantsI16Constant;
extern int32_t const ConstantsI32Constant;
extern int64_t const ConstantsI64Constant;
extern float const ConstantsF32Constant;
extern double const ConstantsF64Constant;
extern NSString * __nonnull const ConstantsStringConstant;
extern NSNumber * __nullable const ConstantsOptionalIntegerConstant;
extern Constants * __nonnull const ConstantsObjectConstant;


text:
package com.azure.spring.cloud.autoconfigure.eventhubs;

import com.azure.data.appconfiguration.ConfigurationClientBuilder;
import com.azure.messaging.eventhubs.EventHubClientBuilder;
import com.azure.messaging.eventhubs.EventHubConsumerAsyncClient;
import com.azure.messaging.eventhubs.EventHubConsumerClient;
import com.azure.spring.cloud.autoconfigure.TestBuilderCustomizer;
import com.azure.spring.cloud.autoconfigure.context.AzureContextUtils;
import com.azure.spring.cloud.service.implementation.eventhubs.factory.EventHubClientBuilderFactory;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;

import static com.azure.spring.cloud.autoconfigure.eventhubs.EventHubsTestUtils.CONNECTION_STRING_FORMAT;
import static org.assertj.core.api.Assertions.assertThat;

class AzureEventHubsConsumerClientConfigurationTests {

    private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
        .withConfiguration(AutoConfigurations.of(AzureEventHubsConsumerClientConfiguration.class));

    @Test
    void noEventHubNameProvidedShouldNotConfigure() {
        contextRunner.run(context -> assertThat(context).doesNotHaveBean(AzureEventHubsConsumerClientConfiguration.class));
    }

    @Test
    void eventHubNameAndConsumerGroupProvidedShouldConfigure() {
        contextRunner
            .withPropertyValues(
                "spring.cloud.azure.eventhubs.event-hub-name=test-eventhub",
                "spring.cloud.azure.eventhubs.consumer.consumer-group=test-consumer-group"
            )
            .run(context -> {
                assertThat(context).hasSingleBean(AzureEventHubsConsumerClientConfiguration.class);
                assertThat(context).doesNotHaveBean(AzureEventHubsConsumerClientConfiguration.SharedConsumerConnectionConfiguration.class);
                assertThat(context).doesNotHaveBean(AzureEventHubsConsumerClientConfiguration.DedicatedConsumerConnectionConfiguration.class);
            });

        contextRunner
            .withPropertyValues(
                "spring.cloud.azure.eventhubs.consumer.event-hub-name=test-eventhub",
                "spring.cloud.azure.eventhubs.consumer.consumer-group=test-consumer-group"
            )
            .run(context -> {
                assertThat(context).hasSingleBean(AzureEventHubsConsumerClientConfiguration.class);
                assertThat(context).doesNotHaveBean(AzureEventHubsConsumerClientConfiguration.SharedConsumerConnectionConfiguration.class);
                assertThat(context).doesNotHaveBean(AzureEventHubsConsumerClientConfiguration.DedicatedConsumerConnectionConfiguration.class);
            });
    }

    @Test
    void withGlobalEventHubConnectionSetShouldConfigureShared() {
        String namespace = "test-namespace";
        String eventHubName = "test-eventhub";
        String consumerGroupName = "test-consumer-group";

        EventHubClientBuilder clientBuilder = new EventHubClientBuilder()
            .consumerGroup(consumerGroupName)
            .connectionString(String.format(CONNECTION_STRING_FORMAT, namespace), eventHubName);

        contextRunner
            .withPropertyValues(
                "spring.cloud.azure.eventhubs.namespace=" + namespace,
                "spring.cloud.azure.eventhubs.event-hub-name=" + eventHubName,
                "spring.cloud.azure.eventhubs.consumer.consumer-group=" + consumerGroupName
            )
            .withUserConfiguration(AzureEventHubsPropertiesTestConfiguration.class)
            .withBean(EventHubClientBuilder.class, () -> clientBuilder)
            .run(
                context -> {
                    assertThat(context).doesNotHaveBean(AzureEventHubsConsumerClientConfiguration.DedicatedConsumerConnectionConfiguration.class);
                    assertThat(context).hasSingleBean(AzureEventHubsConsumerClientConfiguration.SharedConsumerConnectionConfiguration.class);
                    assertThat(context).hasSingleBean(EventHubConsumerAsyncClient.class);
                    assertThat(context).hasSingleBean(EventHubConsumerClient.class);
                }
            );
    }

    @Test
    void withDedicatedEvenHubConnectionSetShouldConfigureDedicated() {
        contextRunner
            .withPropertyValues(
                "spring.cloud.azure.eventhubs.consumer.namespace=test-namespace",
                "spring.cloud.azure.eventhubs.consumer.event-hub-name=test-event-hub",
                "spring.cloud.azure.eventhubs.consumer.consumer-group=test-consumer-group",
                "spring.cloud.azure.eventhubs.namespace=test-namespace"
            )
            .withUserConfiguration(AzureEventHubsPropertiesTestConfiguration.class)
            .run(
                context -> {
                    assertThat(context).doesNotHaveBean(AzureEventHubsConsumerClientConfiguration.SharedConsumerConnectionConfiguration.class);
                    assertThat(context).hasSingleBean(AzureEventHubsConsumerClientConfiguration.DedicatedConsumerConnectionConfiguration.class);
                    assertThat(context).hasSingleBean(EventHubClientBuilderFactory.class);
                    assertThat(context).hasSingleBean(EventHubClientBuilder.class);
                    assertThat(context).hasSingleBean(EventHubConsumerAsyncClient.class);
                    assertThat(context).hasSingleBean(EventHubConsumerClient.class);
                    assertThat(context).hasBean(AzureContextUtils.EVENT_HUB_CONSUMER_CLIENT_BUILDER_FACTORY_BEAN_NAME);
                    assertThat(context).hasBean(AzureContextUtils.EVENT_HUB_CONSUMER_CLIENT_BUILDER_BEAN_NAME);
                }
            );
    }

    @Test
    void customizerShouldBeCalled() {
        EventHubBuilderCustomizer customizer = new EventHubBuilderCustomizer();
        this.contextRunner
            .withPropertyValues(
                "spring.cloud.azure.eventhubs.consumer.namespace=test-namespace",
                "spring.cloud.azure.eventhubs.consumer.event-hub-name=test-event-hub",
                "spring.cloud.azure.eventhubs.consumer.consumer-group=test-consumer-group",
                "spring.cloud.azure.eventhubs.namespace=test-namespace"
            )
            .withUserConfiguration(AzureEventHubsPropertiesTestConfiguration.class)
            .withBean("customizer1", EventHubBuilderCustomizer.class, () -> customizer)
            .withBean("customizer2", EventHubBuilderCustomizer.class, () -> customizer)
            .run(context -> assertThat(customizer.getCustomizedTimes()).isEqualTo(2));
    }

    @Test
    void otherCustomizerShouldNotBeCalled() {
        EventHubBuilderCustomizer customizer = new EventHubBuilderCustomizer();
        OtherBuilderCustomizer otherBuilderCustomizer = new OtherBuilderCustomizer();
        this.contextRunner
            .withPropertyValues(
                "spring.cloud.azure.eventhubs.consumer.namespace=test-namespace",
                "spring.cloud.azure.eventhubs.consumer.event-hub-name=test-event-hub",
                "spring.cloud.azure.eventhubs.consumer.consumer-group=test-consumer-group",
                "spring.cloud.azure.eventhubs.namespace=test-namespace"
            )
            .withUserConfiguration(AzureEventHubsPropertiesTestConfiguration.class)
            .withBean("customizer1", EventHubBuilderCustomizer.class, () -> customizer)
            .withBean("customizer2", EventHubBuilderCustomizer.class, () -> customizer)
            .withBean("customizer3", OtherBuilderCustomizer.class, () -> otherBuilderCustomizer)
            .run(context -> {
                assertThat(customizer.getCustomizedTimes()).isEqualTo(2);
                assertThat(otherBuilderCustomizer.getCustomizedTimes()).isEqualTo(0);
            });
    }

    private static class EventHubBuilderCustomizer extends TestBuilderCustomizer<EventHubClientBuilder> {

    }

    private static class OtherBuilderCustomizer extends TestBuilderCustomizer<ConfigurationClientBuilder> {

    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/half_overlay"
        android:drawable="@drawable/milk"
        android:width="80dp"
        android:height="120dp"
        />

</layer-list>


text:
#ifndef MYTH_MEM_BARRIER_H_
#define MYTH_MEM_BARRIER_H_

#include "myth_config.h"

//A macro for supressing optimization
#define myth_loop_barrier() asm volatile("":::"memory")

//MEMO:Architecture-Dependent Code
#if defined MYTH_ARCH_i386 || defined MYTH_ARCH_amd64

#ifdef MYTH_BARRIER_FENCES
//Memory barriers by x86 fence instructions
//Guarantees successive reads to be executed after this
#define myth_rbarrier() asm volatile("lfence\n":::"memory")
//Guarantees former writes to be executed before this
#define myth_wbarrier() asm volatile("sfence\n":::"memory")
//rbarrier+wbarrier
#define myth_rwbarrier() asm volatile("mfence\n":::"memory")
#elif defined MYTH_BARRIER_CILK
//Memory barriers used by Cilk
//Guarantees successive reads to be executed after this
#define myth_rbarrier() {\
	int x=0,y;\
	asm volatile("xchgl %0,%1":"=r"(x):"m"(y),"0"(x):"memory");\
}
//Guarantees former writes to be executed before this
#define myth_wbarrier() asm volatile("":::"memory")
//rbarrier+wbarrier
#define myth_rwbarrier() myth_rbarrier();
#elif defined MYTH_BARRIER_CILK_WEAK
//R->R orderings are guaranteed by x86[_64] architecture
#define myth_rbarrier() asm volatile("":::"memory")
//W->W orderings are guaranteed by x86[_64] architecture
#define myth_wbarrier() asm volatile("":::"memory")
//R->W orderings are NOT guaranteed. Need to serialize by atomic or fence insns
#define myth_rwbarrier() {\
	int x=0,y;\
	asm volatile("xchgl %0,%1":"=r"(x):"m"(y),"0"(x):"memory");\
}
//#define myth_rwbarrier() asm volatile("mfence":::"memory")
#else
#error "Choose memory barrier"
#endif

#elif defined MYTH_ARCH_sparc
//Default
#define myth_rbarrier() __sync_synchronize()
#define myth_wbarrier() __sync_synchronize()
#define myth_rwbarrier() __sync_synchronize()

#else
#warning "Architecture-dependent memory barrier is not defined, substituted by GCC extension"

//Default
#define myth_rbarrier() __sync_synchronize()
#define myth_wbarrier() __sync_synchronize()
#define myth_rwbarrier() __sync_synchronize()

#endif

#endif /* MYTH_BARRIER_H_ */


text:
package se.snylt.witch.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.SOURCE)
public @interface BindWhen {

    public final static String ALWAYS = "always";

    public final static String NOT_SAME = "notSame";

    public final static String NOT_EQUALS = "notEquals";

    public final static String ONCE = "once";

    String value();
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- Appenders -->
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p: %c - %m%n" />
        </layout>
    </appender>

    <!-- Application Loggers -->
    <logger name="test.example.mvcparameters">
        <level value="info" />
    </logger>

   <!-- Spring Loggers -->
    <logger name="org.springframework">
        <level value="debug" />
    </logger>

    <logger name="org.springframework.core">
        <level value="info" />
    </logger>

    <logger name="org.springframework.beans">
        <level value="info" />
    </logger>

    <logger name="org.springframework.mvc">
        <level value="debug" />
    </logger>

    <logger name="org.springframework.context">
        <level value="info" />
    </logger>

    <logger name="org.springframework.web">
        <level value="info" />
    </logger>

    <logger name="org.springframework.http.converter">
        <level value="debug" />
    </logger>

    <!-- Root Logger -->
    <root>
        <priority value="warn" />
        <appender-ref ref="console" />
    </root>

</log4j:configuration>


text:
package eu.timepit.refined

import eu.timepit.refined.api.{Max, Refined}
import eu.timepit.refined.boolean._
import eu.timepit.refined.numeric._
import eu.timepit.refined.types.numeric._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import shapeless.tag.@@

class MaxSpec extends Properties("Max") {

  property("Max[Int Refined Less[1]]") = secure {
    Max[Int Refined Less[W.`1`.T]].max.value ?= 0
  }

  property("Max[Int Refined Less[0]]") = secure {
    Max[Int Refined Less[W.`0`.T]].max.value ?= -1
  }

  property("Max[Long Refined Less[5]]") = secure {
    Max[Long Refined Less[W.`5`.T]].max.value ?= 4L
  }

  property("Max[Float Refined Less[5]]") = secure {
    Max[Float Refined Less[W.`5`.T]].max.value ?= 4.9999995f
  }

  property("Max[Byte Refined Greater[0]]") = secure {
    Max[Byte Refined Greater[W.`0`.T]].max.value ?= Byte.MaxValue
  }

  property("Max[Short Refined Greater[0]]") = secure {
    Max[Short Refined Greater[W.`0`.T]].max.value ?= Short.MaxValue
  }

  property("Max[Int Refined Greater[0]]") = secure {
    Max[Int Refined Greater[W.`0`.T]].max.value ?= Int.MaxValue
  }

  property("Max[Long Refined Greater[0]]") = secure {
    Max[Long Refined Greater[W.`0`.T]].max.value ?= Long.MaxValue
  }

  property("Max[Float Refined Greater[0]]") = secure {
    Max[Float Refined Greater[W.`0`.T]].max.value ?= Float.MaxValue
  }

  property("Max[Double Refined Greater[0]]") = secure {
    Max[Double Refined Greater[W.`0`.T]].max.value ?= Double.MaxValue
  }

  property("Max[Int Refined NonNegative]") = secure {
    Max[Int Refined NonNegative].max.value ?= Int.MaxValue
  }

  property("Max[Int Refined NonPositive]") = secure {
    Max[Int Refined NonPositive].max.value ?= 0
  }

  property("Max[Float Refined NonPositive]") = secure {
    Max[Float Refined NonPositive].max.value ?= 0f
  }

  property("Max[Double Refined NonPositive]") = secure {
    Max[Double Refined NonPositive].max.value ?= 0d
  }

  property("Max[Int Refined Not[Greater[-5]]]") = secure {
    Max[Int Refined Not[Greater[W.`-5`.T]]].max.value ?= -5
  }

  property("Max[Int Refined Interval.Open[1, 4]]") = secure {
    Max[Int Refined Interval.Open[W.`1`.T, W.`4`.T]].max.value ?= 3
  }

  property("Max[Double Refined Interval.Open[1, 4]]") = secure {
    Max[Double Refined Interval.Open[W.`1`.T, W.`4`.T]].max.value ?= 3.9999999999999996
  }

  property("Max[Int Refined Interval.Closed[-20, 10]]") = secure {
    Max[Int Refined Interval.Closed[W.`-20`.T, W.`10`.T]].max.value ?= 10
  }

  property("Max[Int @@ Interval.Closed[-20, 10]]") = secure {
    Max[Int @@ Interval.Closed[W.`-20`.T, W.`10`.T]].max.asInstanceOf[Int] ?= 10
  }

  property("Max[Double Refined Interval.Closed[-20d, 10.99991d]]") = secure {
    Max[Double Refined Interval.Closed[W.`-20d`.T, W.`10.99991d`.T]].max.value ?= 10.99991d
  }

  property("Max[Char Refined Interval.Closed['A', 'Z']]") = secure {
    Max[Char Refined Interval.Closed[W.`'A'`.T, W.`'Z'`.T]].max.value ?= 'Z'
  }

  property("Max[Int Refined Even]") = secure {
    Max[Int Refined Even].max.value ?= 2147483646
  }

  property("Max[Int Refined Divisible[5]]") = secure {
    Max[Int Refined Divisible[W.`5`.T]].max.value ?= 2147483645
  }

  property("Max[Int Refined (Negative And Even)]") = secure {
    Max[Int Refined (Negative And Even)].max.value ?= -2
  }

  property("NegLong.MaxValue") = secure {
    NegLong.MaxValue ?= NegLong.unsafeFrom(-1)
  }

  property("PosFloat.MaxValue") = secure {
    PosFloat.MaxValue ?= PosFloat.unsafeFrom(Float.MaxValue)
  }
}


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

namespace dgMicMute.Enumerations
{
    /// <summary>
    /// The ERole enumeration defines constants that indicate the role that the system has assigned to an audio endpoint device.
    /// </summary>
    /// <remarks>
    /// Source: http://msdn.microsoft.com/en-us/library/windows/desktop/dd370842(v=vs.85).aspx
    /// </remarks>
    public enum ERole
    {
        EConsole = 0,
        EMultimedia = 1,
        ECommunications = 2,
        ERoleEnumCount = 3
    }
}


text:
function results = parallel_imbalanced_gaussian
if nargin < 2, cases = 100; end
if nargin < 1, nMax = 5000; end

parfor i = 1:10
    results(i) = imbalanced_gaussian(nMax, cases);
end

save('imablanced_data', 'results');
end


text:
<?php

/**#@+ @ignore */
require_once("ID3/Frame/AbstractLink.php");
/**#@-*/

/**
 * The <i>Copyright/Legal information</i> frame is a URL pointing at a webpage
 * where the terms of use and ownership of the file is described.
 *
 * @package    php-reader
 * @subpackage ID3
 * @author     Sven Vollbehr <svollbehr@gmail.com>
 * @copyright  Copyright (c) 2008 The PHP Reader Project Workgroup
 * @license    http://code.google.com/p/php-reader/wiki/License New BSD License
 * @version    $Rev: 65 $
 */
final class ID3_Frame_WCOP extends ID3_Frame_AbstractLink {}


text:
@interface S2MAppDelegate ()

@property (strong, nonatomic) S2MHockeyHandler* hockeyHandler;

@end

@implementation S2MAppDelegate

static BOOL isRunningTests(void) __attribute__((const));

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (isRunningTests()) {
        return YES;
    }
    NSLog(@"appDelegate didFinishLaunchingWithOptions!");

    self.hockeyHandler = [[S2MHockeyHandler alloc] init];
    [self.hockeyHandler setCrashManagerdDidFinishBlock:^(NSError * error) {
        NSLog(@"CrashManagerdDidFinishBlock. Error %@", error);
    }];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[StartViewController alloc] init]];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    if (isRunningTests()) {
        return;
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if (isRunningTests()) {
        return;
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    if (isRunningTests()) {
        return;
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if (isRunningTests()) {
        return;
    }
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    if (isRunningTests()) {
        return;
    }
}

#pragma mark - Testing

static BOOL isRunningTests(void)
{
    NSDictionary* environment = [[NSProcessInfo processInfo] environment];
    NSString* injectBundle = environment[@"XCInjectBundle"];
    return [[injectBundle pathExtension] isEqualToString:@"octest"] || [[injectBundle pathExtension] isEqualToString:@"xctest"];
}

#pragma mark HockeyApp

- (void)testCrash
{
    [self.hockeyHandler makeApplicationCrash];
}
@end


text:
namespace Samples
{
    using System;

    public sealed class Sample
    {
    }
}


text:
> Create an array with values that are present in the first input array but not additional ones

## Install

```
$ npm install array-differ
```

## Usage

```js
import arrayDiffer from 'array-differ';

arrayDiffer([2, 3, 4], [3, 50]);
//=> [2, 4]
```

## API

### arrayDiffer(input, ...values)

Returns a new array.

#### input

Type: `unknown[]`

#### values

Type: `unknown[]`

Arrays of values to exclude.

## FAQ

### What is the time complexity of the algorithm?

[Read here.](https://github.com/sindresorhus/array-differ/issues/10)

---

		Get professional support for this package with a Tidelift subscription

		Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.


text:
<?php

namespace Drupal\Tests\Component\FileCache;

use Drupal\Component\FileCache\FileCacheBackendInterface;

/**
 * Allows to cache data based on file modification dates in a static cache.
 */
class StaticFileCacheBackend implements FileCacheBackendInterface {

  /**
   * Internal static cache.
   *
   * @var array
   */
  protected static $cache = [];

  /**
   * Bin used for storing the data in the static cache.
   *
   * @var string
   */
  protected $bin;

  /**
   * Constructs a PHP Storage FileCache backend.
   *
   * @param array $configuration
   *   (optional) Configuration used to configure this object.
   */
  public function __construct($configuration) {
    $this->bin = $configuration['bin'] ?? 'file_cache';
  }

  /**
   * {@inheritdoc}
   */
  public function fetch(array $cids) {
    $result = [];
    foreach ($cids as $cid) {
      if (isset(static::$cache[$this->bin][$cid])) {
        $result[$cid] = static::$cache[$this->bin][$cid];
      }
    }

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function store($cid, $data) {
    static::$cache[$this->bin][$cid] = $data;
  }

  /**
   * {@inheritdoc}
   */
  public function delete($cid) {
    unset(static::$cache[$this->bin][$cid]);
  }

  /**
   * Allows tests to reset the static cache to avoid side effects.
   */
  public static function reset() {
    static::$cache = [];
  }

}


text:
import './chunk-1fafdf15.js';
import './helpers.js';
import './chunk-f134e057.js';
import './chunk-bf1769fd.js';
import './chunk-5f7c65f9.js';
import { r as registerComponent, u as use } from './chunk-cca88db8.js';
import './chunk-f1431ce0.js';
import './chunk-8cb48812.js';
import './chunk-14fab2e4.js';
import './chunk-42f463e6.js';
import './chunk-edc3b90d.js';
import './chunk-5407ef79.js';
import './chunk-51e7cfbe.js';
import { T as Timepicker } from './chunk-ecbcd84b.js';
export { T as BTimepicker } from './chunk-ecbcd84b.js';

var Plugin = {
  install: function install(Vue) {
    registerComponent(Vue, Timepicker);
  }
};
use(Plugin);

export default Plugin;


text:
+++
Talk_date = ""
Talk_start_time = ""
Talk_end_time = ""
Title = "Squads mais eficientes com DevOps"
Type = "talk"
Speakers = ["valdomiro-bilharvas"]
Slides = ""

+++

Depois de alguns anos trabalhando com times em formatos de Squads com a metodologia Devops adquirimos experiencias e muito aprendizado, o processo transformou nossos times e nossa forma de pensar em um fluxo de desenvolvimento eficaz para cada cenário ou seja, clientes/projetos/skills e tecnologias.


text:
<?php

namespace Uci\Bundle\BaseDatosBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class EligeTipoType extends AbstractType {

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('tipoRespuesta', 'entity', array('class' => 'UciBaseDatosBundle:TipoRespuesta', 'required' => true, 'mapped' => false, 'expanded' => true, 'multiple' => false));
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => null
        ));
    }

    /**
     * @return string
     */
    public function getName() {
        return 'EligeTipoType';
    }

}


text: export * from 'rxjs-compat/operator/concatMap';


text:
from coinone.common import base_url, error_code
import base64
import simplejson as json
import hashlib
import hmac
import httplib2
import time
import logging

log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(format=log_format, level=logging.DEBUG)
logger = logging.getLogger(__name__)

class Account:
    def __init__(self, token, key):
        self.token = token
        self.key = key
        self.default_payload = {"access_token": self.token}

    def info(self):
        return self._post('account/user_info')

    def balance(self):
        return self._post('account/balance')

    def daily_balance(self):
        return self._post('account/daily_balance')

    def deposit_address(self):
        return self._post('account/deposit_address')

    def virtual_account(self):
        return self._post('account/virtual_account')

    def orders(self, currency='btc'):
        payload = {**self.default_payload, 'currency': currency}
        return self._post('order/limit_orders', payload)['limitOrders']

    def complete_orders(self, currency='btc'):
        payload = {**self.default_payload, 'currency': currency}
        return self._post('order/complete_orders', payload)['completeOrders']

    def cancel(self, currency='btc',
               order_id=None, price=None, qty=None, is_ask=None, **kwargs):
        """
        cancel an order.
        If all params are empty, it will cancel all orders.
        """
        if all(param is None for param in (order_id, price, qty, is_ask)):
            err = 'This API is no longer supported.'
            logger.error('Failed to cancel all: %s' % err)
            raise Exception(err)
        elif 'type' in kwargs and 'orderId' in kwargs:
            payload = {**self.default_payload,
                       'price': price,
                       'qty': qty,
                       'is_ask': 1 if kwargs['type'] == 'ask' else 0,
                       'order_id': kwargs['orderId'],
                       'currency': currency}
            url = 'order/cancel'
        else:
            payload = {**self.default_payload,
                       'order_id': order_id,
                       'price': price,
                       'qty': qty,
                       'is_ask': is_ask,
                       'currency': currency}
            url = 'order/cancel'
        logger.debug('Cancel: %s' % payload)
        return self._post(url, payload)

    def buy(self, currency='btc', price=None, qty=None, **kwargs):
        """
        make a buy order.
        if quantity is not given, it will make a market price order.
        """
        if qty is None:
            err = 'This API is no longer supported.'
            logger.error('Failed to market buy: %s' % err)
            raise Exception(err)
        else:
            payload = {**self.default_payload,
                       'price': price,
                       'qty': qty,
                       'currency': currency}
            url = 'order/limit_buy'
        logger.debug('Buy: %s' % payload)
        return self._post(url, payload)

    def sell(self, currency='btc', qty=None, price=None, **kwargs):
        """
        make a sell order.
        if price is not given, it will make a market price order.
        """
        if price is None:
            err = 'This API is no longer supported.'
            logger.error('Failed to market sell: %s' % err)
            raise Exception(err)
        else:
            payload = {**self.default_payload,
                       'price': price,
                       'qty': qty,
                       'currency': currency}
            url = 'order/limit_sell'
        logger.debug('Sell: %s' % payload)
        return self._post(url, payload)

    def _post(self, url, payload=None):
        def encode_payload(payload):
            payload[u'nonce'] = int(time.time()*1000)
            ret = json.dumps(payload).encode()
            return base64.b64encode(ret)

        def get_signature(encoded_payload, secret_key):
            signature = hmac.new(
                secret_key.upper().encode(), encoded_payload, hashlib.sha512)
            return signature.hexdigest()

        def get_response(url, payload, key):
            encoded_payload = encode_payload(payload)
            headers = {
                'Content-type': 'application/json',
                'X-COINONE-PAYLOAD': encoded_payload,
                'X-COINONE-SIGNATURE': get_signature(encoded_payload, key)
            }
            http = httplib2.Http()
            response, content = http.request(
                url, 'POST', headers=headers, body=encoded_payload)
            return content

        if payload is None:
            payload = self.default_payload
        res = get_response(base_url+url, payload, self.key)
        res = json.loads(res)
        if res['result'] == 'error':
            err = res['errorCode']
            raise Exception(int(err), error_code[err])
        return res


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                tools:context="br.com.grapp.atividades.SecundarioActivity"
                android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Informe um número"/>

    <EditText
        android:id="@+id/edxNumero"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Confirmar"
        android:onClick="confirmarClick"/>

</LinearLayout>


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

#include "components/keyed_service/core/dependency_graph.h"

#include <stddef.h>

#include <algorithm>
#include <deque>
#include <iterator>

#include "base/strings/string_piece.h"

namespace {

// Escapes |id| to be a valid ID in the DOT format [1]. This is implemented as
// enclosing the string in quotation marks, and escaping any quotation marks
// found with backslashes.
// [1] http://www.graphviz.org/content/dot-language
std::string Escape(base::StringPiece id) {
  std::string result = "\"";
  result.reserve(id.size() + 2);  // +2 for the enclosing quotes.
  size_t after_last_quot = 0;
  size_t next_quot = id.find('"');
  while (next_quot != base::StringPiece::npos) {
    result.append(id.data() + after_last_quot, next_quot - after_last_quot);
    result.append("\"");
    after_last_quot = next_quot + 1;
    next_quot = id.find('"', after_last_quot);
  }
  result.append(id.data() + after_last_quot, id.size() - after_last_quot);
  result.append("\"");
  return result;
}

}  // namespace

DependencyGraph::DependencyGraph() {}

DependencyGraph::~DependencyGraph() {}

void DependencyGraph::AddNode(DependencyNode* node) {
  all_nodes_.push_back(node);
  construction_order_.clear();
}

void DependencyGraph::RemoveNode(DependencyNode* node) {
  all_nodes_.erase(std::remove(all_nodes_.begin(), all_nodes_.end(), node),
                   all_nodes_.end());

  // Remove all dependency edges that contain this node.
  EdgeMap::iterator it = edges_.begin();
  while (it != edges_.end()) {
    EdgeMap::iterator temp = it;
    ++it;

    if (temp->first == node || temp->second == node)
      edges_.erase(temp);
  }

  construction_order_.clear();
}

void DependencyGraph::AddEdge(DependencyNode* depended,
                              DependencyNode* dependee) {
  edges_.insert(std::make_pair(depended, dependee));
  construction_order_.clear();
}

bool DependencyGraph::GetConstructionOrder(
    std::vector<DependencyNode*>* order) {
  if (construction_order_.empty() && !BuildConstructionOrder())
    return false;

  *order = construction_order_;
  return true;
}

bool DependencyGraph::GetDestructionOrder(std::vector<DependencyNode*>* order) {
  if (construction_order_.empty() && !BuildConstructionOrder())
    return false;

  *order = construction_order_;

  // Destroy nodes in reverse order.
  std::reverse(order->begin(), order->end());

  return true;
}

bool DependencyGraph::BuildConstructionOrder() {
  // Step 1: Build a set of nodes with no incoming edges.
  std::deque<DependencyNode*> queue;
  std::copy(all_nodes_.begin(), all_nodes_.end(), std::back_inserter(queue));

  std::deque<DependencyNode*>::iterator queue_end = queue.end();
  for (EdgeMap::const_iterator it = edges_.begin(); it != edges_.end(); ++it) {
    queue_end = std::remove(queue.begin(), queue_end, it->second);
  }
  queue.erase(queue_end, queue.end());

  // Step 2: Do the Kahn topological sort.
  std::vector<DependencyNode*> output;
  EdgeMap edges(edges_);
  while (!queue.empty()) {
    DependencyNode* node = queue.front();
    queue.pop_front();
    output.push_back(node);

    std::pair<EdgeMap::iterator, EdgeMap::iterator> range =
        edges.equal_range(node);
    EdgeMap::iterator it = range.first;
    while (it != range.second) {
      DependencyNode* dest = it->second;
      EdgeMap::iterator temp = it;
      it++;
      edges.erase(temp);

      bool has_incoming_edges = false;
      for (EdgeMap::iterator jt = edges.begin(); jt != edges.end(); ++jt) {
        if (jt->second == dest) {
          has_incoming_edges = true;
          break;
        }
      }

      if (!has_incoming_edges)
        queue.push_back(dest);
    }
  }

  if (!edges.empty()) {
    // Dependency graph has a cycle.
    return false;
  }

  construction_order_ = output;
  return true;
}

std::string DependencyGraph::DumpAsGraphviz(
    const std::string& toplevel_name,
    const base::Callback<std::string(DependencyNode*)>& node_name_callback)
    const {
  std::string result("digraph {\n");
  std::string escaped_toplevel_name = Escape(toplevel_name);

  // Make a copy of all nodes.
  std::deque<DependencyNode*> nodes;
  std::copy(all_nodes_.begin(), all_nodes_.end(), std::back_inserter(nodes));

  // State all dependencies and remove |second| so we don't generate an
  // implicit dependency on the top level node.
  std::deque<DependencyNode*>::iterator nodes_end(nodes.end());
  result.append("  /* Dependencies */\n");
  for (EdgeMap::const_iterator it = edges_.begin(); it != edges_.end(); ++it) {
    result.append("  ");
    result.append(Escape(node_name_callback.Run(it->second)));
    result.append(" -> ");
    result.append(Escape(node_name_callback.Run(it->first)));
    result.append(";\n");

    nodes_end = std::remove(nodes.begin(), nodes_end, it->second);
  }
  nodes.erase(nodes_end, nodes.end());

  // Every node that doesn't depend on anything else will implicitly depend on
  // the top level node.
  result.append("\n  /* Toplevel attachments */\n");
  for (std::deque<DependencyNode*>::const_iterator it = nodes.begin();
       it != nodes.end();
       ++it) {
    result.append("  ");
    result.append(Escape(node_name_callback.Run(*it)));
    result.append(" -> ");
    result.append(escaped_toplevel_name);
    result.append(";\n");
  }

  result.append("\n  /* Toplevel node */\n");
  result.append("  ");
  result.append(escaped_toplevel_name);
  result.append(" [shape=box];\n");

  result.append("}\n");
  return result;
}


text:
from __future__ import unicode_literals

import json

from django import forms
from django.template.loader import render_to_string
from django.utils import six
from django.utils.translation import ugettext_lazy as _

from .conf import settings
from . import app_settings

class GeopositionWidget(forms.MultiWidget):
    template_name = 'geoposition/widgets/geoposition.html'

    def __init__(self, attrs=None):
        widgets = (
            forms.TextInput(),
            forms.TextInput(),
        )
        super(GeopositionWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if isinstance(value, six.text_type):
            return value.rsplit(',')
        if value:
            return [value.latitude, value.longitude]
        return [None, None]

    def get_config(self):
        return {
            'map_widget_height': settings.MAP_WIDGET_HEIGHT or 500,
            'map_options': json.dumps(settings.MAP_OPTIONS),
            'marker_options': json.dumps(settings.MARKER_OPTIONS),
        }

    def get_context(self, name, value, attrs):
        # Django 1.11 and up
        context = super(GeopositionWidget, self).get_context(name, value, attrs)
        context['latitude'] = {
            'widget': context['widget']['subwidgets'][0],
            'label': _("latitude"),
        }
        context['longitude'] = {
            'widget': context['widget']['subwidgets'][1],
            'label': _("longitude"),
        }
        context['config'] = self.get_config()
        return context

    def format_output(self, rendered_widgets):
        # Django 1.10 and down
        return render_to_string('geoposition/widgets/geoposition.html', {
            'latitude': {
                'html': rendered_widgets[0],
                'label': _("latitude"),
            },
            'longitude': {
                'html': rendered_widgets[1],
                'label': _("longitude"),
            },
            'config': self.get_config(),
        })

    class Media:
        js = (
            '//maps.google.com/maps/api/js?key=%s' % settings.GOOGLE_MAPS_API_KEY,
            'geoposition/geoposition.js',
        )
        if app_settings.GEOPOSITION_GMAP_URL_AUTOLOAD:
            if app_settings.GEOPOSITION_GMAP_URL:
                js += (
                    app_settings.GEOPOSITION_GMAP_URL
                )
        css = {
            'all': ('geoposition/geoposition.css',)
        }


text:
<refentry xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          id="qanda.title.properties">
<refmeta>
<refentrytitle>qanda.title.properties</refentrytitle>
<refmiscinfo role="type">attribute set</refmiscinfo>
</refmeta>
<refnamediv>
<refname>qanda.title.properties</refname>
<refpurpose>Properties for qanda set titles</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment id='qanda.title.properties.frag'>
<xsl:attribute-set name="qanda.title.properties">
  <xsl:attribute name="font-family">
    <xsl:value-of select="$title.font.family"/>
  </xsl:attribute>
  <xsl:attribute name="font-weight">bold</xsl:attribute>
  <!-- font size is calculated dynamically by qanda.heading template -->
  <xsl:attribute name="keep-with-next.within-column">always</xsl:attribute>
  <xsl:attribute name="space-before.minimum">0.8em</xsl:attribute>
  <xsl:attribute name="space-before.optimum">1.0em</xsl:attribute>
  <xsl:attribute name="space-before.maximum">1.2em</xsl:attribute>
</xsl:attribute-set>
</src:fragment>
</refsynopsisdiv>

<refsect1><title>Description</title>

<para>The properties common to all qanda set titles.</para>

</refsect1>
</refentry>


text:
#ifndef {{ model.name }}_EXT_COST
#define {{ model.name }}_EXT_COST

#ifdef __cplusplus
extern "C" {
#endif

{% if cost.cost_ext_fun_type == "casadi" %}
{% if cost.cost_type == "EXTERNAL" %}
int {{ model.name }}_cost_ext_cost_fun(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem);
int {{ model.name }}_cost_ext_cost_fun_work(int *, int *, int *, int *);
const int *{{ model.name }}_cost_ext_cost_fun_sparsity_in(int);
const int *{{ model.name }}_cost_ext_cost_fun_sparsity_out(int);
int {{ model.name }}_cost_ext_cost_fun_n_in(void);
int {{ model.name }}_cost_ext_cost_fun_n_out(void);

int {{ model.name }}_cost_ext_cost_fun_jac_hess(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem);
int {{ model.name }}_cost_ext_cost_fun_jac_hess_work(int *, int *, int *, int *);
const int *{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_in(int);
const int *{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_out(int);
int {{ model.name }}_cost_ext_cost_fun_jac_hess_n_in(void);
int {{ model.name }}_cost_ext_cost_fun_jac_hess_n_out(void);

int {{ model.name }}_cost_ext_cost_fun_jac(const real_t** arg, real_t** res, int* iw, real_t* w, void *mem);
int {{ model.name }}_cost_ext_cost_fun_jac_work(int *, int *, int *, int *);
const int *{{ model.name }}_cost_ext_cost_fun_jac_sparsity_in(int);
const int *{{ model.name }}_cost_ext_cost_fun_jac_sparsity_out(int);
int {{ model.name }}_cost_ext_cost_fun_jac_n_in(void);
int {{ model.name }}_cost_ext_cost_fun_jac_n_out(void);
{% endif %}

{% else %}
int {{ cost.cost_function_ext_cost }}(void **, void **, void *);
{% endif %}

#ifdef __cplusplus
} /* extern "C" */
#endif

#endif  // {{ model.name }}_EXT_COST


text:
var shell = require('shelljs');
var chalk = require('chalk');
const packageJson = require('../package.json');

shell.echo(chalk.grey(`${packageJson.name}@${packageJson.version} was successfully published.`));


text:
import getHashData from '../utils/get-hash-data';
import setHashData from '../utils/set-hash-data';
import { ranges, properties, defaults } from '../utils/default-options';
import customizeCSS from '../css/customize.css';

const customizeGalaxy = () => {
  // set globals
  const hashData = getHashData(window.location.hash);
  const settings = defaults;

  // ------------------------------------------------------------
  // -- Register event dispatcher -------------------------------
  // ------------------------------------------------------------
  const onReady = () => {
    window.dispatchEvent(new CustomEvent('on-customize-ready'));
  };

  // ------------------------------------------------------------
  // -- Make canvas visible and dispatch ready event ------------
  // ------------------------------------------------------------
  const finish = () => {
    const galaxy = document.getElementById('galaxy');
    galaxy.style.display = 'block';
    galaxy.style.height = '100vh';
    galaxy.style.width = '100vh';
    onReady();
  };

  // ------------------------------------------------------------
  // -- Set default values if none set --------------------------
  // ------------------------------------------------------------
  const setDefaults = () => {
    for (let i = 0; i < properties.length; i++) {
      if (!hashData[properties[i]] || isNaN(+hashData[properties[i]])) {
        hashData[properties[i]] = settings[properties[i]];
      } else {
        settings[properties[i]] = hashData[properties[i]];
      }
    }
    setHashData(hashData);
  };

  // ------------------------------------------------------------
  // -- Create a slider -----------------------------------------
  // ------------------------------------------------------------
  const createSlider = (property) => {
    let slider = `<div class="text title">${ranges[property].title}</div>`;
    for (let i = 0; i < ranges[property].subtitles.length; i++) {
      slider += `<div class="text subtitle">${ranges[property].subtitles[i]}</div>`;
    }
    slider += `<div class="text default">default: ${ranges[property].default}</div>`
            + `<input id="${property}-slider" class="slider" type="range" `
            +   `list="${property}-tickmarks" min="${ranges[property].min}" `
            +   `max="${ranges[property].max}" value="${settings[property]}" `
            +   `step="${ranges[property].step}">`
            + `<datalist id="${property}-tickmarks">`;
    let limit = (
      (ranges[property].max - ranges[property].min)
      / ranges[property].step
    ) + 1;
    limit = limit > 13 ? 13 : limit;
    const chunk = (ranges[property].max - ranges[property].min) / (limit - 1);
    for (let i = 0; i < limit; i++) {
      slider += `<option value="${ranges[property].min + (chunk * i)}">`;
    }
    slider += '</datalist>'
            + `<div id="${property}-display" class="text display">`
            +   `${settings[property]}</div>`
            + '

';
    return slider;
  };

  // ------------------------------------------------------------
  // -- Create customization interface --------------------------
  // ------------------------------------------------------------
  const createInterface = (customizeDiv) => {
    document.getElementsByTagName('html')[0].style.background = '#333';
    let customizePage = `<style type="text/css">${customizeCSS}</style>`
      + '
Customize
'
      + '

';
    for (let i = 0; i < properties.length; i++) {
      customizePage += createSlider(properties[i]);
    }
    customizePage += '<button type="submit" id="done">Done</button>';
    customizeDiv.innerHTML = customizePage;
  };

  // ------------------------------------------------------------
  // -- Handle sliders ------------------------------------------
  // ------------------------------------------------------------
  const handleSliders = () => {
    for (let i = 0; i < properties.length; i++) {
      const display = document.getElementById(`${properties[i]}-display`);
      const slider = document.getElementById(`${properties[i]}-slider`);
      slider.onmousemove = (e) => {
        display.innerText = e.target.value;
      };
      slider.onchange = (e) => {
        display.innerText = e.target.value;
        settings[properties[i]] = e.target.value;
        hashData[properties[i]] = e.target.value;
        setHashData(hashData);
      };
    }
  };

  // ------------------------------------------------------------
  // -- Handle done button --------------------------------------
  // ------------------------------------------------------------
  const handleDone = (customizeDiv, cb) => {
    const done = document.getElementById('done');
    done.onclick = () => {
      hashData.customized = 1;
      setHashData(hashData);
      customizeDiv.innerHTML = '';
      document.getElementsByTagName('html')[0].style.background = '';

      cb();
    };
  };

  // ------------------------------------------------------------
  // -- Controller Script ---------------------------------------
  // ------------------------------------------------------------
  const controller = () => {
    setDefaults();

    if (!hashData.customized) {
      // if not customized yet
      const customizeDiv = document.getElementById('customize');
      createInterface(customizeDiv);
      handleSliders();
      handleDone(customizeDiv, finish);
    } else {
      // if already customized
      finish();
    }
  };

  // run controller
  controller();
};

export default customizeGalaxy;