text:
/**
 * @file video.js
 */
import window from 'global/window';
import document from 'global/document';
import * as setup from './setup';
import * as stylesheet from './utils/stylesheet.js';
import Component from './component';
import EventTarget from './event-target';
import * as Events from './utils/events.js';
import Player from './player';
import plugin from './plugins.js';
import mergeOptions from '../../src/js/utils/merge-options.js';
import * as Fn from './utils/fn.js';
import TextTrack from './tracks/text-track.js';
import AudioTrack from './tracks/audio-track.js';
import VideoTrack from './tracks/video-track.js';

import { createTimeRanges } from './utils/time-ranges.js';
import formatTime from './utils/format-time.js';
import log from './utils/log.js';
import * as Dom from './utils/dom.js';
import * as browser from './utils/browser.js';
import * as Url from './utils/url.js';
import extendFn from './extend.js';
import merge from 'lodash-compat/object/merge';
import xhr from 'xhr';

// Include the built-in techs
import Tech from './tech/tech.js';
import Html5 from './tech/html5.js';
import Flash from './tech/flash.js';

// HTML5 Element Shim for IE8
if (typeof HTMLVideoElement === 'undefined') {
  document.createElement('video');
  document.createElement('audio');
  document.createElement('track');
}

/**
 * Doubles as the main function for users to create a player instance and also
 * the main library object.
 * The `videojs` function can be used to initialize or retrieve a player.
 * ```js
 *     var myPlayer = videojs('my_video_id');
 * ```
 *
 * @param  {String|Element} id      Video element or video element ID
 * @param  {Object=} options        Optional options object for config/settings
 * @param  {Function=} ready        Optional ready callback
 * @return {Player}                 A player instance
 * @mixes videojs
 * @method videojs
 */
function videojs(id, options, ready){
  let tag; // Element of ID

  // Allow for element or ID to be passed in
  // String ID
  if (typeof id === 'string') {

    // Adjust for jQuery ID syntax
    if (id.indexOf('#') === 0) {
      id = id.slice(1);
    }

    // If a player instance has already been created for this ID return it.
    if (videojs.getPlayers()[id]) {

      // If options or ready funtion are passed, warn
      if (options) {
        log.warn(`Player "${id}" is already initialised. Options will not be applied.`);
      }

      if (ready) {
        videojs.getPlayers()[id].ready(ready);
      }

      return videojs.getPlayers()[id];

    // Otherwise get element for ID
    } else {
      tag = Dom.getEl(id);
    }

  // ID is a media element
  } else {
    tag = id;
  }

  // Check for a useable element
  if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also
    throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns
  }

  // Element may have a player attr referring to an already created player instance.
  // If not, set up a new player and return the instance.
  return tag['player'] || Player.players[tag.playerId] || new Player(tag, options, ready);
}

// Add default styles
if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  let style = Dom.$('.vjs-styles-defaults');

  if (!style) {
    style = stylesheet.createStyleElement('vjs-styles-defaults');
    let head = Dom.$('head');
    head.insertBefore(style, head.firstChild);
    stylesheet.setTextContent(style, `
      .video-js {
        width: 300px;
        height: 150px;
      }

      .vjs-fluid {
        padding-top: 56.25%
      }
    `);
  }
}

// Run Auto-load players
// You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version)
setup.autoSetupTimeout(1, videojs);

/*
 * Current software version (semver)
 *
 * @type {String}
 */
videojs.VERSION = '__VERSION__';

/**
 * The global options object. These are the settings that take effect
 * if no overrides are specified when the player is created.
 *
 * ```js
 *     videojs.options.autoplay = true
 *     // -> all players will autoplay by default
 * ```
 *
 * @type {Object}
 */
videojs.options = Player.prototype.options_;

/**
 * Get an object with the currently created players, keyed by player ID
 *
 * @return {Object} The created players
 * @mixes videojs
 * @method getPlayers
 */
videojs.getPlayers = () => Player.players;

/**
 * Expose players object.
 *
 * @memberOf videojs
 * @property {Object} players
 */
videojs.players = Player.players;

/**
 * Get a component class object by name
 * ```js
 *     var VjsButton = videojs.getComponent('Button');
 *     // Create a new instance of the component
 *     var myButton = new VjsButton(myPlayer);
 * ```
 *
 * @return {Component} Component identified by name
 * @mixes videojs
 * @method getComponent
 */
videojs.getComponent = Component.getComponent;

/**
 * Register a component so it can referred to by name
 * Used when adding to other
 * components, either through addChild
 * `component.addChild('myComponent')`
 * or through default children options
 * `{ children: ['myComponent'] }`.
 * ```js
 *     // Get a component to subclass
 *     var VjsButton = videojs.getComponent('Button');
 *     // Subclass the component (see 'extend' doc for more info)
 *     var MySpecialButton = videojs.extend(VjsButton, {});
 *     // Register the new component
 *     VjsButton.registerComponent('MySepcialButton', MySepcialButton);
 *     // (optionally) add the new component as a default player child
 *     myPlayer.addChild('MySepcialButton');
 * ```
 * NOTE: You could also just initialize the component before adding.
 * `component.addChild(new MyComponent());`
 *
 * @param {String} The class name of the component
 * @param {Component} The component class
 * @return {Component} The newly registered component
 * @mixes videojs
 * @method registerComponent
 */
videojs.registerComponent = (name, comp) => {
  if (Tech.isTech(comp)) {
    log.warn(`The ${name} tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)`);
  }

  Component.registerComponent.call(Component, name, comp);
};

/**
 * Get a Tech class object by name
 * ```js
 *     var Html5 = videojs.getTech('Html5');
 *     // Create a new instance of the component
 *     var html5 = new Html5(options);
 * ```
 *
 * @return {Tech} Tech identified by name
 * @mixes videojs
 * @method getComponent
 */
videojs.getTech = Tech.getTech;

/**
 * Register a Tech so it can referred to by name.
 * This is used in the tech order for the player.
 *
 * ```js
 *     // get the Html5 Tech
 *     var Html5 = videojs.getTech('Html5');
 *     var MyTech = videojs.extend(Html5, {});
 *     // Register the new Tech
 *     VjsButton.registerTech('Tech', MyTech);
 *     var player = videojs('myplayer', {
 *       techOrder: ['myTech', 'html5']
 *     });
 * ```
 *
 * @param {String} The class name of the tech
 * @param {Tech} The tech class
 * @return {Tech} The newly registered Tech
 * @mixes videojs
 * @method registerTech
 */
videojs.registerTech = Tech.registerTech;

/**
 * A suite of browser and device tests
 *
 * @type {Object}
 * @private
 */
videojs.browser = browser;

/**
 * Whether or not the browser supports touch events. Included for backward
 * compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED`
 * instead going forward.
 *
 * @deprecated
 * @type {Boolean}
 */
videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED;

/**
 * Subclass an existing class
 * Mimics ES6 subclassing with the `extend` keyword
 * ```js
 *     // Create a basic javascript 'class'
 *     function MyClass(name){
 *       // Set a property at initialization
 *       this.myName = name;
 *     }
 *     // Create an instance method
 *     MyClass.prototype.sayMyName = function(){
 *       alert(this.myName);
 *     };
 *     // Subclass the exisitng class and change the name
 *     // when initializing
 *     var MySubClass = videojs.extend(MyClass, {
 *       constructor: function(name) {
 *         // Call the super class constructor for the subclass
 *         MyClass.call(this, name)
 *       }
 *     });
 *     // Create an instance of the new sub class
 *     var myInstance = new MySubClass('John');
 *     myInstance.sayMyName(); // -> should alert "John"
 * ```
 *
 * @param {Function} The Class to subclass
 * @param {Object} An object including instace methods for the new class
 *                   Optionally including a `constructor` function
 * @return {Function} The newly created subclass
 * @mixes videojs
 * @method extend
 */
videojs.extend = extendFn;

/**
 * Merge two options objects recursively
 * Performs a deep merge like lodash.merge but **only merges plain objects**
 * (not arrays, elements, anything else)
 * Other values will be copied directly from the second object.
 * ```js
 *     var defaultOptions = {
 *       foo: true,
 *       bar: {
 *         a: true,
 *         b: [1,2,3]
 *       }
 *     };
 *     var newOptions = {
 *       foo: false,
 *       bar: {
 *         b: [4,5,6]
 *       }
 *     };
 *     var result = videojs.mergeOptions(defaultOptions, newOptions);
 *     // result.foo = false;
 *     // result.bar.a = true;
 *     // result.bar.b = [4,5,6];
 * ```
 *
 * @param {Object} defaults  The options object whose values will be overriden
 * @param {Object} overrides The options object with values to override the first
 * @param {Object} etc       Any number of additional options objects
 *
 * @return {Object} a new object with the merged values
 * @mixes videojs
 * @method mergeOptions
 */
videojs.mergeOptions = mergeOptions;

/**
 * Change the context (this) of a function
 *
 *     videojs.bind(newContext, function(){
 *       this === newContext
 *     });
 *
 * NOTE: as of v5.0 we require an ES5 shim, so you should use the native
 * `function(){}.bind(newContext);` instead of this.
 *
 * @param  {*}        context The object to bind as scope
 * @param  {Function} fn      The function to be bound to a scope
 * @param  {Number=}  uid     An optional unique ID for the function to be set
 * @return {Function}
 */
videojs.bind = Fn.bind;

/**
 * Create a Video.js player plugin
 * Plugins are only initialized when options for the plugin are included
 * in the player options, or the plugin function on the player instance is
 * called.
 * **See the plugin guide in the docs for a more detailed example**
 * ```js
 *     // Make a plugin that alerts when the player plays
 *     videojs.plugin('myPlugin', function(myPluginOptions) {
 *       myPluginOptions = myPluginOptions || {};
 *
 *       var player = this;
 *       var alertText = myPluginOptions.text || 'Player is playing!'
 *
 *       player.on('play', function(){
 *         alert(alertText);
 *       });
 *     });
 *     // USAGE EXAMPLES
 *     // EXAMPLE 1: New player with plugin options, call plugin immediately
 *     var player1 = videojs('idOne', {
 *       myPlugin: {
 *         text: 'Custom text!'
 *       }
 *     });
 *     // Click play
 *     // --> Should alert 'Custom text!'
 *     // EXAMPLE 3: New player, initialize plugin later
 *     var player3 = videojs('idThree');
 *     // Click play
 *     // --> NO ALERT
 *     // Click pause
 *     // Initialize plugin using the plugin function on the player instance
 *     player3.myPlugin({
 *       text: 'Plugin added later!'
 *     });
 *     // Click play
 *     // --> Should alert 'Plugin added later!'
 * ```
 *
 * @param {String} name The plugin name
 * @param {Function} fn The plugin function that will be called with options
 * @mixes videojs
 * @method plugin
 */
videojs.plugin = plugin;

/**
 * Adding languages so that they're available to all players.
 * ```js
 *     videojs.addLanguage('es', { 'Hello': 'Hola' });
 * ```
 *
 * @param  {String} code The language code or dictionary property
 * @param  {Object} data The data values to be translated
 * @return {Object} The resulting language dictionary object
 * @mixes videojs
 * @method addLanguage
 */
videojs.addLanguage = function(code, data){
  code = ('' + code).toLowerCase();
  return merge(videojs.options.languages, { [code]: data })[code];
};

/**
 * Log debug messages.
 *
 * @param {...Object} messages One or more messages to log
 */
videojs.log = log;

/**
 * Creates an emulated TimeRange object.
 *
 * @param  {Number|Array} start Start time in seconds or an array of ranges
 * @param  {Number} end   End time in seconds
 * @return {Object}       Fake TimeRange object
 * @method createTimeRange
 */
videojs.createTimeRange = videojs.createTimeRanges = createTimeRanges;

/**
 * Format seconds as a time string, H:MM:SS or M:SS
 * Supplying a guide (in seconds) will force a number of leading zeros
 * to cover the length of the guide
 *
 * @param  {Number} seconds Number of seconds to be turned into a string
 * @param  {Number} guide   Number (in seconds) to model the string after
 * @return {String}         Time formatted as H:MM:SS or M:SS
 * @method formatTime
 */
videojs.formatTime = formatTime;

/**
 * Resolve and parse the elements of a URL
 *
 * @param  {String} url The url to parse
 * @return {Object}     An object of url details
 * @method parseUrl
 */
videojs.parseUrl = Url.parseUrl;

/**
 * Returns whether the url passed is a cross domain request or not.
 *
 * @param {String} url The url to check
 * @return {Boolean}   Whether it is a cross domain request or not
 * @method isCrossOrigin
 */
videojs.isCrossOrigin = Url.isCrossOrigin;

/**
 * Event target class.
 *
 * @type {Function}
 */
videojs.EventTarget = EventTarget;

/**
 * Add an event listener to element
 * It stores the handler function in a separate cache object
 * and adds a generic handler to the element's event,
 * along with a unique id (guid) to the element.
 *
 * @param  {Element|Object}   elem Element or object to bind listeners to
 * @param  {String|Array}   type Type of event to bind to.
 * @param  {Function} fn   Event listener.
 * @method on
 */
videojs.on = Events.on;

/**
 * Trigger a listener only once for an event
 *
 * @param  {Element|Object}   elem Element or object to
 * @param  {String|Array}   type Name/type of event
 * @param  {Function} fn Event handler function
 * @method one
 */
videojs.one = Events.one;

/**
 * Removes event listeners from an element
 *
 * @param  {Element|Object}   elem Object to remove listeners from
 * @param  {String|Array=}   type Type of listener to remove. Don't include to remove all events from element.
 * @param  {Function} fn   Specific listener to remove. Don't include to remove listeners for an event type.
 * @method off
 */
videojs.off = Events.off;

/**
 * Trigger an event for an element
 *
 * @param  {Element|Object}      elem  Element to trigger an event on
 * @param  {Event|Object|String} event A string (the type) or an event object with a type attribute
 * @param  {Object} [hash] data hash to pass along with the event
 * @return {Boolean=} Returned only if default was prevented
 * @method trigger
 */
videojs.trigger = Events.trigger;

/**
 * A cross-browser XMLHttpRequest wrapper. Here's a simple example:
 *
 *     videojs.xhr({
 *       body: someJSONString,
 *       uri: "/foo",
 *       headers: {
 *         "Content-Type": "application/json"
 *       }
 *     }, function (err, resp, body) {
 *       // check resp.statusCode
 *     });
 *
 * Check out the [full
 * documentation](https://github.com/Raynos/xhr/blob/v2.1.0/README.md)
 * for more options.
 *
 * @param {Object} options settings for the request.
 * @return {XMLHttpRequest|XDomainRequest} the request object.
 * @see https://github.com/Raynos/xhr
 */
videojs.xhr = xhr;

/**
 * TextTrack class
 *
 * @type {Function}
 */
videojs.TextTrack = TextTrack;

/**
 * export the AudioTrack class so that source handlers can create
 * AudioTracks and then add them to the players AudioTrackList
 *
 * @type {Function}
 */
videojs.AudioTrack = AudioTrack;

/**
 * export the VideoTrack class so that source handlers can create
 * VideoTracks and then add them to the players VideoTrackList
 *
 * @type {Function}
 */
videojs.VideoTrack = VideoTrack;

/**
 * Determines, via duck typing, whether or not a value is a DOM element.
 *
 * @method isEl
 * @param  {Mixed} value
 * @return {Boolean}
 */
videojs.isEl = Dom.isEl;

/**
 * Determines, via duck typing, whether or not a value is a text node.
 *
 * @method isTextNode
 * @param  {Mixed} value
 * @return {Boolean}
 */
videojs.isTextNode = Dom.isTextNode;

/**
 * Creates an element and applies properties.
 *
 * @method createEl
 * @param  {String} [tagName='div'] Name of tag to be created.
 * @param  {Object} [properties={}] Element properties to be applied.
 * @param  {Object} [attributes={}] Element attributes to be applied.
 * @return {Element}
 */
videojs.createEl = Dom.createEl;

/**
 * Check if an element has a CSS class
 *
 * @method hasClass
 * @param {Element} element Element to check
 * @param {String} classToCheck Classname to check
 */
videojs.hasClass = Dom.hasElClass;

/**
 * Add a CSS class name to an element
 *
 * @method addClass
 * @param {Element} element    Element to add class name to
 * @param {String} classToAdd Classname to add
 */
videojs.addClass = Dom.addElClass;

/**
 * Remove a CSS class name from an element
 *
 * @method removeClass
 * @param {Element} element    Element to remove from class name
 * @param {String} classToRemove Classname to remove
 */
videojs.removeClass = Dom.removeElClass;

/**
 * Adds or removes a CSS class name on an element depending on an optional
 * condition or the presence/absence of the class name.
 *
 * @method toggleElClass
 * @param  {Element} element
 * @param  {String} classToToggle
 * @param  {Boolean|Function} [predicate]
 *         Can be a function that returns a Boolean. If `true`, the class
 *         will be added; if `false`, the class will be removed. If not
 *         given, the class will be added if not present and vice versa.
 */
videojs.toggleClass = Dom.toggleElClass;

/**
 * Apply attributes to an HTML element.
 *
 * @method setAttributes
 * @param  {Element} el         Target element.
 * @param  {Object=} attributes Element attributes to be applied.
 */
videojs.setAttributes = Dom.setElAttributes;

/**
 * Get an element's attribute values, as defined on the HTML tag
 * Attributes are not the same as properties. They're defined on the tag
 * or with setAttribute (which shouldn't be used with HTML)
 * This will return true or false for boolean attributes.
 *
 * @method getAttributes
 * @param  {Element} tag Element from which to get tag attributes
 * @return {Object}
 */
videojs.getAttributes = Dom.getElAttributes;

/**
 * Empties the contents of an element.
 *
 * @method emptyEl
 * @param  {Element} el
 * @return {Element}
 */
videojs.emptyEl = Dom.emptyEl;

/**
 * Normalizes and appends content to an element.
 *
 * The content for an element can be passed in multiple types and
 * combinations, whose behavior is as follows:
 *
 * - String
 *   Normalized into a text node.
 *
 * - Element, TextNode
 *   Passed through.
 *
 * - Array
 *   A one-dimensional array of strings, elements, nodes, or functions (which
 *   return single strings, elements, or nodes).
 *
 * - Function
 *   If the sole argument, is expected to produce a string, element,
 *   node, or array.
 *
 * @method appendContent
 * @param  {Element} el
 * @param  {String|Element|TextNode|Array|Function} content
 * @return {Element}
 */
videojs.appendContent = Dom.appendContent;

/**
 * Normalizes and inserts content into an element; this is identical to
 * `appendContent()`, except it empties the element first.
 *
 * The content for an element can be passed in multiple types and
 * combinations, whose behavior is as follows:
 *
 * - String
 *   Normalized into a text node.
 *
 * - Element, TextNode
 *   Passed through.
 *
 * - Array
 *   A one-dimensional array of strings, elements, nodes, or functions (which
 *   return single strings, elements, or nodes).
 *
 * - Function
 *   If the sole argument, is expected to produce a string, element,
 *   node, or array.
 *
 * @method insertContent
 * @param  {Element} el
 * @param  {String|Element|TextNode|Array|Function} content
 * @return {Element}
 */
videojs.insertContent = Dom.insertContent;

/*
 * Custom Universal Module Definition (UMD)
 *
 * Video.js will never be a non-browser lib so we can simplify UMD a bunch and
 * still support requirejs and browserify. This also needs to be closure
 * compiler compatible, so string keys are used.
 */
if (typeof define === 'function' && define['amd']) {
  define('videojs', [], function(){ return videojs; });

// checking that module is an object too because of umdjs/umd#35
} else if (typeof exports === 'object' && typeof module === 'object') {
  module['exports'] = videojs;
}

export default videojs;


text:
typedef enum {
    WMLabelVerticalTextAlignmentTop = UIControlContentVerticalAlignmentTop,
    WMLabelVerticalTextAlignmentMiddle = UIControlContentVerticalAlignmentCenter,
    WMLabelVerticalTextAlignmentBottom = UIControlContentVerticalAlignmentBottom
} WMLabelVerticalTextAlignment;

@interface WMLabel : UILabel
@property (nonatomic, assign) WMLabelVerticalTextAlignment verticalTextAlignment;
@property (nonatomic, assign) UIEdgeInsets textEdgeInsets;
@property (nonatomic) WMViewBorderWidth borderWidth;
@property (nonatomic, strong) UIColor* borderColor;
@end

redpajama_set_name: RedPajamaGithub


text:
require 'databasedotcom/chatter/record'

module Databasedotcom
  module Chatter
    # A GroupMembership represents the membership of a certain User in a certain Group.
    class GroupMembership < Record
    end
  end
end


text:
module API
  module V1
    module Helpers
      def require_no_authentication
        env['api.endpoint'].namespace == '/tokens'
      end

      def authenticate_account_from_token!
        conditions = params.slice(Devise::TokenAuthenticatable.token_authentication_key)
        account = Account.find_for_token_authentication(conditions)
        if account
          env['current_account'] = account
        else
          # Insert random sleep to make token prediction more difficult by timing attack.
          sleep((200 + rand(200)) / 1000.0)
          error!('Requires valid auth_token.', 401)
        end
      end

      def find_project(subject)
        project = nil
        unless (subject.class == Class) || subject.is_a?(Audit)
          if subject.is_a?(Project)
            project = subject
          elsif !subject.is_a?(Account)
            project = subject.project
          end
        end
        project
      end

      def find_project_by_account(account, *args)
        account.projects.find do |project|
          project.id == args.pop[:project].id
        end if args.last[:project]
      end

      def create_ability(subject, *args)
        project = nil
        if args.last.is_a?(Hash) && args.last.key?(:project)
          if subject.class == Class
            project = args.pop[:project]
          elsif subject.is_a?(Account)
            project = find_project_by_account(subject, *args)
          else
            project = find_project(subject)
          end
        else
          project = find_project(subject)
        end
        Ability.new(current_account, project)
      end

      def current_project(model)
        project = nil
        model_object = nil
        model_list = { project_id: Project,
                       application_id: Application,
                       system_id: System,
                       cloud_id: Cloud,
                       blueprint_id: Blueprint,
                       assignment_id: Assignment,
                       role_id: Role,
                       id: model }
        model_list.each_key do |key|
          model_object = model_list[key].find_by_id(params[key]) if params.key?(key)
          break if model_object
        end
        if model_object.class == Project
          project = model_object
        elsif model_object
          project = model_object.project
        end
        project
      end

      def track_api(project_id)
        track_method = %w(PUT POST DELETE)
        if track_method.include?(request.request_method)
          account_id = current_account.id if current_account
          ::Audit.create!(ip: request.ip, account: account_id, status: status, request: request.url, project_id: project_id)
        end
      end

      def authorize!(action, subject, *args)
        create_ability(subject, *args).authorize!(action, subject, *args)
      end

      def can?(action, subject, *args)
        create_ability(subject, *args).can?(action, subject, *args)
      end

      def cannot?(action, subject, *args)
        create_ability(subject, *args).cannot?(action, subject, *args)
      end

      def current_ability
        ::Ability.new(current_account)
      end

      def current_account
        env['current_account']
      end

      def declared_params
        declared(params, include_missing: false).to_hash.with_indifferent_access
      end

      def permitted_params(*args)
        ActionController::Parameters.new(params.slice(*args)).permit(*args)
      end
    end
  end
end


text:
package ductive.console.commands.register.annotations;

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Cmd {

	String[] path();

	String help();

}


text:
from ikalog.scenes.scene import Scene
from ikalog.utils import *

class StatefulScene(Scene):

    def _switch_state(self, new_state):
        self._state = new_state
        IkaUtils.dprint('%s: switching to state %s' %
                        (self, new_state.__name__))

    def _state_default(self, context):
        raise Exception('Must be overrided')

    def match_no_cache(self, context):
        return self._state(context)

    def __init__(self, engine):
        super(StatefulScene, self).__init__(engine)

        self._state = self._state_default


text:
<annotation>
<folder>JPEGImages</folder>
<filename>2.jpg</filename>
<path>/home/pi/detection_dataset/JPEGImages/2.jpg</path><source>
<database>Unknown</database>
</source><size>
<width>640</width>
<height>480</height>
</size>
<object>
  <name>RBC</name>
  <pose>Unspecified</pose>
  <truncated>0</truncated>
  <difficult>0</difficult>
  <bndbox>
    <xmin>17</xmin>
    <ymin>62</ymin>
    <xmax>218</xmax>
    <ymax>357</ymax>
  </bndbox>
</object>
</annotation>


text:
#include "wtf/CryptographicallyRandomNumber.h"
#include "wtf/CurrentTime.h"
#include "wtf/Partitions.h"
#include "wtf/WTF.h"
#include <base/test/test_suite.h>
#include <string.h>

static double dummyCurrentTime()
{
    return 0.0;
}

int main(int argc, char** argv)
{
    WTF::Partitions::initialize(nullptr);
    WTF::setTimeFunctionsForTesting(dummyCurrentTime);
    WTF::initialize(nullptr);
    return base::RunUnitTestsUsingBaseTestSuite(argc, argv);
}


text:
/**
 * @file thread
 * @author zhujialu
 */
define(function (require, exports) {

    /**
     * 启用一个线程
     *
     * @param {Object} options
     * @param {string} options.type 线程类型
     * @param {number} options.unit 每次处理多少数据
     * @param {number} options.interval 时间间隔
     * @param {Array} options.data 处理的数据
     * @param {Function} options.onfinish
     * @param {Function} options.onstep
     */
    exports.start = function (options) {

        var data = options.data;
        var unit = options.unit;
        var interval = options.interval;
        var onstep = options.onstep;

        function run(index) {
            var start = index * unit;

            index++;

            var end = Math.min(index * unit, data.length);
            var part = data.slice(start, end);

            if (part.length === 0) {

                if (typeof options.onfinish === 'function') {
                    options.onfinish();
                }

                options.task = null;

                return;
            }

            if (typeof onstep === 'function') {
                onstep(part);
            }

            options.task = setTimeout(function () {
                run(index);
            }, interval);
        }

        run(0);
    };

    /**
     * 停止线程
     *
     * @param {Object} options 传入 start 的对象
     */
    exports.stop = function (options) {
        if (options.task) {
            clearTimeout(options.task);
            delete options.task;
        }
    };

});


text:
#ifndef __RTW_P2P_H_
#define __RTW_P2P_H_

#include <drv_types.h>

u32 build_beacon_p2p_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_probe_resp_p2p_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_prov_disc_request_p2p_ie(struct wifidirect_info *pwdinfo, u8 *pbuf, u8* pssid, u8 ussidlen, u8* pdev_raddr );
u32 build_assoc_resp_p2p_ie(struct wifidirect_info *pwdinfo, u8 *pbuf, u8 status_code);
u32 build_deauth_p2p_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
#ifdef CONFIG_WFD
u32 build_probe_req_wfd_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_probe_resp_wfd_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_beacon_wfd_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_nego_req_wfd_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_nego_resp_wfd_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_nego_confirm_wfd_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_assoc_req_wfd_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_assoc_resp_wfd_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_provdisc_req_wfd_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
u32 build_provdisc_resp_wfd_ie(struct wifidirect_info *pwdinfo, u8 *pbuf);
#endif //CONFIG_WFD

u32 process_probe_req_p2p_ie(struct wifidirect_info *pwdinfo, u8 *pframe, uint len);
u32 process_assoc_req_p2p_ie(struct wifidirect_info *pwdinfo, u8 *pframe, uint len, struct sta_info *psta);
u32 process_p2p_devdisc_req(struct wifidirect_info *pwdinfo, u8 *pframe, uint len);
u32 process_p2p_devdisc_resp(struct wifidirect_info *pwdinfo, u8 *pframe, uint len);
u8 process_p2p_provdisc_req(struct wifidirect_info *pwdinfo,  u8 *pframe, uint len);
u8 process_p2p_provdisc_resp(struct wifidirect_info *pwdinfo,  u8 *pframe);
u8 process_p2p_group_negotation_req( struct wifidirect_info *pwdinfo, u8 *pframe, uint len );
u8 process_p2p_group_negotation_resp( struct wifidirect_info *pwdinfo, u8 *pframe, uint len );
u8 process_p2p_group_negotation_confirm( struct wifidirect_info *pwdinfo, u8 *pframe, uint len );
u8 process_p2p_presence_req(struct wifidirect_info *pwdinfo, u8 *pframe, uint len);

void process_p2p_ps_ie(PADAPTER padapter, u8 *IEs, u32 IELength);
void p2p_ps_wk_hdl(_adapter *padapter, u8 p2p_ps_state);
void p2p_protocol_wk_hdl(_adapter *padapter, int intCmdType);
u8 p2p_ps_wk_cmd(_adapter*padapter, u8 p2p_ps_state, u8 enqueue);

#ifdef CONFIG_IOCTL_CFG80211
void rtw_init_cfg80211_wifidirect_info( _adapter*	padapter);
int rtw_p2p_check_frames(_adapter *padapter, const u8 *buf, u32 len, u8 tx);
#endif //CONFIG_IOCTL_CFG80211

void init_wifidirect_info( _adapter* padapter, enum P2P_ROLE role);
int rtw_p2p_enable(_adapter *padapter, enum P2P_ROLE role);

static inline void _rtw_p2p_set_state(struct wifidirect_info *wdinfo, enum P2P_STATE state)
{
	if(wdinfo->p2p_state != state) {
		//wdinfo->pre_p2p_state = wdinfo->p2p_state;
		wdinfo->p2p_state = state;
	}
}
static inline void _rtw_p2p_set_pre_state(struct wifidirect_info *wdinfo, enum P2P_STATE state)
{
	if(wdinfo->pre_p2p_state != state) {
		wdinfo->pre_p2p_state = state;
	}
}
#if 0
static inline void _rtw_p2p_restore_state(struct wifidirect_info *wdinfo)
{
	if(wdinfo->pre_p2p_state != -1) {
		wdinfo->p2p_state = wdinfo->pre_p2p_state;
		wdinfo->pre_p2p_state = -1;
	}
}
#endif
static inline void _rtw_p2p_set_role(struct wifidirect_info *wdinfo, enum P2P_ROLE role)
{
	if(wdinfo->role != role) {
		wdinfo->role = role;
	}
}
static inline int _rtw_p2p_state(struct wifidirect_info *wdinfo)
{
	return wdinfo->p2p_state;
}
static inline int _rtw_p2p_pre_state(struct wifidirect_info *wdinfo)
{
	return wdinfo->pre_p2p_state;
}
static inline int _rtw_p2p_role(struct wifidirect_info *wdinfo)
{
	return wdinfo->role;
}
static inline bool _rtw_p2p_chk_state(struct wifidirect_info *wdinfo, enum P2P_STATE state)
{
	return wdinfo->p2p_state == state;
}
static inline bool _rtw_p2p_chk_role(struct wifidirect_info *wdinfo, enum P2P_ROLE role)
{
	return wdinfo->role == role;
}

#ifdef CONFIG_DBG_P2P
void dbg_rtw_p2p_set_state(struct wifidirect_info *wdinfo, enum P2P_STATE state, const char *caller, int line);
void dbg_rtw_p2p_set_pre_state(struct wifidirect_info *wdinfo, enum P2P_STATE state, const char *caller, int line);
//void dbg_rtw_p2p_restore_state(struct wifidirect_info *wdinfo, const char *caller, int line);
void dbg_rtw_p2p_set_role(struct wifidirect_info *wdinfo, enum P2P_ROLE role, const char *caller, int line);
#define rtw_p2p_set_state(wdinfo, state) dbg_rtw_p2p_set_state(wdinfo, state, __FUNCTION__, __LINE__)
#define rtw_p2p_set_pre_state(wdinfo, state) dbg_rtw_p2p_set_pre_state(wdinfo, state, __FUNCTION__, __LINE__)
#define rtw_p2p_set_role(wdinfo, role) dbg_rtw_p2p_set_role(wdinfo, role, __FUNCTION__, __LINE__)
//#define rtw_p2p_restore_state(wdinfo) dbg_rtw_p2p_restore_state(wdinfo, __FUNCTION__, __LINE__)
#else //CONFIG_DBG_P2P
#define rtw_p2p_set_state(wdinfo, state) _rtw_p2p_set_state(wdinfo, state)
#define rtw_p2p_set_pre_state(wdinfo, state) _rtw_p2p_set_pre_state(wdinfo, state)
#define rtw_p2p_set_role(wdinfo, role) _rtw_p2p_set_role(wdinfo, role)
//#define rtw_p2p_restore_state(wdinfo) _rtw_p2p_restore_state(wdinfo)
#endif //CONFIG_DBG_P2P

#define rtw_p2p_state(wdinfo) _rtw_p2p_state(wdinfo)
#define rtw_p2p_pre_state(wdinfo) _rtw_p2p_pre_state(wdinfo)
#define rtw_p2p_role(wdinfo) _rtw_p2p_role(wdinfo)
#define rtw_p2p_chk_state(wdinfo, state) _rtw_p2p_chk_state(wdinfo, state)
#define rtw_p2p_chk_role(wdinfo, role) _rtw_p2p_chk_role(wdinfo, role)

#define rtw_p2p_findphase_ex_set(wdinfo, value) \
	(wdinfo)->find_phase_state_exchange_cnt = (value)

//is this find phase exchange for social channel scan?
#define rtw_p2p_findphase_ex_is_social(wdinfo)   \
	(wdinfo)->find_phase_state_exchange_cnt >= P2P_FINDPHASE_EX_SOCIAL_FIRST

//should we need find phase exchange anymore?
#define rtw_p2p_findphase_ex_is_needed(wdinfo) \
	((wdinfo)->find_phase_state_exchange_cnt < P2P_FINDPHASE_EX_MAX && \
	(wdinfo)->find_phase_state_exchange_cnt != P2P_FINDPHASE_EX_NONE)

#endif


text:
pushd cbits
autoreconf -fvi
popd


text:
require 'spec_helper'

RSpec.describe Orga::DashboardController do
  render_views

  describe '#GET index' do
    context 'without admin role' do
      it 'redirects to root patg' do
        sign_in create(:student)
        get :index
        expect(response).to redirect_to root_path
      end
    end

    context 'with admin role' do
      before do
        user = create(:supervisor)
        create(:organizer_role, user: user)
        sign_in user
        get :index
      end

      it 'renders the dashboard' do
        expect(response).to render_template :index
      end

      it 'shows link to project space' do
        expect(response.body).to include orga_projects_path
      end

      it 'shows link to teams space' do
        expect(response.body).to include orga_teams_path
      end

      it 'shows link to conferences space' do
        expect(response.body).to include orga_conferences_path
      end

      it 'shows link to seasons space' do
        expect(response.body).to include orga_seasons_path
      end

      it 'shows link to exports' do
        expect(response.body).to include orga_exports_path
      end

      it 'does not show link to rating space' do
        expect(response.body).not_to include rating_path
      end
    end
  end
end


text:
"""Constants for the motionEye integration."""
from datetime import timedelta
from typing import Final

from motioneye_client.const import (
    KEY_WEB_HOOK_CS_CAMERA_ID,
    KEY_WEB_HOOK_CS_CHANGED_PIXELS,
    KEY_WEB_HOOK_CS_DESPECKLE_LABELS,
    KEY_WEB_HOOK_CS_EVENT,
    KEY_WEB_HOOK_CS_FILE_PATH,
    KEY_WEB_HOOK_CS_FILE_TYPE,
    KEY_WEB_HOOK_CS_FPS,
    KEY_WEB_HOOK_CS_FRAME_NUMBER,
    KEY_WEB_HOOK_CS_HEIGHT,
    KEY_WEB_HOOK_CS_HOST,
    KEY_WEB_HOOK_CS_MOTION_CENTER_X,
    KEY_WEB_HOOK_CS_MOTION_CENTER_Y,
    KEY_WEB_HOOK_CS_MOTION_HEIGHT,
    KEY_WEB_HOOK_CS_MOTION_VERSION,
    KEY_WEB_HOOK_CS_MOTION_WIDTH,
    KEY_WEB_HOOK_CS_NOISE_LEVEL,
    KEY_WEB_HOOK_CS_THRESHOLD,
    KEY_WEB_HOOK_CS_WIDTH,
)

DOMAIN: Final = "motioneye"

ATTR_EVENT_TYPE: Final = "event_type"
ATTR_WEBHOOK_ID: Final = "webhook_id"

CONF_ACTION: Final = "action"
CONF_CLIENT: Final = "client"
CONF_COORDINATOR: Final = "coordinator"
CONF_ADMIN_PASSWORD: Final = "admin_password"
CONF_ADMIN_USERNAME: Final = "admin_username"
CONF_STREAM_URL_TEMPLATE: Final = "stream_url_template"
CONF_SURVEILLANCE_USERNAME: Final = "surveillance_username"
CONF_SURVEILLANCE_PASSWORD: Final = "surveillance_password"
CONF_WEBHOOK_SET: Final = "webhook_set"
CONF_WEBHOOK_SET_OVERWRITE: Final = "webhook_set_overwrite"

DEFAULT_WEBHOOK_SET: Final = True
DEFAULT_WEBHOOK_SET_OVERWRITE: Final = False
DEFAULT_SCAN_INTERVAL: Final = timedelta(seconds=30)

EVENT_MOTION_DETECTED: Final = "motion_detected"
EVENT_FILE_STORED: Final = "file_stored"

EVENT_MOTION_DETECTED_KEYS: Final = [
    KEY_WEB_HOOK_CS_EVENT,
    KEY_WEB_HOOK_CS_FRAME_NUMBER,
    KEY_WEB_HOOK_CS_CAMERA_ID,
    KEY_WEB_HOOK_CS_CHANGED_PIXELS,
    KEY_WEB_HOOK_CS_NOISE_LEVEL,
    KEY_WEB_HOOK_CS_WIDTH,
    KEY_WEB_HOOK_CS_HEIGHT,
    KEY_WEB_HOOK_CS_MOTION_WIDTH,
    KEY_WEB_HOOK_CS_MOTION_HEIGHT,
    KEY_WEB_HOOK_CS_MOTION_CENTER_X,
    KEY_WEB_HOOK_CS_MOTION_CENTER_Y,
    KEY_WEB_HOOK_CS_THRESHOLD,
    KEY_WEB_HOOK_CS_DESPECKLE_LABELS,
    KEY_WEB_HOOK_CS_FPS,
    KEY_WEB_HOOK_CS_HOST,
    KEY_WEB_HOOK_CS_MOTION_VERSION,
]

EVENT_FILE_STORED_KEYS: Final = [
    KEY_WEB_HOOK_CS_EVENT,
    KEY_WEB_HOOK_CS_FRAME_NUMBER,
    KEY_WEB_HOOK_CS_CAMERA_ID,
    KEY_WEB_HOOK_CS_NOISE_LEVEL,
    KEY_WEB_HOOK_CS_WIDTH,
    KEY_WEB_HOOK_CS_HEIGHT,
    KEY_WEB_HOOK_CS_FILE_PATH,
    KEY_WEB_HOOK_CS_FILE_TYPE,
    KEY_WEB_HOOK_CS_THRESHOLD,
    KEY_WEB_HOOK_CS_FPS,
    KEY_WEB_HOOK_CS_HOST,
    KEY_WEB_HOOK_CS_MOTION_VERSION,
]

EVENT_FILE_URL: Final = "file_url"
EVENT_MEDIA_CONTENT_ID: Final = "media_content_id"

MOTIONEYE_MANUFACTURER: Final = "motionEye"

SERVICE_SET_TEXT_OVERLAY: Final = "set_text_overlay"
SERVICE_ACTION: Final = "action"
SERVICE_SNAPSHOT: Final = "snapshot"

SIGNAL_CAMERA_ADD: Final = f"{DOMAIN}_camera_add_signal." "{}"
SIGNAL_CAMERA_REMOVE: Final = f"{DOMAIN}_camera_remove_signal." "{}"

TYPE_MOTIONEYE_ACTION_SENSOR = f"{DOMAIN}_action_sensor"
TYPE_MOTIONEYE_MJPEG_CAMERA: Final = "motioneye_mjpeg_camera"
TYPE_MOTIONEYE_SWITCH_BASE: Final = f"{DOMAIN}_switch"

WEB_HOOK_SENTINEL_KEY: Final = "src"
WEB_HOOK_SENTINEL_VALUE: Final = "hass-motioneye"


text: Pruebas para el uso de git


text:
/**
 * @fileoverview
 * Manage a callback with invocation scope. This is used internally by GameJs but might be useful for others.
 */

/**
 * @param {Function} callback
 * @param {Object} scope with which the callback will be triggered
 */
var Callback = exports.Callback = function(fn, scope) {
	this.fn = fn;
	this.fnScope = scope || {};
	return this;
};
/**
 * Any arguments passed to `trigger` will be passed to the callback.
 */
Callback.prototype.trigger = function() {
	this.fn.apply(this.fnScope, arguments);
};


text:
#include <arpa/inet.h>
#include <fcntl.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#include <gnutls/gnutls.h>
#include <gnutls/x509.h>

#include <open-osdp.h>
#include <osdp-local-config.h>
#include <osdp-tls.h>
#include <osdp_conformance.h>

int read_tcp_stream(OSDP_CONTEXT* ctx,
    int
        net_fd,
    int* poll);

int tcp_connect(void);

char
    buffer[MAX_BUF + 1];
OSDP_TLS_CONFIG
config;
OSDP_CONTEXT
context;
OSDP_OUT_CMD
current_output_command[16];
int
    current_sd; // current socket for tcp connection
struct timespec
    last_time_check_ex;
OSDP_BUFFER
osdp_buf;
OSDP_INTEROP_ASSESSMENT
osdp_conformance;
OSDP_PARAMETERS
p_card;
time_t
    previous_time;
int
    request_immediate_poll;
struct sockaddr_in
    sa_serv;
char* tag;

// cardholder number kludge

unsigned char
    creds_buffer_a[64 * 1024];
int
    creds_buffer_a_lth;
int
    creds_buffer_a_next;
int
    creds_buffer_a_remaining;

// passphrase kludge

int
    passphrase_length;
int
    plmax
    = 16;
char
    current_passphrase[17];
char
    specified_passphrase[17];

int initialize(OSDP_TLS_CONFIG* config,
    int
        argc,
    char* argv[])
{ /* initialize */

    char
        command[1024];
    char
        current_network_address[1024];
    int
        status;

    status = ST_OK;
    memset(config, 0, sizeof(*config));
    current_network_address[0] = 0;

    memset(&context, 0, sizeof(context));
    strcpy(context.init_parameters_path, "open-osdp-params.json");
    strcpy(context.log_path, "open-osdp.log");

    // if there's an argument it is the config file path
    if (argc > 1) {
        strcpy(context.init_parameters_path, argv[1]);

        // a second argument is the network address of the destination
        if (argc > 2)
            strcpy(current_network_address, argv[2]);
    };

    sprintf(config->version, "v%d.%d-Build%d",
        OSDP_VERSION_MAJOR, OSDP_VERSION_MINOR, OSDP_VERSION_BUILD);
    strcpy(config->ca_file, OSDP_LCL_CA_KEYS);
    // sets port
    config->listen_sap = 10001;

    //strcpy (specified_passphrase, "speakFriend&3ntr");
    strcpy(specified_passphrase, OSDP_LCL_DEFAULT_PSK);

    if (status EQUALS ST_OK)
        status = initialize_osdp(&context);
    if (context.role EQUALS OSDP_ROLE_CP)
        tag = "CP";
    else
        tag = "PD";

    // initialize my current pid
    if (status EQUALS ST_OK) {
        pid_t
            my_pid;

        my_pid = getpid();
        context.current_pid = my_pid;
        sprintf(command, OSPD_LCL_SET_PID_TEMPLATE,
            tag, my_pid);
        system(command);
    };

    // init timer
    memset(&last_time_check_ex, 0, sizeof(last_time_check_ex));

    if (strlen(current_network_address) > 0)
        strcpy(context.network_address, current_network_address);

    sprintf(context.command_path,
        OSDP_LCL_COMMAND_PATH, tag);

    context.authenticated = 1; // for now just say we're authenticated.

    if (status EQUALS ST_OK) {
        fprintf(stderr, "osdp-tcp-client version %s\n",
            config->version);
        if (context.role EQUALS OSDP_ROLE_CP) {
            fprintf(stderr, "Role: CP\n");
        };
        if (context.role EQUALS OSDP_ROLE_PD) {
            fprintf(stderr, "Role: PD\n");
        };
    };

    return (status);

} /* initialize */

int init_tls_client(void)
{ /* init_tls_client */

    int
        status;
    int
        status_sock;

    status = ST_OK;
    if (status EQUALS ST_OK) {
        /* connect to the peer
         */
        current_sd = tcp_connect();
    };
    if (status EQUALS ST_OK) {
        status_sock = fcntl(current_sd, F_SETFL,
            fcntl(current_sd, F_GETFL, 0) | O_NONBLOCK);
        if (status_sock EQUALS - 1) {
            status = ST_OSDP_TCP_NONBLOCK;
            ;
        };
    };
    return (status);

} /* init_tls_client */

int local_socket_setup(int* lcl_sock_fd)
{ /* local_socket_setup */

    struct sockaddr_un usock;
    char sn[1024];
    int
        status;
    int
        status_socket;
    char* tag;
    int
        ufd;

    status = ST_OK;
    memset(sn, 0, sizeof(1024));
    if (context.role EQUALS OSDP_ROLE_CP)
        tag = "CP";
    else
        tag = "PD";
    sprintf(sn, OSDP_LCL_UNIX_SOCKET, tag);

    ufd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (ufd != -1) {
        memset(&usock, 0, sizeof(usock));
        usock.sun_family = AF_UNIX;
        unlink(sn);
        strcpy(usock.sun_path, sn);
        fprintf(stderr, "unix socket path %s\n",
            usock.sun_path);
        status_socket = bind(ufd, (struct sockaddr*)&usock, sizeof(usock));
        if (status_socket != -1) {
            status_socket = fcntl(ufd, F_SETFL,
                fcntl(ufd, F_GETFL, 0) | O_NONBLOCK);
            if (status_socket != -1) {
                status_socket = listen(ufd, 0);
            } else {
                status = -5;
            };
        } else {
            status = -4;
        };
    } else {
        status = -3;
    };

    if (status EQUALS ST_OK)
        *lcl_sock_fd = ufd;
    return (status);

} /* local_socket_setup */

int main(int
             argc,
    char* argv[])
{ /* main for osdp-tcp-client */

    int
        c1;
    int
        done_tls;
    fd_set
        exceptfds;
    fd_set
        readfds;
    int
        nfds;
    const sigset_t
        sigmask;
    int
        status;
    int
        status_io;
    int
        status_sock;
    int
        status_tls;
    struct timespec
        timeout;
    int
        tls_current_length;
    fd_set
        writefds;
    int
        ufd;

    status = ST_OK;
    status = initialize(&config, argc, argv);
    if (status EQUALS ST_OK) {
        status = local_socket_setup(&ufd);
    };
    if (status EQUALS ST_OK) {
        memset(&last_time_check_ex, 0, sizeof(last_time_check_ex));

        done_tls = 0; // assume not done unless some bad status

        status = init_tls_client();

        // for "phase 1" authentication, kludge it by sending a passphrase
        // send the passphrase to authenticate
        status = send_osdp_data(&context,
            (unsigned char*)specified_passphrase, plmax);
        if (status != ST_OK)
            done_tls = 1;

        if (status EQUALS 0) {
            request_immediate_poll = 0;
            while (!done_tls) {
                fflush(stdout);
                fflush(stderr);
                fflush(context.log);
                {
                    // look for file descriptor activity

                    nfds = 0;
                    FD_ZERO(&readfds);
                    FD_ZERO(&writefds);
                    FD_ZERO(&exceptfds);
                    FD_SET(ufd, &readfds);
                    FD_SET(current_sd, &readfds);
                    nfds = ufd + 1;
                    if (current_sd > ufd)
                        nfds = current_sd + 1;
                    timeout.tv_sec = 0;
                    timeout.tv_nsec = 100000000;
                    status_sock = pselect(nfds, &readfds, &writefds, &exceptfds,
                        &timeout, &sigmask);

                    if (status_sock > 0) {
                        // check for command input (unix socket activity pokes us to check)
                        if (FD_ISSET(ufd, &readfds)) {
                            char cmdbuf[2];
                            char gratuitous_data[2] = { C_OSDP_MARK, 0x00 };
                            ;

                            /*
                              send a benign "message" up the line so that the other knows we're active.
                              If the othere end is the CP this will motivate it to generate an osdp_POLL.
                            */
                            status = send_osdp_data(&context, (unsigned char*)gratuitous_data, 1);
                            if (status != ST_OK)
                                done_tls = 1;

                            c1 = accept(ufd, NULL, NULL);
                            if (c1 != -1) {
                                status_io = read(c1, cmdbuf, sizeof(cmdbuf));
                                if (status_io > 0) {
                                    close(c1);

                                    status = process_current_command();
                                    if (status EQUALS ST_OK)
                                        preserve_current_command();
                                    status = ST_OK;
                                };
                            };
                        };

                        if (FD_ISSET(current_sd, &readfds)) {
                            status = read_tcp_stream(&context, current_sd,
                                &request_immediate_poll);
                        };
                    };

                    // idle processing

                    if (status_sock EQUALS 0) {
                        if ((context.role EQUALS OSDP_ROLE_CP) && context.authenticated) {
                            if (osdp_timeout(&context, &last_time_check_ex) || request_immediate_poll) {
                                // if timer 0 expired dump the status
                                if (context.timer[0].status EQUALS OSDP_TIMER_RESTARTED)
                                    status = write_status(&context);

                                // if "the timer" went off, do the background process

                                status = background(&context);
                                request_immediate_poll = 0;
                            };
                        };
                    };
                }

                if (0) {
                    status = ST_OK; // assume tls read was ok for starters
                    tls_current_length = status_tls;
                    if (status_tls EQUALS 0)
                        status = ST_OSDP_TLS_CLOSED;
                    if (status_tls < 0)
                        status = ST_OSDP_TLS_ERROR;
                    if (status EQUALS ST_OK) {
                        if (context.verbosity > 4)
                            fprintf(stderr, "%d bytes received via TCP:\n",
                                status_tls);

                        // append buffer to osdp buffer
                        if (context.authenticated) {
                            // while first not SOM skip until SOM

                            int i;
                            int done;
                            int current_length;

                            i = 0;
                            current_length = tls_current_length;
                            done = 0;
                            while (!done) {
                                if (buffer[i] != C_SOM) {
                                    i++;
                                    current_length--;
                                } else {
                                    memcpy(osdp_buf.buf + osdp_buf.next,
                                        buffer + i, current_length);
                                    osdp_buf.next = osdp_buf.next + current_length;
                                    status = ST_NET_INPUT_READY;
                                    done = 1;
                                };
                                if (i EQUALS tls_current_length)
                                    done = 1;
                            }
                        };
                    }
                };
                if (status != ST_OK) {
                    if (status != ST_NET_INPUT_READY) {
                        fprintf(stderr, "status %d\n", status);
                        done_tls = 1;
                    };
                };
                // if there was input, process the message
                if (status EQUALS ST_NET_INPUT_READY) {
                    if (status != ST_OK)
                        status = process_osdp_input(&osdp_buf);
                    // if it's too short so far it'll be 'serial_in' so ignore that
                    if (status EQUALS ST_SERIAL_IN)
                        status = ST_OK;
                };
                if (status != ST_OK) {
                    done_tls = 1;
                };
            } /* not done dls */;
        } /* tls initialized */;
    };

    if (status != ST_OK)
        fprintf(stderr, "osdp-tls return status %d\n",
            status);

    return (status);

} /* main for osdp-net-client */

int tcp_connect(void)
{
    const char* PORT = "10001";
    int err, sd;
    struct sockaddr_in sa;

    fprintf(context.log, "Connecting to %s Port %s\n",
        context.network_address,
        PORT);
    /* connects to server
     */
    sd = socket(AF_INET, SOCK_STREAM, 0);

    memset(&sa, '\0', sizeof(sa));
    sa.sin_family = AF_INET;
    sa.sin_port = htons(atoi(PORT));
    inet_pton(AF_INET, context.network_address, &sa.sin_addr);

    err = connect(sd, (struct sockaddr*)&sa, sizeof(sa));
    if (err < 0) {
        fprintf(stderr, "Connect error\n");
        exit(1);
    }

    return sd;
}

int read_tcp_stream(OSDP_CONTEXT* ctx,
    int
        net_fd,
    int* poll)
{ /* read_tcp_stream */

    char
        buffer[1024];
    int
        current_length;
    int
        done;
    int
        i;
    int
        lth;
    int
        status;
    int
        status_io;
    //current_passphrase
    //passphrase_length
    ///plmax
    //specified_passphrase

    status = ST_OK;
    status_io = read(net_fd, buffer, sizeof(buffer));
    if (status_io EQUALS 0)
        status = ST_OSDP_NET_CLOSED;
    if (status_io < 0)
        status = ST_OSDP_NET_ERROR;
    if (status EQUALS ST_OK) {
        if (context.verbosity > 9)
            fprintf(stderr, "net read %d\n", status_io);
        ctx->bytes_received = ctx->bytes_received + status_io;

        // if we have enough data look for the passphrase
        if (!ctx->authenticated) {
            if (passphrase_length < plmax) {
                lth = status_io;
                if ((passphrase_length + lth) > plmax)
                    lth = plmax - passphrase_length;
                memcpy(current_passphrase + passphrase_length, buffer, lth);
                if (0 EQUALS
                        memcmp(current_passphrase, specified_passphrase, plmax))
                    ctx->authenticated = 1;
            };
        };

        // append buffer to osdp buffer
        if (ctx->authenticated) {
            // while first not SOM skip until SOM
            i = 0;
            current_length = status_io;
            done = 0;
            while (!done) {
                if (buffer[i] != C_SOM) {
                    if (ctx->slow_timer) {
                        fprintf(stderr, "!SOM %02x\n",
                            buffer[i]);
                        *poll = 1;
                    };
                    i++;
                    current_length--;
                } else {
                    // saw an SOM, so normal incoming message
                    request_immediate_poll = 0;
                    memcpy(osdp_buf.buf + osdp_buf.next,
                        buffer + i, current_length);
                    osdp_buf.next = osdp_buf.next + current_length;
                    status = ST_NET_INPUT_READY;
                    done = 1;
                };
                if (i EQUALS status_io)
                    done = 1;
            }
        };
    };
    return (status);

} /* read_tcp_stream */

int send_osdp_data(OSDP_CONTEXT* context,
    unsigned char* buf,
    int
        lth)
{ /* send_osdp_data */

    int
        status;
    int
        status_io;

    status = ST_OK;
    status_io = write(current_sd, buf, lth);

    context->bytes_sent = context->bytes_sent + lth;
    if (status_io != lth)
        status = -3;
    return (status);

} /* send_osdp_data */


text:
=============
HTTP Utilties
=============

.. module:: werkzeug.http

Werkzeug provides a couple of functions to parse and generate HTTP headers
that are useful when implementing WSGI middlewares or whenever you are
operating on a lower level layer.  All this functionality is also exposed
from request and response objects.

Date Functions
==============

The following functions simplify working with times in an HTTP context.
Werkzeug uses offset-naive :class:`~datetime.datetime` objects internally
that store the time in UTC.  If you're working with timezones in your
application make sure to replace the tzinfo attribute with a UTC timezone
information before processing the values.

.. autofunction:: cookie_date

.. autofunction:: http_date

.. autofunction:: parse_date

Header Parsing
==============

The following functions can be used to parse incoming HTTP headers.
Because Python does not provide data structures with the semantics required
by :rfc:`2616`, Werkzeug implements some custom data structures that are
:ref:`documented separately <http-datastructures>`.

.. autofunction:: parse_options_header

.. autofunction:: parse_set_header

.. autofunction:: parse_list_header

.. autofunction:: parse_dict_header

.. autofunction:: parse_accept_header(value, [class])

.. autofunction:: parse_cache_control_header

.. autofunction:: parse_authorization_header

.. autofunction:: parse_www_authenticate_header

.. autofunction:: parse_if_range_header

.. autofunction:: parse_range_header

.. autofunction:: parse_content_range_header

Header Utilities
================

The following utilities operate on HTTP headers well but do not parse
them.  They are useful if you're dealing with conditional responses or if
you want to proxy arbtirary requests but want to remove WSGI-unsupported
hop-by-hop headers.  Also there is a function to create HTTP header
strings from the parsed data.

.. autofunction:: is_entity_header

.. autofunction:: is_hop_by_hop_header

.. autofunction:: remove_entity_headers

.. autofunction:: remove_hop_by_hop_headers

.. autofunction:: is_byte_range_valid

.. autofunction:: quote_header_value

.. autofunction:: unquote_header_value

.. autofunction:: dump_header

Cookies
=======

.. autofunction:: parse_cookie

.. autofunction:: dump_cookie

Conditional Response Helpers
============================

For conditional responses the following functions might be useful:

.. autofunction:: parse_etags

.. autofunction:: quote_etag

.. autofunction:: unquote_etag

.. autofunction:: generate_etag

.. autofunction:: is_resource_modified

Constants
=========

.. data:: HTTP_STATUS_CODES

    A dict of status code -> default status message pairs.  This is used
    by the wrappers and other places where a integer status code is expanded
    to a string throughout Werkzeug.

Form Data Parsing
=================

.. module:: werkzeug.formparser

Werkzeug provides the form parsing functions separately from the request
object so that you can access form data from a plain WSGI environment.

The following formats are supported by the form data parser currently:

-   `application/x-www-form-urlencoded`
-   `multipart/form-data`

Nested multipart is currently not supported (Werkzeug 0.6) albeit unused
by any of the modern webbrowsers.

Usage example:

>>> from cStringIO import StringIO
>>> data = '--foo\r\nContent-Disposition: form-data; name="test"\r\n' \
... '\r\nHello World!\r\n--foo--'
>>> environ = {'wsgi.input': StringIO(data), 'CONTENT_LENGTH': str(len(data)),
...            'CONTENT_TYPE': 'multipart/form-data; boundary=foo',
...            'REQUEST_METHOD': 'POST'}
>>> stream, form, files = parse_form_data(environ)
>>> stream.read()
''
>>> form['test']
u'Hello World!'
>>> not files
True

Normally the WSGI environment is provided by the WSGI gateway with the
incoming data as part of it.  If you want to generate such fake-WSGI
environments for unittesting you might want to use the
:func:`create_environ` function or the :class:`EnvironBuilder` instead.

.. autoclass:: FormDataParser

.. autofunction:: parse_form_data

.. autofunction:: parse_multipart_headers


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Regular api update</title>


text:
import { Component, Element, Prop, h, State, Host } from '@stencil/core';

@Component({
  tag: 'hubspot-dynamic-content',
  styleUrl: 'hubspot-dynamic-content.scss',
  shadow: false
})
export class HubspotDynamicContent {

  @Prop() listId: string = 'default';
  @State() isInList = false;
  @Element() el;

  API_URL = 'https://ionic-site-new.now.sh/api/hubspot/hasconverted';

  async componentWillLoad() {
    const hsutk = window['getCookie']('hubspotutk');

    fetch(`${this.API_URL}?listId=${this.listId}&hsutk=${hsutk}`)
      .then(response => response.json())
      .then( data => {
        this.isInList = data.found;
      })
      .catch(e => {
        console.warn(e);
      })
      .finally( () => {
        this.el.classList.add('ready');
      });
  }

  render() {
    // console.log('rendering', this.isInList);
    return (
      <Host>
        {this.isInList ?
          <slot name="default" /> :
          <slot name="alternate" />
        }
      </Host>
    );
  }
}


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

<TITLE>
org.hibernate.cache.ehcache.internal.nonstop (Hibernate JavaDocs)
</TITLE>

<META NAME="date" CONTENT="2013-10-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package org.hibernate.cache.ehcache.internal.nonstop

Class Summary

HibernateNonstopCacheExceptionHandler
Class that takes care of NonStopCacheException that happens in hibernate module

NonstopAccessStrategyFactory
Implementation of EhcacheAccessStrategyFactory that takes care of Nonstop cache exceptions using
 HibernateNonstopCacheExceptionHandler

NonstopAwareCollectionRegionAccessStrategy
Implementation of CollectionRegionAccessStrategy that handles NonStopCacheException using
 HibernateNonstopCacheExceptionHandler

NonstopAwareEntityRegionAccessStrategy
Implementation of EntityRegionAccessStrategy that handles NonStopCacheException using
 HibernateNonstopCacheExceptionHandler

NonstopAwareNaturalIdRegionAccessStrategy
Implementation of NaturalIdRegionAccessStrategy that handles NonStopCacheException using
 HibernateNonstopCacheExceptionHandler

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2001-2013 Red Hat, Inc.  All Rights Reserved.


text:
module Utils
  class StandardImporter
    def each
      while true do
        yield gets.chomp
      end
    end
  end
end


text:
using System;

namespace NAudio.Dmo
{
    [Flags]
    internal enum DmoInputStatusFlags
    {
        None,
        DMO_INPUT_STATUSF_ACCEPT_DATA = 0x1
    }
}


text:
"use strict";

/**
 * @module Collision
 * @class CGSGCollisionRegionTester
 * @extends {Object}
 * @constructor
 * @type {CGSGCollisionRegionTester}
 * @author Vincent Vanghelle (vincent.vanghelle@capgemini.com)
 */
var CGSGCollisionRegionTester = CGSGObject.extend(
    {
        initialize : function () {
            this.classType="CGSGCollisionRegionTester";
        },

        /**
         * Indicate if two nodes are colliding
         * @method isColliding
         * @param currentNode
         * @param testedNode
         * @param threshold
         * @return {boolean} true if nodes are colliding
         */
        isColliding : function(currentNode, testedNode,threshold){
            if (threshold === null) {
                threshold = 0;
            }
            var nodeRight = testedNode.getAbsoluteRight();
            var nodeBottom = testedNode.getAbsoluteBottom();

            if ((currentNode.getAbsoluteLeft() <= nodeRight + threshold &&
                currentNode.getAbsoluteRight() >= testedNode.getAbsoluteLeft() - threshold) ||
                (currentNode.getAbsoluteRight() >= testedNode.getAbsoluteLeft() - threshold &&
                    currentNode.getAbsoluteLeft() <= nodeRight + threshold)) {

                if (currentNode.getAbsoluteTop() <= nodeBottom + threshold &&
                    currentNode.getAbsoluteBottom() >= testedNode.getAbsoluteTop() - threshold) {
                    return true;
                }
            }

            return false;
        }
    }
);


text:
package io.unravelling.ferguson;

import io.unravelling.ferguson.configuration.FergusonConfiguration;
import io.unravelling.ferguson.ems.FergusonEms;
import io.unravelling.ferguson.exceptions.InvalidConfigurationException;
import io.unravelling.ferguson.model.ServerType;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class to build the different kinds of Ferguson instances.
 */
public final class FergusonFactory {

  /**
   * Class default logger.
   */
  private static final Logger LOGGER = LoggerFactory.getLogger(FergusonFactory.class);

  /**
   * Private constructor to disable instantiation of this class.
   */
  private FergusonFactory() {}

  /**
   * Gets a new instance of Ferguson based on the provided configuration.
   * @param configuration Configuration of the instance.
   * @return Created Ferguson instance.
   * @throws InvalidConfigurationException Exception thrown when receiving an invalid configuration.
   */
  public static Ferguson getFerguson(final Properties configuration) throws InvalidConfigurationException {
    if (LOGGER.isInfoEnabled()) {
      LOGGER.debug("Validating the configuration...");
    }

    if (!FergusonConfiguration.validateConfiguration(configuration)) {
      throw new InvalidConfigurationException("Invalid configuration found...");
    }

    if (LOGGER.isInfoEnabled()) {
      LOGGER.debug("Looks good, creating the instance...");
    }

    Ferguson ferguson = null;

    final ServerType serverType =
        ServerType.valueOf(configuration.getProperty(FergusonConfiguration.SERVER_TYPE));

    if (ServerType.EMS.equals(serverType)) {
      ferguson = new FergusonEms(configuration);
    }

    return ferguson;
  }
}


text:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
import functools
from PyQt5.QtWebKitWidgets import *
from gui import Ui_MainWindow
from PyQt5.QtCore import QCoreApplication
from rake import *
from textrank import *
import nltk
from contentBasedRecommender import *
import qdarkstyle
from wordcloud import WordCloud
from utilities import *
import StringIO
import base64
import qtawesome as qta
from random import randint
sys.modules['PyQt4.QtGui'] = QtGui
from PIL.ImageQt import ImageQt
from hybrid_tfw2v_demo import *
from emotion_recognizer import predictEmo,initialize_emotion_recognizer

class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle('SmartMM')
        self.initialize()

    def initialize(self):
        first_load()
        self.emovecs = initialize_emotion_recognizer()
        self.initalize_gui()
        self.initialize_triggers()

    def initalize_gui(self):
        self.ui.review1.setStyleSheet("background-color: DarkCyan;color: black")
        self.ui.recommendButton.setStyleSheet("background-color: Tomato;color: black")
        self.ui.review1.setIcon(qta.icon('fa.flag'))
        self.ui.recommendButton.setIcon(qta.icon('fa.bullseye'))
        self.setup_mov_list()
        self.ui.progressInfo.setVisible(False)
        self.ui.progressBar.setVisible(False)
        self.showClickedItem(self.ui.listWidget.item(0))

    def initialize_triggers(self):
        self.ui.actionExit.triggered.connect(QCoreApplication.instance().quit)
        self.ui.actionAdd_Files.triggered.connect(self.addFiles_triggered)
        self.ui.actionAdd_Folders.triggered.connect(self.addFolder_triggered)
        self.ui.listWidget.itemClicked.connect(self.showClickedItem)
        self.ui.actionSync.triggered.connect(self.internet_sync_trigger)
        self.ui.recommendButton.clicked.connect(self.recommendMovies)

    #The list shows movies even if movie is removed from folder
    def recommendMovies(self):
        list = getSeenMovies()
        list = [x[0] for x in list]
        print list
        recommender = Recommender()
        rec_list = recommender.get_n_recommendations(10, list)
        for movie in rec_list:
            self.ui.listWidgetRecommend.addItem(movie['title'])

    def setup_mov_list(self):
        movies = get_mov_names()
        self.ui.listWidget.clear()
        #check if the movie exists in the folder acc. to db entry
        #correct it
        for movie in movies:
            if movie != "":
                print movie
                item = QtWidgets.QListWidgetItem()
                widget = QtWidgets.QWidget()
                widgetText = QtWidgets.QLabel(movie)
                widgetCheckbox = QtWidgets.QCheckBox()
                path = os.getcwd()
                widgetCheckbox.setStyleSheet(
                    "QCheckBox::indicator:unchecked {image: url(%s/images/star_greyed_small.png);}"
                    "QCheckBox::indicator:checked {image: url(%s/images/star_pressed_small.png);}" % (path,path)
                )
                widgetLayout = QtWidgets.QHBoxLayout()
                widgetLayout.addWidget(widgetText)
                widgetLayout.addStretch(1)
                widgetLayout.addWidget(widgetCheckbox)
                widget.setLayout(widgetLayout)
                item.setSizeHint(widget.sizeHint())
                seen = getSeenValue(movie)
                #print movie + " Initial Seen Value: " + str(seen)
                if seen:
                    widgetCheckbox.setCheckState(QtCore.Qt.Checked)
                #print checkbox.isChecked()
                widgetCheckbox.stateChanged.connect(functools.partial(self.checkFunction, movie))
                self.ui.listWidget.addItem(item)
                self.ui.listWidget.setItemWidget(item, widget)

                ####OLD CODE WITHOUT LABEL
                """
                #print movie
                item = QtWidgets.QListWidgetItem(movie)
                self.ui.listWidget.addItem(item)
                checkbox = QtWidgets.QCheckBox()
                seen = getSeenValue(movie)
                #print movie + " Initial Seen Value: " + str(seen)
                if seen:
                    checkbox.setCheckState(QtCore.Qt.Checked)
                #print checkbox.isChecked()
                checkbox.stateChanged.connect(functools.partial(self.checkFunction, movie))
                self.ui.listWidget.setItemWidget(item, checkbox)
                """

    def checkFunction(self, movie):
        #if state == QtCore.Qt.Checked:
        changeSeenValue(movie)

    def addFolder_triggered(self):
        dir = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Directory"))
        add_folder(dir)
        self.setup_mov_list()

    def addFiles_triggered(self):
        filename=QtWidgets.QFileDialog.getOpenFileName(self)
        add_file(filename[0])
        self.setup_mov_list()

    def displayImage(self, imgData):
        qimg = QtGui.QImage.fromData(imgData)
        pixmap = QtGui.QPixmap.fromImage(qimg)
        self.ui.imgLabel.setPixmap(pixmap)

    def showClickedItem(self,item):
        #selected_vid = item.text()
        try:
            selected_vid = self.ui.listWidget.itemWidget(item).findChild(QtWidgets.QLabel).text()
            self.update_gui_with_mov(selected_vid)
        except Exception as e:
            print e.message

    def update_gui_with_mov(self,mov):
        mov_details = prep_mov_details_dict(mov_to_id(mov))
        print mov_details
        #print len(mov_details["review_urls"])
        self.ui.labelMov.setText(mov_details["name"])
        self.ui.labelGenre.setText(mov_details["genres"])
        self.ui.textMovSummary.setText(mov_details["plot"])
        self.ui.textDirector.setText(mov_details["directors"])
        self.ui.textProducer.setText(mov_details["producers"])
        self.ui.textStarCast.setText(mov_details["cast"])
        self.ui.textRTRating.setText(mov_details["rt_rating"])
        self.ui.textIMDBRating.setText(mov_details["imdb_rating"])
        self.ui.textVoteCount.setText(mov_details["votes"])
        self.displayImage(mov_details["img"])
        self.displayWordCloud(mov_details["plot"])
        self.emotionDisplay(mov)
        #self.displayReview(mov_details)
        if (len(mov_details["review"])):
            self.ui.review1.disconnect()
            self.ui.review1.clicked.connect(functools.partial(self.displayReview, mov_details))
        QCoreApplication.processEvents()
        #if(len(mov_details["reviews"])):
        #    self.displayRakeKeywords(mov_details["reviews"][0])
        #    self.displayTextRankKeywords(mov_details["reviews"][0])
        #    self.displayKeywords(mov_details["reviews"][0])

    def emotionDisplay(self,mov):
        path = mov_to_path(mov).split(".")[0]+".srt"
        print path
        try:
            emotions = predictEmo(path,self.emovecs)
        except Exception as e:
            print e.message
        if emotions is None:
            self.ui.pbarAngry.setValue(0)
            self.ui.pbarSurprise.setValue(0)
            self.ui.pbarFear.setValue(0)
            self.ui.pbarSad.setValue(0)
            self.ui.pbarHappy.setValue(0)
        print emotions
        self.ui.pbarAngry.setValue(emotions['anger']*100)
        self.ui.pbarSurprise.setValue(emotions['surprise']*100)
        self.ui.pbarFear.setValue(emotions['fear']*100)
        self.ui.pbarSad.setValue(emotions['sad']*100)
        self.ui.pbarHappy.setValue(emotions['happy']*100)

    def displayWordCloud(self, plot):
        #print plot
        rake = Rake("SmartStoplist.txt")
        keywords = rake.run(str(plot))
        #print keywords
        data = WordCloud(max_words=15).generate_from_frequencies(keywords)
        img = data.to_image()
        #print img
        pix = QtGui.QPixmap.fromImage(ImageQt(img))
        scaledPix = pix.scaled(self.ui.wordCloudLabel.size(), QtCore.Qt.KeepAspectRatio)

        #img.show()
        #data = img.tostring('raw', 'RGBA')
        #image = QtGui.QImage(data, img.size[0], img.size[1], QtGui.QImage.Format_ARGB32)
        #pix = QtGui.QPixmap.fromImage(image)

        self.ui.wordCloudLabel.setPixmap(scaledPix)
        #print "displayed"

    def displayReview(self, mov_details):
        print mov_details["name"]
        class MyWebView(QWebView):
            def __init__(self):
                QWebView.__init__(self)
                self.setWindowTitle(mov_details["name"])
                #print "Hello"

            def _loadFinished(self):
                js1 = """
                var text = "Less impressive are the screenplay and Ron Howard's direction";
                var re = new RegExp(text, "gi");
                document.body.innerHTML = document.body.innerHTML.replace(re,"" + text + "");
                """

                js2 = """
                var text = {0};
                var re = new RegExp(text, "gi");
                document.body.innerHTML = document.body.innerHTML.replace(re,"" + text + "");
                """
                sentences = "Writer Akiva Goldsman (he of the two bad Batman films fame), adapting the script from Sylvia Nasar's biography of Nash, reveals only the warts that aren't too ugly (there is no mention of Nash's bisexuality or of his divorce from Alicia)."
                sentences = sentences.split(".")
                # print repr(sentences[0])
                # sentences[0] = sentences[0].replace("\n","")
                # sentences[0] = "\"%s.\"" % ( sentences[0] )
                # print repr(sentences[0])
                # js2 = js2.format(sentences[0], "red")
                #for sent in sentences:
                #    sent = sent.replace("\n","")
                #    sent = "\"%s.\"" % ( sent )
                #    print repr(sent)
                #    js2 = js2.format(sent, "red")

                #tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
                #tokens = [token.replace("\n", "") for token in tokenizer.tokenize(mov_details["reviews"][0])]
                #print tokens
                #for token in tokens:
                #    #print token
                #    js2 = js2.format(token, "blue")q
                #    self.page().mainFrame().evaluateJavaScript(js2)

                #print js2
                #print js2==js1
                #self.page().mainFrame().evaluateJavaScript(js2)
                #self.page().mainFrame().evaluateJavaScript("""alert("done")""")
                print "load finished"

        print "Review clicked "
        self.webview = MyWebView()
        #self.webview.load(QtCore.QUrl(mov_details["review_urls"][0]))
        html = str(mov_details["review"])
        html = self.sentimentify(html)
        self.webview.setHtml(html)
        path = os.getcwd()
        self.webview.settings().setUserStyleSheetUrl(QtCore.QUrl.fromLocalFile( path + "/review.css"))
        #self.webview.loadFinished.connect(self.webview._loadFinished)
        self.webview.show()

        ##Old Code to replace string
        """//var index = innerHTML.indexOf(text);
                //alert(index);
                //if(index >=0)
                    //innerHTML = innerHTML.substring(0,index) + "" + innerHTML.substring(index,index+text.length) + "" + innerHTML.substring(index + text.length);"""

        #####Code to add CSS File
        #path = os.getcwd()
        #self.webview.settings().setUserStyleSheetUrl(QtCore.QUrl.fromLocalFile(path + "/highlight.css"))

    def sentimentify(self, review):
        rake = Rake("SmartStoplist.txt")
        keywords = rake.run(review)
        #print keywords
        data = WordCloud(max_words=15).generate_from_frequencies(keywords)
        img = data.to_image()
        output = StringIO.StringIO()
        img.save(output, format = 'PNG')
        output.seek(0)
        output_s = output.read()
        b64 = base64.b64encode(output_s)

        strRev = ''.format(b64)
        review_sentences = nltk.sent_tokenize(review)
        scores = test(review_sentences)
        # test(reviews[0])
        colors = [ '#FF0000', '#FF9900', '#FFFF66', '#CCFFBB', '#005A04' ]

        for score,review_sentence in zip(scores,review_sentences):
            strRev += "".format(colors[score]) + review_sentence + " " + ""

        strRev = "
" + strRev + "
"
        print strRev
        return strRev

    def displayRakeKeywords(self, review):
        rake = Rake("SmartStoplist.txt")
        keywords = rake.run(str(review))
        print keywords
        text = ""
        for word in keywords[:10]:
            text += str(word[0])
            text += ";\n"
        #self.ui.keywordLabel.setText(text)
        #self.ui.keywordLabel.setToolTip(text)

    def displayTextRankKeywords(self, review):
        review = review.decode('utf8')
        keywords = extractKeyphrases(review)
        print keywords
        keywords = list(keywords)
        text = ""
        for word in keywords[:10]:
            text += str(word)
            text += ";\n"
        #self.ui.keywordLabel_2.setText(text)
        #self.ui.keywordLabel_2.setToolTip(text)

    def displayKeywords(self, review):
        review = review.decode('utf8')
        wordTokens = nltk.word_tokenize(review)
        tagged = nltk.pos_tag(wordTokens)
        #textlist = [x[0] for x in tagged]
        tags = ['JJ']
        adjectives = [item[0] for item in tagged if item[1] in tags]
        print set(adjectives)

    #it does not overwrite the db, rather inserts duplicate values
    #correct it
    def internet_sync_trigger(self):
        self.syncer = MovieSyncThread(self)
        self.syncer.startSignal.connect(self.init_progressbar)
        self.syncer.updateSignal.connect(self.update_progressbar)
        self.syncer.terminateSignal.connect(self.terminate_progressbar)
        self.syncer.start()

    def terminate_progressbar(self):
        self.ui.progressInfo.setVisible(False)
        self.ui.progressBar.setVisible(False)

    def update_progressbar(self):
        self.ui.progressBar.setValue(self.ui.progressBar.value() + 1)

    def init_progressbar(self, maxProgressBarValue):
        print "Initialize progress bar now"
        # self.ui.progressInfo.setVisible(True)
        self.ui.progressBar.setVisible(True)
        self.ui.progressBar.setMaximum(maxProgressBarValue)
        # self.ui.progressInfo.setText("Fetching info...Please Wait!")
        self.ui.statusbar.showMessage("Fetching info...Please Wait!")
        self.ui.progressBar.setValue(0)

    def recommendMovies(self):
        list = getSeenMovies()
        reco_thread = RecommenderThread(self,15,list)
        reco_thread.startSignal.connect(self.init_progressbar)
        reco_thread.updateSignal.connect(self.update_progressbar)
        reco_thread.terminateSignal.connect(self.terminate_recos)
        reco_thread.start()

    def terminate_recos(self,recos):
        seen_movies = getSeenMovies()
        seen_movie_longnames = [name for id,imdb_id,name in seen_movies]
        for movie in recos:
            if movie["long imdb canonical title"] not in seen_movie_longnames:
                self.ui.listWidgetRecommend.addItem(movie['title'])
        self.terminate_progressbar()

class MovieSyncThread(QtCore.QThread):

    startSignal = QtCore.pyqtSignal(int)
    updateSignal = QtCore.pyqtSignal()
    terminateSignal = QtCore.pyqtSignal()

    def __init__(self,parent):
        QtCore.QThread.__init__(self,parent)

    def run(self):
        mov_names = get_mov_names()
        self.startSignal.emit(len(mov_names))

        print "Performing Sync"
        if check_net() is True:
            for mov in mov_names:
                # self.parent.ui.progressBar.setValue(init_value)
                add_mov_details_to_db(mov)
                self.updateSignal.emit()
        self.terminateSignal.emit()
            # Parallel(n_jobs=-1,verbose=2,backend="threading")(
            #     delayed(add_mov_details_to_db)(mov) for mov in mov_names)
        # self.parent.ui.progressInfo.setVisible(False)
        # self.parent.ui.progressBar.setVisible(False)

class RecommenderThread(QtCore.QThread):
    startSignal = QtCore.pyqtSignal(int)
    updateSignal = QtCore.pyqtSignal()
    terminateSignal = QtCore.pyqtSignal(list)

    def __init__(self,parent,n,movies_lst):
        QtCore.QThread.__init__(self,parent)
        self.n = n
        self.movies_lst = movies_lst

    def run(self):
        self.startSignal.emit(1)
        print "Generating Recommendations"
        recos_list = Recommender().get_n_recommendations(self.n,self.movies_lst)
        self.updateSignal.emit()
        self.terminateSignal.emit(recos_list)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle("fusion")
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    window = MyApp()
    #window.showMaximized()
    window.show()
    sys.exit(app.exec_())


text:
zrequire('poll_widget');

set_global('$', global.make_zjquery());
set_global('i18n', global.stub_i18n);

set_global('people', {});
set_global('blueslip', {});
set_global('templates', {});

const noop = () => {};
const return_false = () => false;
const return_true = () => true;

run_test('poll_data_holder my question', () => {
    const is_my_poll = true;
    const question = 'Favorite color?';

    const sender_id = 99;
    people.my_current_user_id = () => sender_id;

    const data_holder = poll_widget.poll_data_holder(is_my_poll, question);

    let data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        comments: [],
        question: 'Favorite color?',
    });

    const question_event = {
        type: 'question',
        question: 'best plan?',
    };

    data_holder.handle_event(sender_id, question_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        comments: [],
        question: 'best plan?',
    });

    const comment_event = {
        type: 'new_comment',
        idx: 1,
        comment: 'release now',
    };

    people.safe_full_names = () => '';

    data_holder.handle_event(sender_id, comment_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        comments: [
            {
                comment: 'release now',
                names: '',
                count: 0,
                key: '99,1',
            },
        ],
        question: 'best plan?',
    });

    let  vote_event = {
        type: 'vote',
        key: '99,1',
        vote: 1,
    };

    data_holder.handle_event(sender_id, vote_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        comments: [
            {
                comment: 'release now',
                names: '',
                count: 1,
                key: '99,1',
            },
        ],
        question: 'best plan?',
    });

    const invalid_vote_event = {
        type: 'vote',
        key: '98,1',
        vote: 1,
    };

    blueslip.error = (msg) => {
        assert.equal(msg, `unknown key for poll: ${invalid_vote_event.key}`);
    };
    data_holder.handle_event(sender_id, invalid_vote_event);
    data = data_holder.get_widget_data();

    const comment_outbound_event = data_holder.handle.new_comment.outbound('new comment');
    assert.deepEqual(comment_outbound_event, {
        type: 'new_comment',
        idx: 2,
        comment: 'new comment',
    });

    const new_question = 'Any new plan?';
    const question_outbound_event = data_holder.handle.question.outbound(new_question);
    assert.deepEqual(question_outbound_event, {
        type: 'question',
        question: new_question,
    });

    const vote_outbound_event = data_holder.handle.vote.outbound('99,1');
    assert.deepEqual(vote_outbound_event, { type: 'vote', key: '99,1', vote: -1 });

    vote_event = {
        type: 'vote',
        key: '99,1',
        vote: -1,
    };

    data_holder.handle_event(sender_id, vote_event);
    data = data_holder.get_widget_data();

    assert.deepEqual(data, {
        comments: [
            {
                comment: 'release now',
                names: '',
                count: 0,
                key: '99,1',
            },
        ],
        question: 'best plan?',
    });
});

run_test('activate another person poll', () => {
    people.is_my_user_id = return_false;
    templates.render = (template_name) => {
        if (template_name === 'poll-widget') {
            return 'poll-widget';
        }
        if (template_name === 'poll-widget-results') {
            return 'poll-widget-results';
        }
    };

    const widget_elem = $('<div>').addClass('widget-content');

    let out_data;   // Used to check the event data sent to the server
    const callback = (data) => {
        out_data = data;
    };

    const opts = {
        elem: widget_elem,
        callback: callback,
        message: {
            sender_id: 100,
        },
    };

    const set_widget_find_result = (selector) => {
        const elem = $.create(selector);
        widget_elem.set_find_results(selector, elem);
        return elem;
    };

    const poll_comment = set_widget_find_result('button.poll-comment');
    const poll_comment_input = set_widget_find_result('input.poll-comment');
    const widget_comment_container = set_widget_find_result('ul.poll-widget');

    const poll_question = set_widget_find_result('button.poll-question');
    const poll_question_input = set_widget_find_result('input.poll-question');
    const poll_question_header = set_widget_find_result('.poll-question-header');
    const poll_question_container = set_widget_find_result('.poll-question-bar');
    const poll_comment_container = set_widget_find_result('.poll-comment-bar');

    const poll_vote_button = set_widget_find_result('button.poll-vote');

    let question_button_callback;
    let comment_button_callback;
    let vote_button_callback;

    poll_question.on = (event, func) => {
        assert.equal(event, 'click');
        question_button_callback = func;
    };

    poll_comment.on = (event, func) => {
        assert.equal(event, 'click');
        comment_button_callback = func;
    };

    poll_vote_button.on = (event, func) => {
        assert.equal(event, 'click');
        vote_button_callback = func;
    };

    poll_widget.activate(opts);

    assert.equal(widget_elem.html(), 'poll-widget');
    assert.equal(widget_comment_container.html(), 'poll-widget-results');
    assert.equal(poll_question_header.text(), '');

    const e = {
        stopPropagation: noop,
    };

    {
        /* Testing no data sent to server on clicking add question button */
        poll_question_input.val('Is it new?');
        out_data = undefined;
        question_button_callback(e);
        assert.deepEqual(out_data, undefined);
    }

    {
        /* Testing data sent to server on adding comment */
        poll_comment_input.val('cool choice');
        out_data = undefined;
        comment_button_callback(e);
        assert.deepEqual(out_data,  { type: 'new_comment', idx: 1, comment: 'cool choice' });

        poll_comment_input.val('');
        out_data = undefined;
        comment_button_callback(e);
        assert.deepEqual(out_data, undefined);
    }

    const vote_events = [
        {
            sender_id: 100,
            data: {
                type: 'new_comment',
                idx: 1,
                comment: 'release now',
            },
        },
        {
            sender_id: 100,
            data: {
                type: 'vote',
                key: '100,1',
                vote: 1,
            },
        },
    ];

    widget_elem.handle_events(vote_events);

    assert(poll_question.attr('disabled'));
    assert(poll_question_input.attr('disabled'));

    {
        /* Testing data sent to server on voting */
        poll_vote_button.attr('data-key', '100,1');
        const e = {
            stopPropagation: noop,
            target: poll_vote_button,
        };
        out_data = undefined;
        vote_button_callback(e);
        assert.deepEqual(out_data, { type: 'vote', key: '100,1', vote: 1 });
    }

    const add_question_event = [
        {
            sender_id: 100,
            data: {
                type: 'question',
                question: 'best plan?',
            },
        },
    ];

    poll_question_container.show();

    widget_elem.handle_events(add_question_event);

    assert(!poll_question_container.visible());
    assert(poll_comment_container.visible());
});

run_test('activate own poll', () => {
    $.clear_all_elements();

    people.is_my_user_id = return_true;
    templates.render = (template_name) => {
        if (template_name === 'poll-widget') {
            return 'poll-widget';
        }
        if (template_name === 'poll-widget-results') {
            return 'poll-widget-results';
        }
    };

    const widget_elem = $('<div>').addClass('widget-content');
    let out_data;
    const callback = (data) => {
        out_data = data;
    };
    const opts = {
        elem: widget_elem,
        callback: callback,
        message: {
            sender_id: 100,
        },
        extra_data: {
            question: 'Where to go?',
        },
    };

    const set_widget_find_result = (selector) => {
        const elem = $.create(selector);
        widget_elem.set_find_results(selector, elem);
        return elem;
    };

    const poll_comment = set_widget_find_result('button.poll-comment');
    const poll_comment_input = set_widget_find_result('input.poll-comment');
    const widget_comment_container = set_widget_find_result('ul.poll-widget');

    const poll_question = set_widget_find_result('button.poll-question');
    const poll_question_input = set_widget_find_result('input.poll-question');
    const poll_question_header = set_widget_find_result('.poll-question-header');
    const poll_question_container = set_widget_find_result('.poll-question-bar');
    const poll_comment_container = set_widget_find_result('.poll-comment-bar');

    const poll_vote_button = set_widget_find_result('button.poll-vote');

    let question_button_callback;

    poll_question.on = (event, func) => {
        assert.equal(event, 'click');
        question_button_callback = func;
    };

    // Following event handler are already tested and doesn't make sense
    // to test them again
    poll_comment.on = noop;
    poll_vote_button.on = noop;

    poll_question.attr('disabled', false);
    poll_question_input.attr('disabled', false);
    // Setting visiblity to true as default is false
    poll_question_container.show();

    poll_widget.activate(opts);

    assert.equal(widget_elem.html(), 'poll-widget');
    assert.equal(widget_comment_container.html(), 'poll-widget-results');
    assert.equal(poll_question_header.text(), 'Where to go?');
    assert(poll_question.attr('disabled', false));
    assert(poll_question_input.attr('disabled', false));

    {
        /* Testing data sent to server on editing question */
        const e = {
            stopPropagation: noop,
        };

        poll_question_input.val('Is it new?');
        out_data = undefined;
        question_button_callback(e);
        assert.deepEqual(out_data,  { type: 'question', question: 'Is it new?' });

        poll_comment_input.val('');
        out_data = undefined;
        question_button_callback(e);
        assert.deepEqual(out_data, undefined);
    }
    assert(poll_comment_container.visible());
});


text:
class SettingsController < ApplicationController
  permits :hide_checkin_comment

  before_filter :authenticate_user!

  def update(setting)
    if current_user.setting.update_attributes(setting)
      redirect_to setting_path, notice: '設定を更新しました'
    else
      render '/settings/show'
    end
  end
end