text:
import { extend } from '../utils'
import { validateStyles } from '../validator'

let warned = false

function getWarnText (prop) {
  return `[Vue Rneder] "${prop}" is not a standard CSS property,`
    + 'it may not support very well on weex vue render.'
}

function normalize (styles) {
  const realStyle = {}
  for (const key in styles) {
    let value = styles[key]

    // TODO: add more reliable check
    if (typeof value === 'number') {
      value += 'px'
    }

    // warn for unsupported properties
    switch (key) {
      case 'lines':
      case 'item-color':
      case 'itemColor':
      case 'item-selected-color':
      case 'itemSelectedColor':
      case 'item-size':
      case 'itemSize': console.warn(getWarnText(key)); break
    }

    realStyle[key] = value
  }
  return realStyle
}

function getStyleMap (component) {
  if (component && component.$vnode && component.$vnode.context) {
    const $options = component.$vnode.context.$options
    if ($options && $options.style) {
      if (!warned) {
        warned = true
        console.error('[Invalid Bundle Format] This bundle format is '
          + 'generated for Android and iOS platform, '
          + 'please use "vue-loader" to compile the ".vue" file on the web.')
      }
      return $options.style
    }
  }
}

function getStaticClass (component) {
  if (component && component.$vnode && component.$vnode.data) {
    const data = component.$vnode.data
    return [].concat(data.staticClass, data.class)
  }
}

function getComponentStyle (context) {
  const styleMap = getStyleMap(context)
  const staticClass = getStaticClass(context)

  if (styleMap && Array.isArray(staticClass)) {
    const styles = staticClass.reduce((res, name) => {
      return extend(res, styleMap[name])
    }, {})

    return normalize(styles)
  }
}

function mergeStyles (context) {
  const styles = getComponentStyle(context)
  if (context.$el && styles) {
    validateStyles(context.$options && context.$options._componentTag, styles)
    for (const key in styles) {
      context.$el.style[key] = styles[key]
    }
  }
}

export default {
  mounted () {
    mergeStyles(this)
  },
  beforeUpdate () {
    mergeStyles(this)
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Aisel\UserBundle\EventListener;

use Aisel\UserBundle\Entity\User;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * Class UserPersistenceListener
 *
 * @author Ivan Proskuryakov <volgodark@gmail.com>
 */
class UserPersistenceListener
{

    /**
     * @var EncoderFactory
     */
    protected $encoder;

    /**
     * Constructor
     * @param EncoderFactory $encoder
     */
    public function __construct(EncoderFactory $encoder)
    {
        $this->encoder = $encoder;
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function preUpdate(LifeCycleEventArgs $args)
    {
        $this->setPassword($args);
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function prePersist(LifeCycleEventArgs $args)
    {
        $this->setPassword($args);
        $this->setRole($args);
    }

    /**
     * setPassword
     *
     * @param LifecycleEventArgs $args
     */
    public function setPassword(LifeCycleEventArgs $args)
    {
        /** @var User $object */
        $object = $args->getEntity();

        if ($object instanceof AdvancedUserInterface) {

            $salt = md5(uniqid(null, true));
            $object->setSalt($salt);

            $encoder = $this->encoder->getEncoder($object);
            $encodedPassword = $encoder->encodePassword(
                $object->getPlainPassword(),
                $object->getSalt()
            );

            $object->setPassword($encodedPassword);
            $object->setLastLogin(new \DateTime(date('Y-m-d H:i:s')));
        }
    }

    /**
     * setRole
     *
     * @param LifecycleEventArgs $args
     */
    public function setRole(LifeCycleEventArgs $args)
    {
        /** @var User $object */
        $object = $args->getEntity();

        if ($object instanceof AdvancedUserInterface) {
            $object->setRoles(User::ROLE_USER);
        }
    }

}


text:
using System;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;
using Flurl;
using Microsoft.Extensions.Logging;
using RapidCore.Network;
using Skarp.HubSpotClient.Contact.Dto;
using Skarp.HubSpotClient.Contact.Interfaces;
using Skarp.HubSpotClient.Core;
using Skarp.HubSpotClient.Core.Interfaces;
using Skarp.HubSpotClient.Core.Requests;

namespace Skarp.HubSpotClient.Contact
{
    public class HubSpotContactClient : HubSpotBaseClient, IHubSpotContactClient
    {
        /// <summary>
        /// Mockable and container ready constructor
        /// </summary>
        /// <param name="httpClient"></param>
        /// <param name="logger"></param>
        /// <param name="serializer"></param>
        /// <param name="hubSpotBaseUrl"></param>
        /// <param name="apiKeyOrToken"></param>
        public HubSpotContactClient(
            IRapidHttpClient httpClient,
            ILogger<HubSpotContactClient> logger,
            RequestSerializer serializer,
            string hubSpotBaseUrl,
            string apiKeyOrToken
        ) : base(httpClient, logger, serializer, hubSpotBaseUrl, apiKeyOrToken)
        {
        }

        /// <summary>
        /// Create a new instance of the HubSpotContactClient with default dependencies
        /// </summary>
        /// <remarks>
        /// This constructor creates a HubSpotContactClient using "real" dependencies that will send requests
        /// via the network - if you wish to have support for functional tests and mocking use the "eager" constructor
        /// that takes in all underlying dependecies
        /// </remarks>
        /// <param name="apiKeyOrToken">Your API token</param>
        public HubSpotContactClient(string apiKeyOrToken)
        : base(
              new RealRapidHttpClient(new HttpClient()),
              NoopLoggerFactory.Get(),
              new RequestSerializer(new RequestDataConverter(NoopLoggerFactory.Get<RequestDataConverter>())),
              "https://api.hubapi.com",
              apiKeyOrToken
        )
        { }

        /// <summary>
        /// Creates the contact entity asynchronously.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<T> CreateAsync<T>(IContactHubSpotEntity entity) where T : IHubSpotEntity, new()
        {
            Logger.LogDebug("Contact CreateAsync");
            var path = PathResolver(entity, HubSpotAction.Create);
            var data = await PostAsync<T>(path, entity);
            return data;
        }

        /// <summary>
        /// Creates or updates the contact entity asynchronously.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<T> CreateOrUpdateAsync<T>(IContactHubSpotEntity entity) where T : IHubSpotEntity, new()
        {
            Logger.LogDebug("Contact CreateOrUpdateAsync");
            var path = PathResolver(entity, HubSpotAction.CreateOrUpdate)
                .Replace(":contactemail:", WebUtility.UrlEncode(entity.Email));
            var data = await PostAsync<T>(path, entity);
            return data;
        }

        /// <summary>
        /// Return a single contact by id from hubspot
        /// </summary>
        /// <param name="contactId"></param>
        /// <param name="opts">Options for enabling/disabling history and specifying properties</param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public async Task<T> GetByIdAsync<T>(long contactId, ContactGetRequestOptions opts = null) where T : IHubSpotEntity, new()
        {
            Logger.LogDebug("Contact Get by id ");
            var path = PathResolver(new ContactHubSpotEntity(), HubSpotAction.Get)
                .Replace(":contactId:", contactId.ToString());

            path = AddGetRequestOptions(path, opts);

            var data = await GetAsync<T>(path);
            return data;
        }

        /// <summary>
        /// Get a contact by email address
        /// </summary>
        /// <param name="email"></param>
        /// <param name="opts">Options for enabling/disabling history and specifying properties</param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public async Task<T> GetByEmailAsync<T>(string email, ContactGetRequestOptions opts = null) where T : IHubSpotEntity, new()
        {
            Logger.LogDebug("Contact get by email");
            var path = PathResolver(new ContactHubSpotEntity(), HubSpotAction.GetByEmail)
                .Replace(":contactEmail:", email);

            path = AddGetRequestOptions(path, opts);

            var data = await GetAsync<T>(path);
            return data;
        }

        private string AddGetRequestOptions(string path, ContactGetRequestOptions opts = null)
        {
            var newPath = path;

            opts ??= new ContactGetRequestOptions();
            if (opts.PropertiesToInclude.Any())
            {
                newPath = newPath.SetQueryParam("property", opts.PropertiesToInclude);
            }
            if (!opts.IncludeHistory)
            {
                newPath = newPath.SetQueryParam("propertyMode", "value_only");
            }
            newPath = newPath.SetQueryParam("formSubmissionMode", opts.FormSubmissionMode.ToString().ToLowerInvariant());
            newPath = newPath.SetQueryParam("showListMemberships", opts.IncludeListMemberships.ToString().ToLowerInvariant());

            return newPath;
        }

        /// <summary>
        /// List contacts
        /// </summary>
        /// <param name="opts">Request options - use for pagination</param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public async Task<T> ListAsync<T>(ContactListRequestOptions opts = null) where T : IHubSpotEntity, new()
        {
            Logger.LogDebug("Contact ListAsync");
            if (opts == null)
            {
                opts = new ContactListRequestOptions();
            }
            var path = PathResolver(new ContactHubSpotEntity(), HubSpotAction.List)
                .SetQueryParam("count", opts.NumberOfContactsToReturn);
            if (opts.ContactOffset.HasValue)
            {
                path = path.SetQueryParam("vidOffset", opts.ContactOffset);
            }

            if (opts.PropertiesToInclude.Any())
            {
                opts.PropertiesToInclude.ForEach(prop =>
                {
                    path.QueryParams.Add("property", prop);
                });
            }

            var data = await ListAsync<T>(path);
            return data;
        }

        public async Task UpdateAsync(IContactHubSpotEntity contact)
        {
            Logger.LogDebug("Contact update w. id: {0}", contact.Id);
            if (contact.Id < 1)
            {
                throw new ArgumentException("Contact entity must have an id set!");
            }
            var path = PathResolver(contact, HubSpotAction.Update)
                .Replace(":contactId:", contact.Id.ToString());

            await PostAsync<ContactHubSpotEntity>(path, contact);
        }

        public async Task DeleteAsync(long contactId)
        {
            Logger.LogDebug("Contact delete w. id: {0}", contactId);

            var path = PathResolver(new ContactHubSpotEntity(), HubSpotAction.Delete)
                .Replace(":contactId:", contactId.ToString());

            await DeleteAsync<ContactHubSpotEntity>(path);
        }

        /// <summary>
        /// Resolve a hubspot API path based off the entity and operation that is about to happen
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public string PathResolver(IContactHubSpotEntity entity, HubSpotAction action)
        {
            switch (action)
            {
                case HubSpotAction.Create:
                    return $"{entity.RouteBasePath}/contact";
                case HubSpotAction.Get:
                    return $"{entity.RouteBasePath}/contact/vid/:contactId:/profile";
                case HubSpotAction.GetByEmail:
                    return $"{entity.RouteBasePath}/contact/email/:contactEmail:/profile";
                case HubSpotAction.List:
                    return $"{entity.RouteBasePath}/lists/all/contacts/all";
                case HubSpotAction.Update:
                    return $"{entity.RouteBasePath}/contact/vid/:contactId:/profile";
                case HubSpotAction.Delete:
                    return $"{entity.RouteBasePath}/contact/vid/:contactId:";
                case HubSpotAction.CreateOrUpdate:
                    return $"{entity.RouteBasePath}/contact/createOrUpdate/email/:contactemail:";
                default:
                    throw new ArgumentOutOfRangeException(nameof(action), action, null);
            }
        }
    }
}


text:
<?php

namespace Concrete\Core\Search\Pagination\View;
use \Pagerfanta\View\Template\TwitterBootstrap3Template;

class ConcreteBootstrap3Template extends TwitterBootstrap3Template
{

    public function container()
    {
        return sprintf('

%%pages%%

',
            $this->option('css_container_class')
        );
    }
}


text:
package org.sleuthkit.autopsy.actions;

import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.modules.Places;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.coreutils.Logger;

/**
 * The action associated with the Help/Open Log Folder menu item. It opens a
 * file explorer window for either the log subdirectory for the currently open
 * case, or the log subdirectory of the user directory, if there is no current
 * case.
 *
 * This action should only be invoked in the event dispatch thread (EDT).
 */
@ActionRegistration(displayName = "#CTL_OpenLogFolder", iconInMenu = true)
@ActionReference(path = "Menu/Help", position = 1750)
@ActionID(id = "org.sleuthkit.autopsy.actions.OpenLogFolderAction", category = "Help")
public final class OpenLogFolderAction implements ActionListener {

    private static final Logger logger = Logger.getLogger(OpenLogFolderAction.class.getName());

    @Override
    public void actionPerformed(ActionEvent e) {
        File logDir;
        if (Case.isCaseOpen()) {
            try {
                /*
                 * Open the log directory for the case.
                 */
                Case currentCase = Case.getCurrentCase();
                logDir = new File(currentCase.getLogDirectoryPath());
            } catch (IllegalStateException ex) {
                /*
                 * There is no open case, open the application level log
                 * directory.
                 */
                logDir = new File(Places.getUserDirectory().getAbsolutePath() + File.separator + "var" + File.separator + "log");
            }
        } else {
            logDir = new File(Places.getUserDirectory().getAbsolutePath() + File.separator + "var" + File.separator + "log");
        }

        try {
            if (logDir.exists()) {
                Desktop.getDesktop().open(logDir);
            } else {
                logger.log(Level.SEVERE, String.format("The log directory %s does not exist", logDir));
                NotifyDescriptor notifyDescriptor = new NotifyDescriptor.Message(
                        NbBundle.getMessage(this.getClass(), "OpenLogFolder.error1", logDir.getAbsolutePath()),
                        NotifyDescriptor.ERROR_MESSAGE);
                DialogDisplayer.getDefault().notify(notifyDescriptor);
            }
        } catch (IOException ex) {
            logger.log(Level.SEVERE, String.format("Could not open log directory %s", logDir), ex);
            NotifyDescriptor notifyDescriptor = new NotifyDescriptor.Message(
                    NbBundle.getMessage(this.getClass(), "OpenLogFolder.CouldNotOpenLogFolder", logDir.getAbsolutePath()),
                    NotifyDescriptor.ERROR_MESSAGE);
            DialogDisplayer.getDefault().notify(notifyDescriptor);
        }
    }

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

namespace Microsoft.CodeAnalysis
{
    /// <summary>
    /// Represents compilation options common to C# and VB.
    /// </summary>
    [Serializable]
    public abstract class SerializableCompilationOptions : ISerializable
    {
        protected const string OutputKindString = "OutputKind";
        protected const string ModuleNameString = "ModuleName";
        protected const string MainTypeNameString = "MainTypeName";
        protected const string ScriptClassNameString = "ScriptClassName";
        protected const string CryptoKeyContainerString = "CryptoKeyContainer";
        protected const string CryptoKeyFileString = "CryptoKeyFile";
        protected const string DelaySignString = "DelaySign";
        protected const string CheckOverflowString = "CheckOverflow";
        protected const string PlatformString = "Platform";
        protected const string GeneralDiagnosticOptionString = "GeneralDiagnosticOption";
        protected const string WarningLevelString = "WarningLevel";
        protected const string SpecificDiagnosticOptionsString = "SpecificDiagnosticOptions";
        protected const string DebugInformationKindString = "DebugInformationKind";
        protected const string OptimizeString = "Optimize";
        protected const string ConcurrentBuildString = "ConcurrentBuild";
        internal const string ExtendedCustomDebugInformationString = "ExtendedCustomDebugInformation";
        protected const string MetadataImportOptionsString = "MetadataImportOptions";
        protected const string FeaturesString = "Features";

        internal SerializableCompilationOptions()
        {
        }

        protected static void CommonGetObjectData(CompilationOptions options, SerializationInfo info, StreamingContext context)
        {
            info.AddValue(OutputKindString, (int)options.OutputKind);
            info.AddValue(ModuleNameString, options.ModuleName);
            info.AddValue(MainTypeNameString, options.MainTypeName);
            info.AddValue(ScriptClassNameString, options.ScriptClassName);
            info.AddValue(CryptoKeyContainerString, options.CryptoKeyContainer);
            info.AddValue(CryptoKeyFileString, options.CryptoKeyFile);
            info.AddValue(DelaySignString, options.DelaySign);
            info.AddValue(CheckOverflowString, options.CheckOverflow);
            info.AddValue(PlatformString, (int)options.Platform);
            info.AddValue(GeneralDiagnosticOptionString, (int)options.GeneralDiagnosticOption);
            info.AddValue(WarningLevelString, options.WarningLevel);
            info.AddValue(SpecificDiagnosticOptionsString, new Dictionary<string, ReportDiagnostic>(options.SpecificDiagnosticOptions));
            info.AddValue(OptimizeString, (int)options.OptimizationLevel);
            info.AddValue(ConcurrentBuildString, options.ConcurrentBuild);
            info.AddValue(ExtendedCustomDebugInformationString, options.ExtendedCustomDebugInformation);
            info.AddValue(MetadataImportOptionsString, (byte)options.MetadataImportOptions);
            info.AddValue(FeaturesString, options.Features.ToArray());
        }

        public CompilationOptions Options { get { return CommonOptions; } }
        protected abstract CompilationOptions CommonOptions { get; }

        public abstract void GetObjectData(SerializationInfo info, StreamingContext context);
    }
}


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

<title>CallbackHandler (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="javax.security.auth.callback.CallbackHandler interface">
<meta name="keywords" content="handle()">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

compact1, compact2, compact3

javax.security.auth.callback

Interface CallbackHandler

public interface CallbackHandler

 An application implements a CallbackHandler and passes
 it to underlying security services so that they may interact with
 the application to retrieve specific authentication data,
 such as usernames and passwords, or to display certain information,
 such as error and warning messages.

 CallbackHandlers are implemented in an application-dependent fashion.
 For example, implementations for an application with a graphical user
 interface (GUI) may pop up windows to prompt for requested information
 or to display error messages.  An implementation may also choose to obtain
 requested information from an alternate source without asking the end user.

 Underlying security services make requests for different types
 of information by passing individual Callbacks to the
 CallbackHandler.  The CallbackHandler
 implementation decides how to retrieve and display information
 depending on the Callbacks passed to it.  For example,
 if the underlying service needs a username and password to
 authenticate a user, it uses a NameCallback and
 PasswordCallback.  The CallbackHandler
 can then choose to prompt for a username and password serially,
 or to prompt for both in a single window.

 A default CallbackHandler class implementation
 may be specified by setting the value of the
 auth.login.defaultCallbackHandler security property.

 If the security property is set to the fully qualified name of a
 CallbackHandler implementation class,
 then a LoginContext will load the specified
 CallbackHandler and pass it to the underlying LoginModules.
 The LoginContext only loads the default handler
 if it was not provided one.

 All default handler implementations must provide a public
 zero-argument constructor.

See Also:

security properties

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
handle(Callback[] callbacks)

 Retrieve or display the information requested in the
 provided Callbacks.

Method Detail

handle

void handle(Callback[] callbacks)
     throws IOException,
            UnsupportedCallbackException

 Retrieve or display the information requested in the
 provided Callbacks.

 The handle method implementation checks the
 instance(s) of the Callback object(s) passed in
 to retrieve or display the requested information.
 The following example is provided to help demonstrate what an
 handle method implementation might look like.
 This example code is for guidance only.  Many details,
 including proper error handling, are left out for simplicity.

 public void handle(Callback[] callbacks)
 throws IOException, UnsupportedCallbackException {

   for (int i = 0; i < callbacks.length; i++) {
      if (callbacks[i] instanceof TextOutputCallback) {

          // display the message according to the specified type
          TextOutputCallback toc = (TextOutputCallback)callbacks[i];
          switch (toc.getMessageType()) {
          case TextOutputCallback.INFORMATION:
              System.out.println(toc.getMessage());
              break;
          case TextOutputCallback.ERROR:
              System.out.println("ERROR: " + toc.getMessage());
              break;
          case TextOutputCallback.WARNING:
              System.out.println("WARNING: " + toc.getMessage());
              break;
          default:
              throw new IOException("Unsupported message type: " +
                                  toc.getMessageType());
          }

      } else if (callbacks[i] instanceof NameCallback) {

          // prompt the user for a username
          NameCallback nc = (NameCallback)callbacks[i];

          // ignore the provided defaultName
          System.err.print(nc.getPrompt());
          System.err.flush();
          nc.setName((new BufferedReader
                  (new InputStreamReader(System.in))).readLine());

      } else if (callbacks[i] instanceof PasswordCallback) {

          // prompt the user for sensitive information
          PasswordCallback pc = (PasswordCallback)callbacks[i];
          System.err.print(pc.getPrompt());
          System.err.flush();
          pc.setPassword(readPassword(System.in));

      } else {
          throw new UnsupportedCallbackException
                  (callbacks[i], "Unrecognized Callback");
      }
   }
 }

 // Reads user password from given input stream.
 private char[] readPassword(InputStream in) throws IOException {
    // insert code to read a user password from the input stream
 }

Parameters:

callbacks - an array of Callback objects provided
          by an underlying security service which contains
          the information requested to be retrieved or displayed.

Throws:

IOException - if an input or output error occurs.

UnsupportedCallbackException - if the implementation of this
          method does not support one or more of the Callbacks
          specified in the callbacks parameter.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


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

namespace GServer
{
    public class Const
    {
    }
}


text:
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Pandaminium.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)


text:
<?php
declare(strict_types=1);

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     * @Method("GET")
     * @Template("default/homepage.twig")
     * //@Security("is_authenticated()")
     */
    public function indexAction(Request $request)
    {
        //$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'access only for role: ROLE_ADMIN');

        //return $this->render('default/index.html.twig', [
        //    'base_dir' => realpath($this->container->getParameter('kernel.root_dir') . '/..'),
        //]);
        return ['rscontent' => 'path: /
/init'];
    }

    /**
     * @Route("/init")
     * @Method("GET")
     */
    public function initAction()
    {
        $sendToTemplate = [];

        //echo 'init...
';
        //$users = ['result' => $userRepository->findAll()];
        //$sendToTemplate[] = $this->get('jms_serializer')->serialize($users, 'json', SerializationContext::create()
        //    ->setGroups(['list'])
        //    ->setSerializeNull(true)
        //    ->enableMaxDepthChecks());

        //return $this->render('default/index.html.twig', ['base_dir' => realpath($this->container->getParameter('kernel.root_dir') . '/..'),]);
        return $this->render('default/test.twig', ['rscontent' => implode("\n", $sendToTemplate)]);
    }
}


text:
import config from 'config'

import { MainNavigator } from 'navigation'

import { combineReducers } from 'redux'

import { reducers as appConfigsReducer } from 'modules/AppConfigs'
import { reducers as authReducer } from 'modules/Auth'
import { reducers as caseStudiesReducer } from 'modules/CaseStudies'
import { reducers as companyProfileReducer } from 'modules/CompanyProfile'
import { reducers as contactsReducer } from 'modules/Contacts'
import { reducers as contactUsReducer } from 'modules/ContactUs'
import { reducers as faqsReducer } from 'modules/Faqs'
import { reducers as HomeReducer } from 'modules/Home'
import { reducers as houseCategoriesReducer } from 'modules/HouseCategories'
import { reducers as newslettersReducer } from 'modules/Newsletters'
import { reducers as productCategoriesReducer } from 'modules/ProductCategories'
import { reducers as productsReducer } from 'modules/Products'
import { reducers as ricohTouchesReducer } from 'modules/RicohTouches'
import { reducers as searchReducers } from 'modules/Search'
import { reducers as servicesReducer } from 'modules/Services'
import { reducers as settingsReducer } from 'modules/Settings'
import { reducers as solutionCategoriesReducer } from 'modules/SolutionCategories'
import { reducers as solutionsReducer } from 'modules/Solutions'

import { nav } from 'utilities'
import { ga } from 'services'

const tracker = new ga.Tracker( config.ga, config.app.name, config.app.version )

const initialState = MainNavigator.Nav.router.getStateForAction(
  MainNavigator.Nav.router.getActionForPathAndParams(
    config.app.initialRouteName
  )
)

const navReducer = ( state = initialState, action ) => {
  const nextState = MainNavigator.Nav.router.getStateForAction( action, state )

  const currentScreen = nav.getCurrentRouteName( nextState )
  const prevScreen = nav.getCurrentRouteName( state )

  if ( prevScreen !== currentScreen ) {
    tracker.trackScreenView( currentScreen )
  }

  return nextState || state
}

const rootReducer = combineReducers( {
  ...appConfigsReducer,
  ...authReducer,
  ...caseStudiesReducer,
  ...companyProfileReducer,
  ...contactsReducer,
  ...contactUsReducer,
  ...faqsReducer,
  ...HomeReducer,
  ...houseCategoriesReducer,
  ...newslettersReducer,
  ...productCategoriesReducer,
  ...productsReducer,
  ...ricohTouchesReducer,
  ...searchReducers,
  ...servicesReducer,
  ...settingsReducer,
  ...solutionCategoriesReducer,
  ...solutionsReducer,
  nav: navReducer,
} )

export default rootReducer


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > Don't Be a Bully

						Expand All | Collapse All

Don't Be a Bully

 Richard applied to many places. He knew all the bosses of the companies. They were the men Richard used to bully as children. Richard had a very hard time finding a job.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
package net.simonvt.cathode.dagger;

import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import net.simonvt.cathode.settings.NotificationSettingsActivity;
import net.simonvt.cathode.settings.SettingsActivity;
import net.simonvt.cathode.settings.hidden.HiddenItems;
import net.simonvt.cathode.settings.link.TraktLinkActivity;
import net.simonvt.cathode.settings.link.TraktLinkSyncActivity;
import net.simonvt.cathode.settings.login.LoginActivity;
import net.simonvt.cathode.settings.login.OauthWebViewActivity;
import net.simonvt.cathode.settings.login.TokenActivity;
import net.simonvt.cathode.ui.CalendarEntryActivity;
import net.simonvt.cathode.ui.EpisodeDetailsActivity;
import net.simonvt.cathode.ui.HomeActivity;
import net.simonvt.cathode.ui.SeasonDetailsActivity;

@Module public abstract class ActivityBindingModule {

  @ContributesAndroidInjector abstract HomeActivity homeActivity();

  @ContributesAndroidInjector abstract LoginActivity loginActivity();

  @ContributesAndroidInjector abstract TraktLinkActivity traktLinkActivity();

  @ContributesAndroidInjector abstract TraktLinkSyncActivity traktLinkSyncActivity();

  @ContributesAndroidInjector abstract CalendarEntryActivity calendarEntryActivity();

  @ContributesAndroidInjector abstract EpisodeDetailsActivity episodeDetailsActivity();

  @ContributesAndroidInjector abstract SeasonDetailsActivity seasonDetailsActivity();

  @ContributesAndroidInjector abstract OauthWebViewActivity oauthWebViewActivity();

  @ContributesAndroidInjector abstract TokenActivity tokenActivity();

  @ContributesAndroidInjector abstract SettingsActivity settingsActivity();

  @ContributesAndroidInjector abstract NotificationSettingsActivity notificationSettingsActivity();

  @ContributesAndroidInjector abstract HiddenItems hiddenItems();
}


text:
// For conditions of distribution and use, see copyright notice in LICENSE

#pragma once

#include <QDomDocument>

/// Holds data that is transferred server->client immediately after the client has successfully connected to the server.
/** The contents can hold arbitrary data that is to be passed to the client to read. (max 64K bytes). */
struct UserConnectedResponseData
{
    QDomDocument responseData;
};


text:
class TaskPresenter < BasePresenter

  def created_at
    h.l(super)
  end

  def state
    h.t("task.states.#{super}")
  end

  def state_button(state_event)
    can_transition = send(:"may_#{state_event}?")
    button_css =
      case state_event
      when :start
        'btn-primary'
      when :finish
        'btn-success'
      when :reset
        'btn-warning'
      end
    text = h.t("task.events.#{state_event}")
    text_css = "task-state-link task-state-link-#{state_event}"

    h.content_tag(:button, class: "task-btn btn btn-lg #{button_css}",
                           data: {event: state_event, id: id},
                           type: 'button') do
      if can_transition
        h.link_to text, '#', class: text_css
      else
        h.content_tag(:span, text, class: text_css)
      end
    end
  end

  def render_description
    h.content_tag(:div, class: "task-attribute task-attribute-description") do
      h.concat h.content_tag(:strong, "#{Task.human_attribute_name(:description)}: ")
      h.concat h.content_tag(:p, description, class: 'qa-task-description')
    end
  end

  def render_list_attribute(attribute)
    h.content_tag(:div, class: "task-attribute task-attribute-#{attribute}") do
      h.concat h.content_tag(:strong, "#{Task.human_attribute_name(attribute)}: ")
      h.concat h.content_tag(:span, send(attribute), class: "qa-task-#{attribute}")
    end
  end

end


text:
<?php
    /*
     * Set format for output array.
     * Available choices
     * json, serialized php, xml, kml, wikitable
     *
     * To do:
     * consider moving mapping here
     */

    class Format{

        function outputJsonp($results, $callback){
            /* Setting up JSONP headers */
            @header ("content-type: application/javascript; charset=utf-8");

            /* Printing the wrapped JSON Object */
            echo $callback.'('.json_encode($results).');';
        }

        function outputJson($results){
            /* Setting up JSON headers */
            @header ("content-type: application/json; charset=utf-8");
            header ("Access-Control-Allow-Origin: *");

            $compact=False;
            if (strtolower($_GET['json']) == 'compact'){
                $compact=True;
            }
            /* Printing the JSON Object */
            if ($compact){
                echo json_encode($results);
            }else{
                echo self::prettyPrintJson($results);
            }
        }

        function outputPhp($results){
            /* Setting up PHP headers */
            header ("content-type: application/x-php; charset=utf-8");

            /* Printing the PHP serialized Object*/
            echo serialize($results);
        }

        function outputXml($results, $xsltPath){
            /* Setting XML header */
            @header ("content-type: text/xml; charset=UTF-8");

            /* Initializing the XML Object */
            $xml = new XmlWriter();
            $xml->openMemory();
            $xml->setIndent(true);
            $xml->setIndentString('    ');
            $xml->startDocument('1.0', 'UTF-8');
            if(isset($xsltPath))
                $xml->WritePi('xml-stylesheet', 'type="text/xsl" href="'.$xsltPath.'"');
            $xml->startElement('callback');
            $xml->writeAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance');
            $xml->writeAttribute('xsi:noNamespaceSchemaLocation','schema.xsd');

            /* Function that converts each array element to an XML node */
            function write(XMLWriter $xml, $data){
                    foreach($data as $key => $value){
                            if(is_array($value)){
                                if (is_numeric($key)){   #The only time a numeric key would be used is if it labels an array with non-uniqe keys
                                    write($xml, $value);
                                    continue;
                                } else{
                                    $xml->startElement($key);
                                    write($xml, $value);
                                    $xml->endElement();
                                    continue;
                                }
                            }
                            $xml->writeElement($key, $value);
                    }
            }

            /* Calls previously declared function, passing our results array as parameter */
            write($xml, $results);

            /* Closing last XML node */
            $xml->endElement();

            /* Printing the XML */
            echo $xml->outputMemory(true);
        }

        function outputKml($results){
            if (strtolower($_GET['action']) == 'get'){
                include('FormatKml.php');
                FormatKml::output($results);
            }else{
                $results['head']['warning'] .= 'KML is only a valid format for the "get" action; defaulting to xml. ';
                self::outputXml($results);
            }
        }

        function outputWiki($results){
            if (strtolower($_GET['action']) == 'get'){
                include('FormatWikilist.php');
                FormatWikilist::output($results);
            }else{
                $results['head']['warning'] .= 'wikilist is only a valid format for the "get" action; defaulting to xml. ';
                self::outputXml($results);
            }
        }

        function outputGeojson($results){
            if (strtolower($_GET['action']) == 'get'){
                include('FormatGeojson.php');
                $full = False;
                $compact = False;
                if (strtolower($_GET['geojson']) == 'full'){
                    $full=True;
                }
                if (strtolower($_GET['json']) == 'compact'){
                    $compact=True;
                }
                FormatGeojson::output($results, $full, $compact);
            }else{
                $results['head']['warning'] .= 'geojson is only a valid format for the "get" action; defaulting to xml. ';
                self::outputXml($results);
            }
        }

        function outputDefault($results){
            self::outputXml($results);
        }

        #quick and dirty
        function outputXsl($results){
            if (strtolower($_GET['action']) == 'get')
                self::outputXml($results, 'get.xsl');
            elseif (strtolower($_GET['action']) == 'artist')
                self::outputXml($results, 'artist.xsl');
            elseif ((strtolower($_GET['action']) == 'admin') and (strtolower($_GET['function']) == 'diff'))
                self::outputXml($results, 'diff.xsl');
            elseif ((strtolower($_GET['action']) == 'admin') and (strtolower($_GET['function']) == 'info'))
                self::outputXml($results, 'info.xsl');
            else{
                $results['head']['warning'] .= 'XSL is only a valid format for the "get" and "admin/diff" actions; defaulting to xml. ';
                self::outputXml($results);
            }
        }

        #For backwards compatibility wiht PHP versions below 5.4
        #Code by Kendall Hopkins @ http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php
        function prettyPrintJson( $results ){
            if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
                return json_encode($results, JSON_PRETTY_PRINT);
            }else{
                return self::prettyPrint(json_encode($results));
            }
        }

        function prettyPrint( $json )
        {
            $result = '';
            $level = 0;
            $prev_char = '';
            $in_quotes = false;
            $ends_line_level = NULL;
            $json_length = strlen( $json );

            for( $i = 0; $i < $json_length; $i++ ) {
                $char = $json[$i];
                $new_line_level = NULL;
                $post = "";
                if( $ends_line_level !== NULL ) {
                    $new_line_level = $ends_line_level;
                    $ends_line_level = NULL;
                }
                if( $char === '"' && $prev_char != '\\' ) {
                    $in_quotes = !$in_quotes;
                } else if( ! $in_quotes ) {
                    switch( $char ) {
                        case '}': case ']':
                            $level--;
                            $ends_line_level = NULL;
                            $new_line_level = $level;
                            break;

                        case '{': case '[':
                            $level++;
                        case ',':
                            $ends_line_level = $level;
                            break;

                        case ':':
                            $post = " ";
                            break;

                        case " ": case "\t": case "\n": case "\r":
                            $char = "";
                            $ends_line_level = $new_line_level;
                            $new_line_level = NULL;
                            break;
                    }
                }
                if( $new_line_level !== NULL ) {
                    $result .= "\n".str_repeat( "\t", $new_line_level );
                }
                $result .= $char.$post;
                $prev_char = $char;
            }

            return $result;
        }

    }
?>


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddDiscIntoSongs extends Migration
{
    public function up(): void
    {
        Schema::table('songs', static function (Blueprint $table): void {
            $table->integer('disc')->after('track')->default(1);
        });
    }

    public function down(): void
    {
        Schema::table('songs', static function (Blueprint $table): void {
            $table->dropColumn('disc');
        });
    }
}


text:
pynrc.DetectorOps.scaid\_list
=============================

.. currentmodule:: pynrc

.. autoproperty:: DetectorOps.scaid_list


text:
using System;
using ProtoBuf;
using TrackableData;

namespace Domain
{
    [ProtoContract]
    public interface IUserContext : ITrackableContainer<IUserContext>
    {
        [ProtoMember(1)] TrackableUserData Data { get; set; }
        [ProtoMember(2)] TrackableDictionary<int, UserAchievement> Achivements { get; set; }
    }
}


text:
package com.project.hellonepal;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {

    // The ImageView of the Logos
    private ImageView coffeeLogo;
    private ImageView travelLogo;
    private ImageView foodLogo;
    private ImageView drinkLogo;
    private ImageView artLogo;
    private ImageView shopLogo;
    public static int selector;

    // The app-specific constant when requesting the location permission
    private static final int PERMISSION_ACCESS_FINE_LOCATION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Attaches a listener for animation/transition to the logos

        travelLogo = (ImageView) findViewById(R.id.travel);
        travelLogo.setOnClickListener(this);

        coffeeLogo = (ImageView) findViewById(R.id.coffee);
        coffeeLogo.setOnClickListener(this);

        foodLogo = (ImageView) findViewById(R.id.food);
        foodLogo.setOnClickListener(this);

        drinkLogo = (ImageView) findViewById(R.id.drink);
        drinkLogo.setOnClickListener(this);

        shopLogo = (ImageView) findViewById(R.id.shop);
        shopLogo.setOnClickListener(this);

        artLogo = (ImageView) findViewById(R.id.art);
        artLogo.setOnClickListener(this);

        // Requests for location permissions at runtime (required for API >= 23)
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_ACCESS_FINE_LOCATION);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Adds animation to the Logos
//        RotateAnimation jitter = new RotateAnimation(0, 2, 50, 50);
//        jitter.setDuration(10);
//        jitter.setRepeatCount(Animation.INFINITE);
//        jitter.setRepeatMode(Animation.REVERSE);
//        coffeeLogo.startAnimation(jitter);
//        travelLogo.startAnimation(jitter);
//        foodLogo.startAnimation(jitter);
//        artLogo.startAnimation(jitter);
//        drinkLogo.startAnimation(jitter);
//        shopLogo.startAnimation(jitter);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.food:
                Animation click = AnimationUtils.loadAnimation(this, R.anim.click);

                // Defines a listener to transition to the PlacePickerActivity after the animation completes
                click.setAnimationListener(new Animation.AnimationListener() {

                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            selector = 1;
                            Intent i = new Intent(getApplicationContext(), PlacePickerActivity.class);
                            startActivity(i);

                        } else {
                            // Notifies the user if there are insufficient location permissions
                            Toast.makeText(getApplicationContext(), "App is missing permissions to access your location!", Toast.LENGTH_LONG).show();
                        }
                    }
                });

                // Attaches the alpha/scale animation to the view
                view.startAnimation(click);
                break;

            case R.id.coffee:
                Animation click2 = AnimationUtils.loadAnimation(this, R.anim.click);

                // Defines a listener to transition to the PlacePickerActivity after the animation completes
                click2.setAnimationListener(new Animation.AnimationListener() {

                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            selector = 2;
                            Intent i = new Intent(getApplicationContext(), PlacePickerActivity.class);
                            startActivity(i);

                        } else {
                            // Notifies the user if there are insufficient location permissions
                            Toast.makeText(getApplicationContext(), "App is missing permissions to access your location!", Toast.LENGTH_LONG).show();
                        }
                    }
                });
                // Attaches the alpha/scale animation to the view
                view.startAnimation(click2);
                break;

            case R.id.travel:
                Animation click3 = AnimationUtils.loadAnimation(this, R.anim.click);

                // Defines a listener to transition to the PlacePickerActivity after the animation completes
                click3.setAnimationListener(new Animation.AnimationListener() {

                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            selector = 4;
                            Intent i = new Intent(getApplicationContext(), PlacePickerActivity.class);
                            startActivity(i);

                        } else {
                            // Notifies the user if there are insufficient location permissions
                            Toast.makeText(getApplicationContext(), "App is missing permissions to access your location!", Toast.LENGTH_LONG).show();
                        }
                    }
                });

                // Attaches the alpha/scale animation to the view
                view.startAnimation(click3);
                break;

            case R.id.drink:
                Animation click4 = AnimationUtils.loadAnimation(this, R.anim.click);

                // Defines a listener to transition to the PlacePickerActivity after the animation completes
                click4.setAnimationListener(new Animation.AnimationListener() {

                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            selector = 3;
                            Intent i = new Intent(getApplicationContext(), PlacePickerActivity.class);
                            startActivity(i);

                        } else {
                            // Notifies the user if there are insufficient location permissions
                            Toast.makeText(getApplicationContext(), "App is missing permissions to access your location!", Toast.LENGTH_LONG).show();
                        }
                    }
                });

                // Attaches the alpha/scale animation to the view
                view.startAnimation(click4);
                break;

            case R.id.art:
                Animation click5 = AnimationUtils.loadAnimation(this, R.anim.click);

                // Defines a listener to transition to the PlacePickerActivity after the animation completes
                click5.setAnimationListener(new Animation.AnimationListener() {

                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            selector = 5;
                            Intent i = new Intent(getApplicationContext(), PlacePickerActivity.class);
                            startActivity(i);

                        } else {
                            // Notifies the user if there are insufficient location permissions
                            Toast.makeText(getApplicationContext(), "App is missing permissions to access your location!", Toast.LENGTH_LONG).show();
                        }
                    }
                });

                // Attaches the alpha/scale animation to the view
                view.startAnimation(click5);
                break;
            case R.id.shop:
                Animation click6 = AnimationUtils.loadAnimation(this, R.anim.click);

                // Defines a listener to transition to the PlacePickerActivity after the animation completes
                click6.setAnimationListener(new Animation.AnimationListener() {

                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            selector = 6;
                            Intent i = new Intent(getApplicationContext(), PlacePickerActivity.class);
                            startActivity(i);

                        } else {
                            // Notifies the user if there are insufficient location permissions
                            Toast.makeText(getApplicationContext(), "App is missing permissions to access your location!", Toast.LENGTH_LONG).show();
                        }
                    }
                });

                // Attaches the alpha/scale animation to the view
                view.startAnimation(click6);
                break;
        }

    }
}


text:
#include <stdint.h>
#include <string.h>
#include <stdlib.h>

#include "ch.h"
#include "hal.h"
#include "hal_spi.h"
#include "chprintf.h"
#include "shell.h"

#include "gfx.h"

#include "ble_lld.h"

#include "ff.h"
#include "ffconf.h"
#include "diskio.h"

#include "async_io_lld.h"
#include "joypad_lld.h"

#include "orchard-ui.h"
#include "orchard-app.h"

#include "badge.h"

struct evt_table orchard_events;

/* linker set for command objects */

orchard_command_start();
orchard_command_end();

#define LED_EXT 14

bool watchdog_started = false;

static const SPIConfig spi1_config = {
	NULL,			/* enc_cp */
	NRF5_SPI_FREQ_8MBPS,	/* freq */
	IOPORT1_SPI_SCK,	/* sckpad */
	IOPORT1_SPI_MOSI,	/* mosipad */
	IOPORT1_SPI_MISO,	/* misopad */
	IOPORT1_SDCARD_CS,	/* sspad */
	FALSE,			/* lsbfirst */
	2,			/* mode */
	0xFF			/* dummy data for spiIgnore() */
};

static const I2CConfig i2c2_config = {
	100000,			/* clock */
	IOPORT1_I2C_SCK,	/* scl_pad */
	IOPORT1_I2C_SDA		/* sda_pad */
};

static void
gpt_callback(GPTDriver *gptp)
{
	(void)gptp;
	return;
}

static void
mmc_callback(GPTDriver *gptp)
{
	(void)gptp;
	disk_timerproc ();
}

/*
 * GPT configuration
 * Frequency: 16MHz
 * Resolution: 32 bits
 */

static const GPTConfig gpt1_config = {
    .frequency  = NRF5_GPT_FREQ_16MHZ,
    .callback   = gpt_callback,
    .resolution = 32,
};

static const GPTConfig gpt2_config = {
    .frequency  = NRF5_GPT_FREQ_62500HZ,
    .callback   = mmc_callback,
    .resolution = 32,
};

static THD_WORKING_AREA(shell_wa, 1024);
static thread_t *shell_tp = NULL;

static SerialConfig serial_config = {
    .speed   = 115200,
    .tx_pad  = UART_TX,
    .rx_pad  = UART_RX,
#if NRF5_SERIAL_USE_HWFLOWCTRL	== TRUE
    .rts_pad = UART_RTS,
    .cts_pad = UART_CTS,
#endif
};

static void shellRestart(void)
{
	static ShellConfig shellConfig;
	static const ShellCommand *shellCommands;

	shellCommands = orchard_commands();

	shellConfig.sc_channel =  (BaseSequentialStream *)&SD1;
	shellConfig.sc_commands = shellCommands;

	/* Recovers memory of the previous shell. */
	if (shell_tp && chThdTerminatedX(shell_tp))
		chThdRelease(shell_tp);

    	shell_tp = chThdCreateStatic (shell_wa, sizeof(shell_wa), NORMALPRIO + 5,
	    shellThread, (void *)&shellConfig);

	return;
}

static void
orchard_app_restart(eventid_t id)
{
	(void)id;

	orchardAppRestart();
}

static void
shell_termination_handler(eventid_t id)
{
	static int i = 1;

	printf ("\r\nRespawning shell (shell #%d, event %d)\r\n", ++i, id);
	shellRestart ();
}

static THD_WORKING_AREA(waThread1, 64);
static THD_FUNCTION(Thread1, arg) {

    (void)arg;
    uint8_t led = LED4;

    chRegSetThreadName("blinker");

    while (1) {
	palTogglePad(IOPORT1, led);
	chThdSleepMilliseconds(1000);
    }
}

void
SVC_Handler (void)
{
	while (1) {}
}

/**@brief Function for application main entry.
 */
int main(void)
{
    uint32_t info;
    uint8_t * p;
#ifdef CRT0_VTOR_INIT
    __disable_irq();
    SCB->VTOR = 0;
    __enable_irq();
#endif

    halInit();
    chSysInit();
    shellInit();

    sdStart (&SD1, &serial_config);
    printf ("\r\n");

    palClearPad (IOPORT1, LED1);
    palClearPad (IOPORT1, LED2);
    palClearPad (IOPORT1, LED3);
    palClearPad (IOPORT1, LED4);

    gptStart (&GPTD2, &gpt1_config);
    gptStart (&GPTD3, &gpt2_config);

    /* Launch test blinker thread. */

    chThdCreateStatic(waThread1, sizeof(waThread1), NORMALPRIO+1,
		      Thread1, NULL);

    chThdSleep(2);
    printf ("SYSTEM START\r\n");
    info = NRF_FICR->INFO.VARIANT;
    p = (uint8_t *)&info;
    printf ("Nordic Semiconductor nRF%x Variant: %c%c%c%c ",
        NRF_FICR->INFO.PART, p[3], p[2], p[1], p[0]);
    printf ("RAM: %dKB Flash: %dKB\r\n", NRF_FICR->INFO.RAM,
        NRF_FICR->INFO.FLASH);
    printf ("Device ID: %x%x\r\n", NRF_FICR->DEVICEID[0],
        NRF_FICR->DEVICEID[1]);
    chThdSleep(2);
    printf (PORT_INFO "\r\n");
    chThdSleep(2);

    printf("Priority levels %d\r\n", CORTEX_PRIORITY_LEVELS);

    joyStart ();
    asyncIoStart ();

    palSetPad (IOPORT1, IOPORT1_SPI_MOSI);
    palSetPad (IOPORT1, IOPORT1_SPI_MISO);
    palSetPad (IOPORT1, IOPORT1_SPI_SCK);
    palSetPad (IOPORT1, IOPORT1_SDCARD_CS);
    palSetPad (IOPORT1, IOPORT1_TOUCH_CS);

    spiStart (&SPID1, &spi1_config);
#ifdef notyet
    i2cStart (&I2CD2, &i2c2_config);

    gfxInit ();

    if (gfileMount ('F', "0:") == FALSE)
        printf ("No SD card found.\r\n");
    else
        printf ("SD card detected.\r\n");
#endif
    bleStart ();

    NRF_P0->DETECTMODE = 0;

    /* Launch shell thread */

    evtTableInit (orchard_events, 5);
    evtTableHook (orchard_events, shell_terminated, shell_termination_handler);

    shellRestart ();
#ifdef notyet
    uiStart ();
    orchardAppInit ();
    orchardAppRestart ();
#endif
    evtTableHook (orchard_events, orchard_app_terminated, orchard_app_restart);

    while (true) {
        chEvtDispatch(evtHandlers(orchard_events), chEvtWaitOne(ALL_EVENTS));
    }

}


text:
package org.olat.presentation.course.condition;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.olat.data.group.context.BGContext;
import org.olat.lms.group.learn.CourseGroupManager;
import org.olat.presentation.framework.core.UserRequest;
import org.olat.presentation.framework.core.components.form.flexible.FormItem;
import org.olat.presentation.framework.core.components.form.flexible.FormItemContainer;
import org.olat.presentation.framework.core.components.form.flexible.elements.MultipleSelectionElement;
import org.olat.presentation.framework.core.components.form.flexible.elements.Reset;
import org.olat.presentation.framework.core.components.form.flexible.elements.Submit;
import org.olat.presentation.framework.core.components.form.flexible.impl.FormBasicController;
import org.olat.presentation.framework.core.components.form.flexible.impl.FormEvent;
import org.olat.presentation.framework.core.components.form.flexible.impl.elements.FormLinkImpl;
import org.olat.presentation.framework.core.components.form.flexible.impl.elements.FormReset;
import org.olat.presentation.framework.core.components.form.flexible.impl.elements.FormSubmit;
import org.olat.presentation.framework.core.control.Controller;
import org.olat.presentation.framework.core.control.WindowControl;
import org.olat.presentation.framework.core.control.generic.closablewrapper.CloseableModalController;
import org.olat.presentation.group.BGControllerFactory;
import org.olat.presentation.group.NewAreaController;
import org.olat.presentation.group.NewBGController;
import org.olat.system.commons.resource.OLATResourceable;
import org.olat.system.event.Event;

/**
 * Description:

 * TODO: patrickb Class Description for MultiSelectColumnController
 *

 * Initial Date: 15.06.2007

 *
 * @author patrickb
 */
public class GroupOrAreaSelectionController extends FormBasicController {

    private MultipleSelectionElement entrySelector;
    protected String[] entries;
    private final String title;
    private FormLinkImpl createNew;
    private final CourseGroupManager courseGrpMngr;
    private final BGContext bgContext;
    private final boolean inGroupMode;
    private NewBGController groupCreateCntrllr;
    private NewAreaController areaCreateCntrllr;
    private CloseableModalController cmc;
    private OLATResourceable ores;

    public GroupOrAreaSelectionController(final OLATResourceable ores, final int groupOrArea, final WindowControl wControl, final UserRequest ureq, final String title,
            final CourseGroupManager courseGrpMngr, final String selectionAsCsvStr) {
        super(ureq, wControl, "group_or_area_selection");
        this.ores = ores;
        /*
         * before initialising the element, prepare data
         */
        this.courseGrpMngr = courseGrpMngr;
        // group or area mode
        this.inGroupMode = groupOrArea == 0;
        //
        this.bgContext = getDefaultBGContext();
        // unique names from list to arry
        List<String> uniqueNames = null;
        if (inGroupMode) {
            uniqueNames = courseGrpMngr.getUniqueLearningGroupNamesFromAllContexts(ores);
        } else {
            uniqueNames = courseGrpMngr.getUniqueAreaNamesFromAllContexts(ores);
        }

        entries = new String[uniqueNames.size()];
        uniqueNames.toArray(entries);
        this.title = title;
        /*
         * init form elements
         */
        initForm(this.flc, this, ureq);
        /*
         * after initialising the element, select the entries
         */
        final String[] activeSelection = selectionAsCsvStr != null ? selectionAsCsvStr.split(",") : new String[] {};
        for (int i = 0; i < activeSelection.length; i++) {
            entrySelector.select(activeSelection[i].trim(), true);
        }
    }

    /*
     * find default context if one is present
     */
    private BGContext getDefaultBGContext() {
        final List courseLGContextes = courseGrpMngr.getLearningGroupContexts(ores);
        for (final Iterator iter = courseLGContextes.iterator(); iter.hasNext();) {
            final BGContext bctxt = (BGContext) iter.next();
            if (bctxt.isDefaultContext()) {
                return bctxt;
            }
        }
        return null;
        // not found! this is inacceptable! -> disable creation of groups!

    }

    @Override
    @SuppressWarnings("unused")
    protected void formInnerEvent(final UserRequest ureq, final FormItem source, final FormEvent event) {
        if (source == createNew) {
            if (inGroupMode) {

                // user wants to create a new group -> show group create form

                removeAsListenerAndDispose(groupCreateCntrllr);
                groupCreateCntrllr = BGControllerFactory.getInstance().createNewBGController(ureq, getWindowControl(), true, bgContext, true, null);
                listenTo(groupCreateCntrllr);

                removeAsListenerAndDispose(cmc);
                cmc = new CloseableModalController(getWindowControl(), "close", groupCreateCntrllr.getInitialComponent());
                listenTo(cmc);

                cmc.activate();

            } else {

                // user wants to create a new area -> show new area create form

                removeAsListenerAndDispose(areaCreateCntrllr);
                areaCreateCntrllr = BGControllerFactory.getInstance().createNewAreaController(ureq, getWindowControl(), bgContext);
                listenTo(areaCreateCntrllr);

                removeAsListenerAndDispose(cmc);
                cmc = new CloseableModalController(getWindowControl(), "close", areaCreateCntrllr.getInitialComponent());
                listenTo(cmc);

                cmc.activate();
            }
        }
    }

    @Override
    @SuppressWarnings("unused")
    protected void event(final UserRequest ureq, final Controller source, final Event event) {
        if (source == groupCreateCntrllr) {

            cmc.deactivate();

            if (event == Event.DONE_EVENT) {
                List<String> uniqueNames = null;
                uniqueNames = courseGrpMngr.getUniqueLearningGroupNamesFromAllContexts(ores);
                // update entries
                entries = new String[uniqueNames.size()];
                uniqueNames.toArray(entries);
                entrySelector.setKeysAndValues(entries, entries, null);
                //
                // select new value
                entrySelector.select(groupCreateCntrllr.getCreatedGroup().getName(), true);

                // inform condition config easy about new groups -> which informs further
                fireEvent(ureq, Event.CHANGED_EVENT);
            }
        } else if (source == areaCreateCntrllr) {

            cmc.deactivate();

            if (event == Event.DONE_EVENT) {
                List<String> uniqueNames = null;
                uniqueNames = courseGrpMngr.getUniqueAreaNamesFromAllContexts(ores);
                // update entries
                entries = new String[uniqueNames.size()];
                uniqueNames.toArray(entries);
                entrySelector.setKeysAndValues(entries, entries, null);
                //
                // select new value
                entrySelector.select(areaCreateCntrllr.getCreatedAreaName(), true);

                // inform condition config easy about new groups -> which informs further
                fireEvent(ureq, Event.CHANGED_EVENT);
            }
        }
    }

    /**
	 */
    @Override
    @SuppressWarnings("unused")
    protected void doDispose() {
        //
    }

    @Override
    @SuppressWarnings("unused")
    protected void initForm(final FormItemContainer boundTo, final Controller listener, final UserRequest ureq) {
        /*
         * // | [] group 1 | create group | // | [] group 2 | | // | submit | cancel | | //
         */
        if (bgContext != null) {
            // easy creation only possible if a default group context available
            if (inGroupMode) {
                createNew = new FormLinkImpl("create");
            } else {
                createNew = new FormLinkImpl("create");
            }
            // is a button
            createNew.setCustomEnabledLinkCSS("b_button");
            createNew.setCustomDisabledLinkCSS("b_button b_disabled");
            // create new group/area on the right side
            boundTo.add(createNew);
        }

        entrySelector = uifactory.addCheckboxesVertical("entries", null, boundTo, entries, entries, null, 1);
        // submitCancel after checkboxes
        //
        final Submit subm = new FormSubmit("subm", "apply");
        final Reset reset = new FormReset("reset", "cancel");
        boundTo.add(subm);
        boundTo.add(reset);
    }

    @Override
    protected void formOK(final UserRequest ureq) {
        fireEvent(ureq, Event.DONE_EVENT);
    }

    @Override
    protected void formResetted(final UserRequest ureq) {
        fireEvent(ureq, Event.CANCELLED_EVENT);
    }

    public Set getSelectedEntries() {
        return entrySelector.getSelectedKeys();
    }

}


text:
class QtActionWidget : public QtBaseWidget {
	Q_OBJECT

public:
	QtActionWidget(PyQtGuiObject* control);
	~QtActionWidget();
	QPushButton* buttonWidget;

	virtual void updateContent();
	void updateTitle();

protected:
	virtual void resizeEvent(QResizeEvent *);

public slots:
	void onClick();
};

#endif


text:
// TypeScript Version: 2.0

/**
* Tests if a value is a Complex128Array.
*
* @param value - value to test
* @returns boolean indicating whether value is a Complex128Array
*
* @example
* var bool = isComplex128Array( new Complex128Array( 10 ) );
* // returns true
*
* @example
* var bool = isComplex128Array( [] );
* // returns false
*/
declare function isComplex128Array( value: any ): boolean;

// EXPORTS //

export = isComplex128Array;


text:
Follow these instructions to install a copy of Glossary Bot locally for development and testing.

#### Requirements

Glossary Bot is written in Python 2.7.

#### Install

Glossary Bot is a [Flask](http://flask.pocoo.org/) app built to run on [Heroku](https://heroku.com/).

To install locally, clone this repository and cd into the resulting directory:

```
git clone git@github.com:codeforamerica/glossary-bot.git
cd glossary-bot
```

Set up and activate a new virtual environment using [Virtualenv](https://github.com/codeforamerica/howto/blob/master/Python-Virtualenv.md):

```
virtualenv venv-glossary-bot
```

Activate the virtual environment:

```
source venv-glossary-bot/bin/activate
```

Install the required packages with pip:

```
pip install -r requirements.txt
```

Create the production [PostgreSQL](https://github.com/codeforamerica/howto/blob/master/PostgreSQL.md) database:

```
createdb glossary-bot
```

Copy `env.sample` to `.env`:

```
cp env.sample .env
```

and make sure that the value of `DATABASE_URL` in `.env` matches the name of the database you created in the last step.

Initialize the database:

```
python manage.py db upgrade
```

And run the application:

```
python manage.py runserver
```

#### Test

To run the app's tests, first create a test database. Make sure the name of the database matches the value of `environ['DATABASE_URL']` set in the `setUp()` function in [test/test_bot.py](https://github.com/codeforamerica/glossary-bot/blob/master/tests/test_bot.py):

```
createdb glossary-bot-test
```

You can now run the tests from the command line:

```
python manage.py runtests
```

or run an individual test:

```
python tests/test_bot.py BotTestCase.test_get_definition
```


text:
<?php
namespace Craft;

class CategoryGroupModel extends BaseModel
{
	// Properties
	// =========================================================================

	/**
	 * @var
	 */
	private $_locales;

	// Public Methods
	// =========================================================================

	/**
	 * Use the translated category group's name as the string representation.
	 *
	 * @return string
	 */
	public function __toString()
	{
		return (string)Craft::t($this->name);
	}

	/**
	 * @return array
	 */
	public function behaviors()
	{
		return array(
			'fieldLayout' => new FieldLayoutBehavior(ElementType::Category),
		);
	}

	/**
	 * Returns the category's locale models.
	 *
	 * @return array
	 */
	public function getLocales()
	{
		if (!isset($this->_locales))
		{
			if ($this->id)
			{
				$this->_locales = craft()->categories->getGroupLocales($this->id, 'locale');
			}
			else
			{
				$this->_locales = array();
			}
		}

		return $this->_locales;
	}

	/**
	 * Sets the section's locale models.
	 *
	 * @param array $locales
	 *
	 * @return null
	 */
	public function setLocales($locales)
	{
		$this->_locales = $locales;
	}

	// Protected Methods
	// =========================================================================

	/**
	 * @inheritDoc BaseModel::defineAttributes()
	 *
	 * @return array
	 */
	protected function defineAttributes()
	{
		return array(
			'id'            => AttributeType::Number,
			'structureId'   => AttributeType::Number,
			'fieldLayoutId' => AttributeType::Number,
			'name'          => AttributeType::String,
			'handle'        => AttributeType::String,
			'hasUrls'       => array(AttributeType::Bool, 'default' => true),
			'template'      => AttributeType::String,
			'maxLevels'     => AttributeType::Number,
		);
	}
}


text:
//
// Copyright (c) 2015 IronCore Labs
//
package com.ironcorelabs.davenport.db

import argonaut._, Argonaut._
import scalaz.syntax.either._

/**
 * A document that's either destined to be put into the DB or came out of the DB.
 * Key - The key where the document is stored.
 * commitVersion - The CommitVersion of the current document
 * data - The data stored in the document, typically RawJsonString when it comes out of the DB.
 */
final case class DBDocument[A](key: Key, commitVersion: CommitVersion, data: A) {
  def map[B](f: A => B): DBDocument[B] = DBDocument(key, commitVersion, f(data))
}

final object DBDocument {
  import scalaz.{ Functor, Equal }
  import scalaz.std.string._
  import scalaz.std.anyVal._
  implicit val instance: Functor[DBDocument] = new Functor[DBDocument] {
    def map[A, B](fa: DBDocument[A])(f: A => B): DBDocument[B] = fa.map(f)
  }

  implicit def dbDocumentEqual[A](implicit aEq: Equal[A]): Equal[DBDocument[A]] = new Equal[DBDocument[A]] {
    override def equalIsNatural: Boolean = aEq.equalIsNatural

    override def equal(doc1: DBDocument[A], doc2: DBDocument[A]): Boolean = (doc1, doc2) match {
      case (DBDocument(key1, commitVersion1, a1), DBDocument(key2, commitVersion2, a2)) =>
        aEq.equal(a1, a2) && Equal[String].equal(key1.value, key2.value) &&
          Equal[Long].equal(commitVersion1.value, commitVersion2.value)
    }
  }

  /**
   * Create a document out of `t` using `codec` and store it at `key`.
   */
  def create[T](key: Key, t: T)(implicit codec: EncodeJson[T]): DBProg[DBDocument[T]] =
    createDoc(key, RawJsonString(t.asJson.nospaces)).map(_.map(_ => t))

  /**
   * Fetch a document from the datastore and decode it using `codec`
   * If deserialization fails the DBProg will result in a left disjunction.
   */
  def get[T](k: Key)(implicit codec: DecodeJson[T]): DBProg[DBDocument[T]] = for {
    s <- getDoc(k)
    decodedValue = s.data.value.decodeWithMessage({ t: T => t.right }, DeserializationError(k, _).left)
    v <- liftDisjunction(decodedValue)
  } yield DBDocument(k, s.commitVersion, v)

  /**
   * A short way to get and update by running the data through `f`.
   */
  def modify[T](k: Key, f: T => T)(implicit codec: CodecJson[T]): DBProg[DBDocument[T]] = for {
    v <- get(k)(codec)
    result <- update(v.map(f))
  } yield result

  /**
   * Update the document to a new value.
   */
  def update[T](doc: DBDocument[T])(implicit codec: EncodeJson[T]): DBProg[DBDocument[T]] =
    updateDoc(doc.key, RawJsonString(doc.data.asJson.toString), doc.commitVersion).
      map(newDoc => newDoc.map(_ => doc.data))

  /**
   * Remove the document stored at key `key`
   */
  def remove(key: Key): DBProg[Unit] = removeKey(key)
}


text:
package org.apache.activemq.spring;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.BeanNameAware;

/**
 * A Spring enhanced connection
 * factory which will automatically use the Spring bean name as the clientIDPrefix property
 * so that connections created have client IDs related to your Spring.xml file for
 * easier comprehension from JMX.
 *
 * @org.apache.xbean.XBean element="connectionFactory"
 *
 *
 */
public class ActiveMQConnectionFactory extends org.apache.activemq.ActiveMQConnectionFactory implements BeanNameAware {

    private String beanName;
    private boolean useBeanNameAsClientIdPrefix;

    /**
     * JSR-250 callback wrapper; converts checked exceptions to runtime exceptions
     *
     * delegates to afterPropertiesSet, done to prevent backwards incompatible signature change.
     */
    @PostConstruct
    private void postConstruct() {
        try {
            afterPropertiesSet();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * @throws Exception
     * @org.apache.xbean.InitMethod
     */
    public void afterPropertiesSet() throws Exception {
        if (isUseBeanNameAsClientIdPrefix() && getClientIDPrefix() == null) {
            setClientIDPrefix(getBeanName());
        }
    }

    public String getBeanName() {
        return beanName;
    }

    @Override
    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public boolean isUseBeanNameAsClientIdPrefix() {
        return useBeanNameAsClientIdPrefix;
    }

    public void setUseBeanNameAsClientIdPrefix(boolean useBeanNameAsClientIdPrefix) {
        this.useBeanNameAsClientIdPrefix = useBeanNameAsClientIdPrefix;
    }
}


text:
package org.broadleafcommerce.core.web.catalog;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.util.BLCSystemProperty;
import org.broadleafcommerce.common.web.BLCAbstractHandlerMapping;
import org.broadleafcommerce.common.web.BroadleafRequestContext;
import org.broadleafcommerce.core.catalog.domain.Category;
import org.broadleafcommerce.core.catalog.service.CatalogService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * This handler mapping works with the Category entity to determine if a category has been configured for
 * the passed in URL.
 *
 * If the URL matches a valid Category then this mapping returns the handler configured via the
 * controllerName property or blCategoryController by default.
 *
 * @author bpolster
 * @since 2.0
 * @see org.broadleafcommerce.core.catalog.domain.Category
 * @see CataService
 */
public class CategoryHandlerMapping extends BLCAbstractHandlerMapping {

    private static final Log LOG = LogFactory.getLog(CategoryHandlerMapping.class);

    private String controllerName = "blCategoryController";

    protected String defaultTemplateName = "catalog/category";

    @Resource(name = "blCatalogService")
    private CatalogService catalogService;

    public static final String CURRENT_CATEGORY_ATTRIBUTE_NAME = "category";

    @Value("${request.uri.encoding}")
    public String charEncoding;

    @Override
    protected Object getHandlerInternal(HttpServletRequest request)
            throws Exception {
        BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();

        if (context != null) {
            Category category = null;
            if (allowCategoryResolutionUsingIdParam()) {
                category = findCategoryUsingIdParam(context);
            }

            if (category == null) {
                category = findCategoryUsingUrl(context);
            }

            if (category != null) {
                context.getRequest().setAttribute(CURRENT_CATEGORY_ATTRIBUTE_NAME, category);
                return controllerName;
            }

        }
        return null;
    }

    public String getDefaultTemplateName() {
        return defaultTemplateName;
    }

    public void setDefaultTemplateName(String defaultTemplateName) {
        this.defaultTemplateName = defaultTemplateName;
    }

    protected Category findCategoryUsingIdParam(BroadleafRequestContext context) throws ServletRequestBindingException {
        Long categoryId = ServletRequestUtils.getLongParameter(context.getRequest(), "categoryId");
        if (categoryId != null) {
            Category category = catalogService.findCategoryById(categoryId);
            if (category != null && LOG.isDebugEnabled()) {
                LOG.debug("Obtained the category using ID=" + categoryId);
            }
            return category;
        }
        return null;
    }

    protected Category findCategoryUsingUrl(BroadleafRequestContext context)
            throws ServletRequestBindingException, UnsupportedEncodingException {
        String requestUri = URLDecoder.decode(context.getRequestURIWithoutContext(), charEncoding);
        Category category = catalogService.findCategoryByURI(requestUri);
        if (category != null && LOG.isDebugEnabled()) {
            LOG.debug("Obtained the category using URI=" + requestUri);
        }
        return category;
    }

    public boolean allowCategoryResolutionUsingIdParam() {
        return BLCSystemProperty.resolveBooleanSystemProperty("allowCategoryResolutionUsingIdParam");
    }
}


text:
Framework scraper plugin for Webuilder/RapidPHP 2016
====================================================

This is Framework Scraper plugin for following editors:

Webuilder: http://www.webuilderapp.com/ <br>
RapidPHP: http://www.rapidphpeditor.com/

Scrapes data for auto-complete and object browser from documentation
of frameworks.

Supports following frameworks:

  - WordPress
  - Zend Framework
  - CakePHP
  - Laravel
  - Yii

Also scrapes PHP built-in documentation.

Development guide
=================

## Basic principles

The main steps of scraping process are:
  1. Load URL in browser
  2. Evaluate the specified JavaScript file (scraper), that
    1. Processes DOM of loaded document
    2. Sends scraped data to plugin
    3. Sends additional URL(s) to scrape and corresponding scraper names to plugin

Most often you will need to traverse multiple URLs to fully scrape all documentation of the framework. You might have list of classes in one URL, then each class in another URL and so on. The basic idea is to write a separate scraper for class list, another scraper for the class and so on.

It's worth to note that although main plugin script (script.js) is written in JScript, the scrapers are written in JavaScript.

Examine existing scrapers (e.g zend_class_list.js and zend_class.js) to get an idea how they work.

## Notes about supported frameworks

Unlike other frameworks, Zend Framework and PHP documentation are scanned from localhost, so you need to download the documentation before you can scan it.

Zend Framework documentation. Download from https://packages.zendframework.com/releases/ZendFramework-2.3.1/ZendFramework-2.3.1-apidoc.zip and extract to http://localhost/ZendFramework-2.3.1-apidoc/

PHP documentation. Download from http://www.php.net/distributions/manual/php_manual_en.tar.gz and extract to http://localhost/php-chunked-xhtml/

## Adding a new framework of your choice

Add new procedures for processing your Framework:

```
function Scrape<FRAMEWORK_NAME_HERE>(Sender) {
  LibName = "<FRAMEWORK_NAME_HERE>";

  AutoCompleteLibrary.DeleteLibrary(LibName);
  AutoCompleteLibrary.AddPHPLibrary(LibName);

  UrlQueue.Add("<URL to framework documentation>");
  ScriptQueue.Add("<name of new scraper.js>");

  CreateWebkit(&DoStartScraping);

}

function Delete<FRAMEWORK_NAME_HERE>(Sender) {
  AutoCompleteLibrary.DeleteLibrary("<FRAMEWORK_NAME_HERE>");
}
```

Add new actions for menu:

```
Script.RegisterAction("Scrape Frameworks", "Scrape <FRAMEWORK_NAME_HERE>", "", &Scrape<FRAMEWORK_NAME_HERE>);
Script.RegisterAction("Scrape Frameworks", "Delete <FRAMEWORK_NAME_HERE>", "", &Delete<FRAMEWORK_NAME_HERE>);
```

Create new JavaScript file that will be the scraper. You might want to use jQuery for scraping. Sometimes documentation will have included by default, if not the plugin will do it for you.
If jQuery is included in the documentation documents by default, your scraper can start the work right away. Otherwise you need to use a special event:

```
jquery_script.onload = function() {

  ... scraper code here...

}
```

Don't forget to restart the editor after scraping to have all new scraped classes, class attributes and functions available in auto-complete and Language Browser.

## Sample scraper

This scraper traverses all Anchor elements containing class "function" and tells plugin that URLs in the href must be scraped using scraper some_scraper_name.js.

```
jQuery('a.function').each(function(i) {
    WeBuilderExtract("some_scraper_name.js", this.href);
  });
```

## Functions that can be used in scrapers

**WeBuilderExtract**(scraper, url) - Load the specified URL and evaluate the specified scraper JavaScript file.
```
WeBuilderExtract("some_scraper.js", this.href.trim());
```

**WeBuilderAddClass**(class_name, description, inherits) - Add class to auto-complete. You can leave "inherits" empty or if the class inherits any attributes from the parent class, specify them in following format: "ParentClassName::$attr,...,method(),..." or "ParentClassName::$attr,...,method(),...;ParentClassName2::...".
```
WeBuilderAddClass("Model", "Object-relational mapper.", "")
```

**WeBuilderAddMethod**(class_name, funcname, funcargs, result_type, description, is_static) - Add class method to auto-complete.
```
WeBuilderAddMethod("Model", "delete", "( integer $id = null , boolean $cascade = true )", "boolean", "Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.", false)
```

**WeBuilderAddProperty**(class_name, fieldname, fieldtype, description, is_static) - Add class property to auto-complete.
```
WeBuilderAddProperty("Model", "$data", "array", "Container for the data that this model gets from persistent storage (usually, a database).", false)
```

**WeBuilderAddFunction**(funcname, funcargs, result_type, description) - Add function to auto-complete.
```
WeBuilderAddFunction("clearCache", "(string $params = null, string $type = 'views', string $ext = '.php')", "boolean", "Used to delete files in the cache directories, or clear contents of cache directories")
```


text:
#include "config.h"
#include "core/html/TimeInputType.h"

#include "HTMLNames.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/InputTypeNames.h"
#include "core/platform/DateComponents.h"
#include <wtf/CurrentTime.h>
#include <wtf/DateMath.h>
#include <wtf/MathExtras.h>
#include <wtf/PassOwnPtr.h>

#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
#include "core/html/DateTimeFieldsState.h"
#include "core/platform/text/PlatformLocale.h"
#include <wtf/text/WTFString.h>
#endif

namespace WebCore {

using namespace HTMLNames;

static const int timeDefaultStep = 60;
static const int timeDefaultStepBase = 0;
static const int timeStepScaleFactor = 1000;

TimeInputType::TimeInputType(HTMLInputElement*  element)
    : BaseTimeInputType(element)
{
}

PassOwnPtr<InputType> TimeInputType::create(HTMLInputElement* element)
{
    return adoptPtr(new TimeInputType(element));
}

void TimeInputType::attach()
{
    observeFeatureIfVisible(UseCounter::InputTypeTime);
}

const AtomicString& TimeInputType::formControlType() const
{
    return InputTypeNames::time();
}

DateComponents::Type TimeInputType::dateType() const
{
    return DateComponents::Time;
}

Decimal TimeInputType::defaultValueForStepUp() const
{
    double current = currentTimeMS();
    double utcOffset = calculateUTCOffset();
    double dstOffset = calculateDSTOffset(current, utcOffset);
    int offset = static_cast<int>((utcOffset + dstOffset) / msPerMinute);
    current += offset * msPerMinute;

    DateComponents date;
    date.setMillisecondsSinceMidnight(current);
    double milliseconds = date.millisecondsSinceEpoch();
    ASSERT(std::isfinite(milliseconds));
    return Decimal::fromDouble(milliseconds);
}

StepRange TimeInputType::createStepRange(AnyStepHandling anyStepHandling) const
{
    DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (timeDefaultStep, timeDefaultStepBase, timeStepScaleFactor, StepRange::ScaledStepValueShouldBeInteger));

    const Decimal stepBase = parseToNumber(element()->fastGetAttribute(minAttr), 0);
    const Decimal minimum = parseToNumber(element()->fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumTime()));
    const Decimal maximum = parseToNumber(element()->fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumTime()));
    const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element()->fastGetAttribute(stepAttr));
    return StepRange(stepBase, minimum, maximum, step, stepDescription);
}

bool TimeInputType::parseToDateComponentsInternal(const UChar* characters, unsigned length, DateComponents* out) const
{
    ASSERT(out);
    unsigned end;
    return out->parseTime(characters, length, 0, end) && end == length;
}

bool TimeInputType::setMillisecondToDateComponents(double value, DateComponents* date) const
{
    ASSERT(date);
    return date->setMillisecondsSinceMidnight(value);
}

bool TimeInputType::isTimeField() const
{
    return true;
}

#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)

String TimeInputType::localizeValue(const String& proposedValue) const
{
    DateComponents date;
    if (!parseToDateComponents(proposedValue, &date))
        return proposedValue;

    Locale::FormatType formatType = shouldHaveSecondField(date) ? Locale::FormatTypeMedium : Locale::FormatTypeShort;

    String localized = element()->locale().formatDateTime(date, formatType);
    return localized.isEmpty() ? proposedValue : localized;
}

String TimeInputType::formatDateTimeFieldsState(const DateTimeFieldsState& dateTimeFieldsState) const
{
    if (!dateTimeFieldsState.hasHour() || !dateTimeFieldsState.hasMinute() || !dateTimeFieldsState.hasAMPM())
        return emptyString();
    if (dateTimeFieldsState.hasMillisecond() && dateTimeFieldsState.millisecond())
        return String::format("%02u:%02u:%02u.%03u",
                dateTimeFieldsState.hour23(),
                dateTimeFieldsState.minute(),
                dateTimeFieldsState.hasSecond() ? dateTimeFieldsState.second() : 0,
                dateTimeFieldsState.millisecond());
    if (dateTimeFieldsState.hasSecond() && dateTimeFieldsState.second())
        return String::format("%02u:%02u:%02u",
                dateTimeFieldsState.hour23(),
                dateTimeFieldsState.minute(),
                dateTimeFieldsState.second());
    return String::format("%02u:%02u", dateTimeFieldsState.hour23(), dateTimeFieldsState.minute());
}

void TimeInputType::setupLayoutParameters(DateTimeEditElement::LayoutParameters& layoutParameters, const DateComponents& date) const
{
    if (shouldHaveSecondField(date)) {
        layoutParameters.dateTimeFormat = layoutParameters.locale.timeFormat();
        layoutParameters.fallbackDateTimeFormat = "HH:mm:ss";
    } else {
        layoutParameters.dateTimeFormat = layoutParameters.locale.shortTimeFormat();
        layoutParameters.fallbackDateTimeFormat = "HH:mm";
    }
    if (!parseToDateComponents(element()->fastGetAttribute(minAttr), &layoutParameters.minimum))
        layoutParameters.minimum = DateComponents();
    if (!parseToDateComponents(element()->fastGetAttribute(maxAttr), &layoutParameters.maximum))
        layoutParameters.maximum = DateComponents();
}

bool TimeInputType::isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const
{
    return hasHour && hasMinute && hasAMPM;
}
#endif

} // namespace WebCore


text:
import socket
import sys
import logging

from PyQt5.QtCore import QThread, QUrl
from PyQt5.QtGui import QIcon
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication

class QFlask:
    def __init__(self, app):
        self.app = app

    def run(self, title='QFlask Application', icon=None, width=640, height=480, zoom=1, **options):
        """Runs the application in a QtWebEngineView.

        :param title: window title.
        :param icon: path to a window icon.
        :param width: initial width of the window.
        :param height: initial height of the window.
        :param zoom: zoom factor of the web content. defaults to 1.
        :param options: the options to be forwarded to the underlying
                        Werkzeug server.
        """

        # Determine free port
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('127.0.0.1', 0))
        port = sock.getsockname()[1]
        sock.close()

        logging.debug('QFlask initialized on port ' + str(port))

        # Start application and flask thread
        qApp = QApplication(sys.argv)
        fApp = FlaskThread(self.app, port, **options)
        fApp.start()

        qApp.aboutToQuit.connect(fApp.terminate)

        view = WebEngineView()
        view.load(QUrl('http://127.0.0.1:' + str(port)))

        view.resize(width, height)
        view.setZoomFactor(zoom)
        view.setWindowTitle(title)
        if icon is not None:
            view.setWindowIcon(QIcon(icon))

        view.show()

        sys.exit(qApp.exec_())

# Separate Thread for Flask
class FlaskThread(QThread):
    def __init__(self, app, port, **options):
        QThread.__init__(self)
        self.app = app
        self.port = port
        self.options = options

    def __del__(self):
        self.wait()

    def run(self):
        self.app.run(host='127.0.0.1', port=self.port, **self.options)

# Own View to suppress various events
class WebEngineView(QWebEngineView):
    def __init__(self):
        super().__init__(None)

    def dragEnterEvent(self, e):
        e.ignore()

    def dropEvent(self, e):
        e.ignore()

    def contextMenuEvent(self, e):
        pass


text:
using System;

namespace MarcelJoachimKloubert.SendNET.ComponentModel
{
    /// <summary>
    /// Defines from where a property should receive notifications.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property,
                    AllowMultiple = true,
                    Inherited = false)]
    public sealed class ReceiveNotificationFromAttribute : Attribute
    {
        #region Constructors (2)

        /// <summary>
        /// Initializes a new instance of the <see cref="ReceiveNotificationFromAttribute" /> class.
        /// </summary>
        /// <param name="senderName">
        /// The value for the <see cref="ReceiveNotificationFromAttribute.SenderName" /> property.
        /// </param>
        /// <exception cref="ArgumentException">
        /// <paramref name="senderName" /> is invalid.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="senderName" /> is <see langword="null" />.
        /// </exception>
        public ReceiveNotificationFromAttribute(string senderName)
        {
            if (senderName == null)
            {
                throw new ArgumentNullException("senderName");
            }

            senderName = senderName.Trim();
            if (senderName == string.Empty)
            {
                throw new ArgumentException("senderName");
            }

            this.SenderName = senderName;
        }

        #endregion Constructors

        #region Properties (1)

        /// <summary>
        /// Gets the name of sender / sending member of the notification.
        /// </summary>
        public string SenderName
        {
            get;
            private set;
        }

        #endregion Properties
    }
}