text:
function [minuteWiseBad minuteWiseGood minuteWiseActivity minuteWiseUsableStress]=overallMinuteByMinuteStressData(phoneOnEpisodes,goodEpisodes,activityEpisodes)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%     Copyright 2014 University of Memphis
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%%

[r c]=size(phoneOnEpisodes);
  minuteWiseUsableStress=[];
    minuteWiseGood=[];
    minuteWiseActivity=[];
    minuteWiseBad=[];
for i=1:r
    participant=phoneOnEpisodes(i,1);
    day=phoneOnEpisodes(i,2);

    ind=find(activityEpisodes(:,1)==participant & activityEpisodes(:,2)==day & activityEpisodes(:,5)==1);
    activityOfTheDay=activityEpisodes(ind,:);

    ind2=find(goodEpisodes(:,1)==participant & goodEpisodes(:,2)==day);
    goodDataOfTheDay=goodEpisodes(ind2,:);

    for t=phoneOnEpisodes(i,3):60000:phoneOnEpisodes(i,4)-1
        starttime=t;
        endtime=t+60000;

        goodData=0;
        activity=0;
        usableForStress=0;
        badData=0;

        %calculate activity duration
        activity=getActivityDuration(activityOfTheDay,starttime,endtime);
        %calculate good duration
        goodData=getGoodDuration(goodDataOfTheDay,starttime,endtime);

        if  activity<goodData
            usableForStress=goodData-activity;
        end
        usableForStress=usableForStress/60; %converting to percentage
        goodData=goodData/60;
        activity=activity/60;
        badData=1-goodData;                 %everything is now in percentage

        minuteWiseUsableStress=[minuteWiseUsableStress; participant day usableForStress];
        minuteWiseGood=[minuteWiseGood; participant day goodData];
        minuteWiseActivity=[minuteWiseActivity; participant day activity];
        minuteWiseBad=[minuteWiseBad; participant day badData];
    end
end
end

function activity=getActivityDuration(activityOfTheDay,starttime,endtime)
    activity=0;
    activity=getDurOfOverlapWithEpisodesAndWindow(activityOfTheDay,starttime,endtime);
%     if activity==-1
%         activity=0;
%     end
end

function goodData=getGoodDuration(goodDataOfTheDay,starttime,endtime)
    goodData=getDurOfOverlapWithEpisodesAndWindow(goodDataOfTheDay,starttime,endtime);
end
function dur=getDurOfOverlapWithEpisodesAndWindow(episodes,starttime,endtime)
%return the total duration from episodes that overlaps with
%the time window [starttime endtime]

    dur=0;
    %case 1: the whole duration (endtime-starttime) is under a good episode
    ind2=find(episodes(:,3)<=starttime & episodes(:,4)>=endtime);
    if ~isempty(ind2)
        dur=(endtime-starttime)/1000;                              %duration in seconds
        return;
    end

    %case 2: good episodes between start and end time
    ind2=find(episodes(:,3)>=starttime & episodes(:,4)<=endtime);
    if ~isempty(ind2)
        dur=dur+sum(episodes(ind2,4)-episodes(ind2,3))/1000;
    end

    %case 3: start time is inside a good episode
    ind2=find(episodes(:,3)<=starttime & episodes(:,4)>=starttime);
    if ~isempty(ind2)
        dur=dur+sum(episodes(ind2,4)-starttime)/1000;
    end

    %case 4: end time is inside a good episode
    ind2=find(episodes(:,3)<=endtime & episodes(:,4)>=endtime);
    if ~isempty(ind2)
        dur=dur+sum(endtime-episodes(ind2,3))/1000;
    end
end
function [goodData activity usableForStress]=getUsableStressDataBeforeTheEvent_voting(goodEpisodes,activityEpisode, timestamp,offset)
    goodData=0;
    activity=0;
    usableForStress=0;
    endtime=timestamp-(offset-1)*60*1000;
    starttime=timestamp-offset*60*1000;
    %calculate activity duration
    activity=getActivityDuration(activityEpisode,starttime,endtime);
    %calculate good duration
    goodData=getGoodDuration(goodEpisodes,starttime,endtime);

    if  activity<goodData
        usableForStress=goodData-activity;
    end
end


text:
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Color;
import java.util.Random;

public class VariasCores extends JFrame {
	public class Colorindo extends JPanel {
		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			Random rnd = new Random();

			for(int i = 0; i < 100; i += 10) {
				if(i % 2 == 0)
					g.setColor(new Color(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
				else
					g.setColor(new Color(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));

				//g.fillOval(i + 10, i + 10, 100 - i, 100 - i);  //Formação de Cone
				g.fillOval(i + 20, i + 20, 200 - i * 2,  200 - i * 2);
			}
		}
	}

	public static void main(String[] args) {
		VariasCores cf = new VariasCores();

		Colorindo of = cf.new Colorindo();

		JFrame janela = new JFrame("Criando formas");

		janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		janela.add(of);
		janela.setSize(250, 275);
		janela.setVisible(true);

	}
}

redpajama_set_name: RedPajamaGithub


text:
package opts

import (
	"fmt"

	"github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ulimit"
)

// UlimitOpt defines a map of Ulimits
type UlimitOpt struct {
	values *map[string]*ulimit.Ulimit
}

// NewUlimitOpt creates a new UlimitOpt
func NewUlimitOpt(ref *map[string]*ulimit.Ulimit) *UlimitOpt {
	if ref == nil {
		ref = &map[string]*ulimit.Ulimit{}
	}
	return &UlimitOpt{ref}
}

// Set validates a Ulimit and sets its name as a key in UlimitOpt
func (o *UlimitOpt) Set(val string) error {
	l, err := ulimit.Parse(val)
	if err != nil {
		return err
	}

	(*o.values)[l.Name] = l

	return nil
}

// String returns Ulimit values as a string.
func (o *UlimitOpt) String() string {
	var out []string
	for _, v := range *o.values {
		out = append(out, v.String())
	}

	return fmt.Sprintf("%v", out)
}

// GetList returns a slice of pointers to Ulimits.
func (o *UlimitOpt) GetList() []*ulimit.Ulimit {
	var ulimits []*ulimit.Ulimit
	for _, v := range *o.values {
		ulimits = append(ulimits, v)
	}

	return ulimits
}


text:
class AbstractService

  attr_reader :valid_graphs

  def initialize(dependencies = { })
    @repository = dependencies.fetch(:repository)
    @valid_graphs = %w[all eldis r4d]
  end

  def get details
    set_instance_vars details
    validate
    merge_uri_with! details

    result = @repository.get_one(details)

    wrap_result(result)
  end

  def do_get_all details, opts
    set_instance_vars details, opts
    validate
    @repository.get_all details, opts
  end

  def count details, opts
    raise InvalidDocumentType, "Graph #{@type} is not supported for this object type.  Valid graphs are: #{@valid_graphs.join(', ')}." unless graph_valid?
    @repository.count @type, opts
  end

  protected

  def set_instance_vars details, opts=nil
    @type = details.fetch(:type)
    @detail = details[:detail]
    @resource_id = details[:id] # allow nil

    set_pagination_parameters opts
  end

  def set_pagination_parameters opts
    if opts.present?
      @format = opts[:format]
      @offset = (opts[:offset] || 0).to_i
      @limit = (opts[:limit] || 10).to_i
    end
  end

  def graph_valid?
    valid_graphs.include?(@type)
  end

  def detail_valid?
    ['full', 'short', nil].include? @detail
  end

  def wrap_result result
    raise DocumentNotFound, "No resource found with id #{@resource_id} not found" if result.nil?
    {
      "results" => [result]
    }
  end

  # Note to use this Subclasses must implement #convert_id_to_uri.
  def merge_uri_with! details
    resource_uri = convert_id_to_uri(@resource_id)
    details.merge! :resource_uri => resource_uri
  end

  def convert_id_to_uri id
    raise StandardError, 'Override #convert_id_to_uri in subclass to use #merge_uri_with'
  end

  def wrap_results results, base_url
    number_of_matched_results = @repository.total_results_of_last_query
    wrap_count_common(results, number_of_matched_results, base_url)
  end

  def wrap_count_results results, base_url
    number_of_matched_results = @repository.total_results_of_count_query
    Rails.logger.debug "num matched: #{number_of_matched_results}"
    wrap_count_common(results, number_of_matched_results, base_url)
  end

  # common wrapping JSON structure of openapi queries.  Shared by
  # count and get_all queries.
  def wrap_count_common results, number_of_matched_results, base_url
    results = [] if results.nil?
    {
      'results' => results,
      'metadata' => metadata(base_url, number_of_matched_results)
    }
  end

  def metadata base_url, number_of_matched_results
    offset = @offset.present? ? Integer(@offset) : 0
    limit = @limit.present? ? Integer(@limit) : 10

    params = {:num_results => limit}

    ret = {
     "num_results"   => number_of_matched_results,
     "start_offset"  => offset
    }

    next_offset = offset + limit
    prev_offset = offset - limit

    Rails.logger.debug("next_offset is #{next_offset} current offset: #{offset} limit: #{limit} previous offset is: #{prev_offset}")

    if next_offset < number_of_matched_results
      next_params = params.merge(:start_offset => next_offset).to_query
      ret['next_page'] = add_params_to_uri(base_url, next_params)
    end

    if prev_offset >= 0
      prev_params = params.merge(:start_offset => prev_offset).to_query
      ret['prev_page'] = add_params_to_uri(base_url, prev_params)
    end

    ret
  end

  def validate
    validate_detail
    validate_graph
  end

  def validate_graph
    raise InvalidDocumentType, "Graph #{@type} is not supported for this object type.  Valid graphs are: #{@valid_graphs.join(', ')}." unless graph_valid?
  end

  def validate_detail
    raise LinkedDevelopmentError, 'Detail must be either full, short or unspecified (in which case it defaults to short).' unless detail_valid?
  end

  private

  # Append parameters to a URL string.  Appends parameters properly in
  # the presence of a '?'
  def add_params_to_uri uri, params
    if uri.include? '?'
      "#{uri}&#{params}"
    else
      "#{uri}?#{params}"
    end
  end
end


text:
#ifndef WebDevToolsAgentImpl_h
#define WebDevToolsAgentImpl_h

#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InspectorRuntimeAgent.h"
#include "core/inspector/InspectorSession.h"
#include "core/inspector/InspectorTracingAgent.h"
#include "platform/heap/Handle.h"
#include "public/platform/WebSize.h"
#include "public/platform/WebThread.h"
#include "public/web/WebDevToolsAgent.h"
#include "web/InspectorEmulationAgent.h"
#include "wtf/Forward.h"
#include "wtf/OwnPtr.h"
#include "wtf/Vector.h"

namespace blink {

class GraphicsLayer;
class InspectedFrames;
class InspectorOverlay;
class InspectorResourceContainer;
class InspectorResourceContentLoader;
class LocalFrame;
class Page;
class PlatformGestureEvent;
class PlatformKeyboardEvent;
class PlatformMouseEvent;
class PlatformTouchEvent;
class V8InspectorSession;
class WebDevToolsAgentClient;
class WebFrameWidgetImpl;
class WebInputEvent;
class WebLayerTreeView;
class WebLocalFrameImpl;
class WebString;
class WebViewImpl;

namespace protocol {
class Value;
}

class WebDevToolsAgentImpl final
    : public GarbageCollectedFinalized<WebDevToolsAgentImpl>
    , public WebDevToolsAgent
    , public InspectorEmulationAgent::Client
    , public InspectorTracingAgent::Client
    , public InspectorPageAgent::Client
    , public InspectorSession::Client
    , private WebThread::TaskObserver {
public:
    static WebDevToolsAgentImpl* create(WebLocalFrameImpl*, WebDevToolsAgentClient*);
    ~WebDevToolsAgentImpl() override;
    DECLARE_VIRTUAL_TRACE();

    void willBeDestroyed();
    WebDevToolsAgentClient* client() { return m_client; }
    InspectorOverlay* overlay() const { return m_overlay.get(); }
    void flushPendingProtocolNotifications();
    void dispatchMessageFromFrontend(int sessionId, const String& message);
    static void webViewImplClosed(WebViewImpl*);
    static void webFrameWidgetImplClosed(WebFrameWidgetImpl*);

    // Instrumentation from web/ layer.
    void didCommitLoadForLocalFrame(LocalFrame*);
    bool screencastEnabled();
    void willAddPageOverlay(const GraphicsLayer*);
    void didRemovePageOverlay(const GraphicsLayer*);
    void layerTreeViewChanged(WebLayerTreeView*);

    // WebDevToolsAgent implementation.
    void attach(const WebString& hostId, int sessionId) override;
    void reattach(const WebString& hostId, int sessionId, const WebString& savedState) override;
    void detach() override;
    void continueProgram() override;
    void dispatchOnInspectorBackend(int sessionId, int callId, const WebString& method, const WebString& message) override;
    void inspectElementAt(const WebPoint&) override;
    void failedToRequestDevTools() override;
    WebString evaluateInWebInspectorOverlay(const WebString& script) override;

private:
    WebDevToolsAgentImpl(WebLocalFrameImpl*, WebDevToolsAgentClient*, InspectorOverlay*, bool includeViewAgents);

    // InspectorTracingAgent::Client implementation.
    void enableTracing(const WTF::String& categoryFilter) override;
    void disableTracing() override;

    // InspectorEmulationAgent::Client implementation.
    void setCPUThrottlingRate(double) override;

    // InspectorPageAgent::Client implementation.
    void pageLayoutInvalidated(bool resized) override;
    void setPausedInDebuggerMessage(const String&) override;
    void waitForCreateWindow(LocalFrame*) override;

    // InspectorSession::Client implementation.
    void sendProtocolMessage(int sessionId, int callId, const String& response, const String& state) override;
    void resumeStartup() override;
    void profilingStarted() override;
    void profilingStopped() override;

    // WebThread::TaskObserver implementation.
    void willProcessTask() override;
    void didProcessTask() override;

    void initializeSession(int sessionId, const String& hostId);
    void destroySession();

    friend class WebDevToolsAgent;
    static void runDebuggerTask(int sessionId, PassOwnPtr<WebDevToolsAgent::MessageDescriptor>);

    bool attached() const { return m_session.get(); }

    WebDevToolsAgentClient* m_client;
    Member<WebLocalFrameImpl> m_webLocalFrameImpl;

    Member<InstrumentingAgents> m_instrumentingAgents;
    Member<InspectorResourceContentLoader> m_resourceContentLoader;
    Member<InspectorOverlay> m_overlay;
    Member<InspectedFrames> m_inspectedFrames;
    Member<InspectorResourceContainer> m_resourceContainer;
    OwnPtr<V8InspectorSession> m_v8Session;

    Member<InspectorDOMAgent> m_domAgent;
    Member<InspectorPageAgent> m_pageAgent;
    Member<InspectorResourceAgent> m_resourceAgent;
    Member<InspectorLayerTreeAgent> m_layerTreeAgent;
    Member<InspectorTracingAgent> m_tracingAgent;

    Member<InspectorSession> m_session;
    bool m_includeViewAgents;
    int m_layerTreeId;
};

} // namespace blink

#endif


text:
package com.streamsets.datacollector.execution.manager;

import com.streamsets.datacollector.execution.PipelineState;
import com.streamsets.datacollector.execution.PipelineStatus;
import com.streamsets.pipeline.api.ExecutionMode;
import com.streamsets.pipeline.api.impl.Utils;

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

public class PipelineStateImpl implements PipelineState {
  private final String name;
  private final String rev;
  private final PipelineStatus status;
  private final String message;
  private final long timeStamp;
  private final Map<String, Object> attributes;
  private final String user;
  private final ExecutionMode executionMode;
  private final String metrics;
  private final int retryAttempt;
  private final long nextRetryTimeStamp;

  @SuppressWarnings("unchecked")
  public PipelineStateImpl(String user, String name, String rev, PipelineStatus status, String message, long timeStamp,
    Map<String, Object> attributes, ExecutionMode executionMode, String metrics, int retryAttempt, long nextRetryTimeStamp) {
    this.name = name;
    this.rev = rev;
    this.user = user;
    this.status = status;
    this.message = message;
    this.timeStamp = timeStamp;
    this.attributes = (Map) ((attributes != null) ? new HashMap<>(attributes) : new HashMap<>());
    this.executionMode = executionMode;
    this.metrics = metrics;
    this.retryAttempt = retryAttempt;
    this.nextRetryTimeStamp = nextRetryTimeStamp;
  }

  @Override
  public String getRev() {
    return rev;
  }

  @Override
  public PipelineStatus getStatus() {
    return this.status;
  }

  @Override
  public String getMessage() {
    return this.message;
  }

  @Override
  public long getTimeStamp() {
    return timeStamp;
  }

  @Override
  public String getName() {
    return name;
  }

  @Override
  public Map<String, Object> getAttributes() {
    return attributes;
  }

  @Override
  public String toString() {
    return Utils.format("PipelineState[name='{}' rev='{}' state='{}' message='{}' timeStamp='{}' attributes='{}']",
      getName(), getRev(), getStatus().name(), getMessage(), getTimeStamp(), getAttributes());
  }

  @Override
  public String getUser() {
    return user;
  }

  @Override
  public ExecutionMode getExecutionMode() {
    return executionMode;
  }

  @Override
  public String getMetrics() {
    return metrics;
  }

  @Override
  public int getRetryAttempt() {
    return retryAttempt;
  }

  @Override
  public long getNextRetryTimeStamp() {
    return nextRetryTimeStamp;
  }
}


text:
title: Async Validation
description: Using async validation with vee-validate
order: 3
---

# Async Validation

This is an example of field that uses an async rule to check if an email is available.

<code-sandbox id="vee-validate-async-validation-xr0t9" title="vee-validate Async Validation"></code-sandbox>


text:
#if !defined(BOOST_SPIRIT_X3_TESTING_JUNE_05_2014_00422PM)
#define BOOST_SPIRIT_X3_TESTING_JUNE_05_2014_00422PM

namespace boost { namespace spirit { namespace x3 { namespace testing
{
    ////////////////////////////////////////////////////////////////////////////
    //
    //  Test utility
    //
    //  The test function accepts a file loaded in memory. The 'test_file'
    //  range param points to the data contained in the file. This file
    //  contains two parts.
    //
    //      1) The source input for testing
    //      2) The expected result.
    //
    //  The first part of the file is sent to the generator function
    //  'gen' which returns a string. This generated string is then compared
    //  to the contents of the second (expected result) part.
    //
    //  The second part is demarcated by the string parameter 'demarcation'
    //  which defaults to "<**expected**>". The expected template may include
    //  embedded regular expressions marked-up within re_prefix and re_suffix
    //  parameter tags. For example, given the default RE markup ("<%" and
    //  "%>"), this template:
    //
    //      <%[0-9]+%>
    //
    //  will match any integer in the source input being tested. The function
    //  will return the first non-matching position. The flag full_match
    //  indicates a full match. It is possible for returned pos to be
    //  at the end of in (in.end()) while still returning full_match ==
    //  false. In that case, we have a partial match.
    //
    //  Here's an example of a test file:
    //
    //      Hello World, I am Joel. This is a test.
    //
    //      <**expected**>
    //      Hello World, I am <%[a-zA-Z]+%>. This is a test.
    //
    ////////////////////////////////////////////////////////////////////////////

    template <typename Iterator>
    struct test_result
    {
        Iterator pos;
        bool full_match;
    };

    template <typename Range, typename F>
    test_result<typename Range::const_iterator>
    test(
        Range test_file
      , F gen
      , char const* demarcation = "<**expected**>"
      , char const* re_prefix = "<%"
      , char const* re_suffix = "%>"
   );

}}}}

#endif


text:
<!DOCTYPE html>

    <title>Berkshire Hathaway INC</title>

   BERKSHIRE HATHAWAY INC. 3555 Farnam Street Suite 1440 Omaha, NE 68131 Official Home Page

  A Message From Warren E. Buffet

New Releases Updated July 1, 2014

  Annual & Interim Reports Updated May 2, 2014

Warren Buffet's Letters to Berkshire Shareholders Updated March 1, 2014

  Link to SEC filings

Charlie Munger's Letters to Wesco Shareholders

  Corporate Governance

Annual Meeting Information

  Links to Berkshire Subsidiary Companies

Comparative Rights and Relative Prices of Class A and B Stock Updated January 20, 2010

 Owner's Manual  To view the Owner's Manual you may use Adobe Acrobat® Reader® software. Click  here to download. Updated March 1, 2014

  Letters from Warren E. Buffet Regarding Pledges to Make Gifts of Berkshire Stock  Updated August 30, 2012

   FOR A FREE INSURANCE RATE QUOTE THAT COULD SAVE YOU SUBSTANTIAL MONEY WWW.GEICO.COM OR CALL 1-888-395-6349, 24 HOURS A DAY

  If you have any comments about our WEB page, you can either write us at the address shown above or e-mail is at berkshire@berkshirehathaway.com. However, due to the limited number of personnel in our corporate office, we are unable to provide a direct response.

  Legal Disclaimer

 Copyright © 1978-2014Berkshire Hathaway Inc.


text:
package tv.baokan.baokanandroid.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * 全局的配置信息
 */
public class SharedPreferencesUtils {

    // 新闻详情字体
    public static final String DETAIL_FONT = "font_key";

    // 配置文件名称
    private static final String CONFIG_FILE_NAME = "config";

    /**
     * 设置一个boolean类型配置
     *
     * @param context context
     * @param key     键
     * @param value   值
     */
    public static void setBoolean(Context context, String key, boolean value) {
        SharedPreferences sp = context.getSharedPreferences(CONFIG_FILE_NAME, Context.MODE_PRIVATE);
        sp.edit().putBoolean(key, value).apply();
    }

    /**
     * 获取一个boolean类型配置
     *
     * @param context  context
     * @param key      键
     * @param defValue 缺省值
     * @return 根据key查找到value
     */
    public static boolean getBoolean(Context context, String key, boolean defValue) {
        SharedPreferences sp = context.getSharedPreferences(CONFIG_FILE_NAME, Context.MODE_PRIVATE);
        return sp.getBoolean(key, defValue);
    }

    /**
     * 设置一个String类型配置
     *
     * @param context context
     * @param key     键
     * @param value   值
     */
    public static void setString(Context context, String key, String value) {
        SharedPreferences sp = context.getSharedPreferences(CONFIG_FILE_NAME, Context.MODE_PRIVATE);
        sp.edit().putString(key, value).apply();
    }

    /**
     * 获取一个String类型配置
     *
     * @param context  context
     * @param key      键
     * @param defValue 缺省值
     * @return 根据key查找到value
     */
    public static String getString(Context context, String key, String defValue) {
        SharedPreferences sp = context.getSharedPreferences(CONFIG_FILE_NAME, Context.MODE_PRIVATE);
        return sp.getString(key, defValue);
    }

    /**
     * 设置一个int类型配置
     *
     * @param context context
     * @param key     键
     * @param value   值
     */
    public static void setInt(Context context, String key, int value) {
        SharedPreferences sp = context.getSharedPreferences(CONFIG_FILE_NAME, Context.MODE_PRIVATE);
        sp.edit().putInt(key, value).apply();
    }

    /**
     * 获取一个int类型配置
     *
     * @param context  context
     * @param key      键
     * @param defValue 缺省值
     * @return 根据key查找到value
     */
    public static int getInt(Context context, String key, int defValue) {
        SharedPreferences sp = context.getSharedPreferences(CONFIG_FILE_NAME, Context.MODE_PRIVATE);
        return sp.getInt(key, defValue);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="rigthtPadding" format="dimension"/>

    <declare-styleable name="DragLayoutOne">
        <attr name="rigthtPadding"/>
    </declare-styleable>

    <declare-styleable name="CircleImageView">
        <attr name="outCircleColor" format="color"/>
        <attr name="outCircleWidth" format="dimension"/>
    </declare-styleable>

    <declare-styleable name="FlyBanner">
        <attr name="points_visibility" format="boolean"/>
        <attr name="points_position" format="enum">
            <enum name="CENTER" value="0"/>
            <enum name="LEFT" value="1"/>
            <enum name="RIGHT" value="2"/>
        </attr>
        <attr name="points_container_background" format="reference|color"/>
    </declare-styleable>

    <declare-styleable name="BBox">
        <attr name="check_style">
            <enum name="fork" value="0" />
            <enum name="hook" value="1" />
        </attr>
        <attr name="color_before" format="color" />
        <attr name="text_color" format="color"></attr>
        <attr name="color_after" format="color" />
        <attr name="check_text" format="string" />
        <attr name="show_border" format="boolean"/>
        <attr name="is_circle_border" format="boolean"/>
    </declare-styleable>

    <declare-styleable name="CouponView">
        <attr name="cv_semicircle_gap" format="dimension|reference"/>
        <attr name="cv_semicircle_radius" format="dimension|reference"/>
        <attr name="cv_semicircle_color" format="color|reference"/>
        <attr name="cv_dash_line_length" format="dimension|reference"/>
        <attr name="cv_dash_line_gap" format="dimension|reference"/>
        <attr name="cv_dash_line_height" format="dimension|reference"/>
        <attr name="cv_dash_line_color" format="color|reference"/>
        <attr name="cv_is_semicircle_top" format="boolean|reference"/>
        <attr name="cv_is_semicircle_bottom" format="boolean|reference"/>
        <attr name="cv_is_semicircle_left" format="boolean|reference"/>
        <attr name="cv_is_semicircle_right" format="boolean|reference"/>
        <attr name="cv_is_dash_line_top" format="boolean|reference"/>
        <attr name="cv_is_dash_line_bottom" format="boolean|reference"/>
        <attr name="cv_is_dash_line_left" format="boolean|reference"/>
        <attr name="cv_is_dash_line_right" format="boolean|reference"/>
        <attr name="cv_dash_line_margin_top" format="dimension|reference"/>
        <attr name="cv_dash_line_margin_bottom" format="dimension|reference"/>
        <attr name="cv_dash_line_margin_left" format="dimension|reference"/>
        <attr name="cv_dash_line_margin_right" format="dimension|reference"/>
    </declare-styleable>
</resources>


text:
This tutorial is a basic guide on how to create a simple web application using Yolk.
We'll look at each of the various components and aspects of an application, how they're
implemented and how they can be enhanced and expanded.

## Contents

* [Bootstrapping](10-bootstrap.md)
  * Directory Structure
  * Composer
  * Entrypoints
* [Application Class](20-application.md)
 * Services
 * Configuration
 * Routes
* [Controllers](30-controllers.md)
 * Accessing a database
 * Validating user input
* [Views](40-views.md)
* [Middleware](50-middleware.md)
 * Authentication


text:
package remote

import (
	"crypto/x509"
	"encoding/json"
	"errors"

	"github.com/cloudflare/cfssl/api/client"
	"github.com/cloudflare/cfssl/config"
	cferr "github.com/cloudflare/cfssl/errors"
	"github.com/cloudflare/cfssl/info"
	"github.com/cloudflare/cfssl/signer"
)

// A Signer represents a CFSSL instance running as signing server.
// fulfills the signer.Signer interface
type Signer struct {
	policy *config.Signing
}

// NewSigner creates a new remote Signer directly from a
// signing policy.
func NewSigner(policy *config.Signing) (*Signer, error) {
	if policy != nil {
		if !policy.Valid() {
			return nil, cferr.New(cferr.PolicyError,
				cferr.InvalidPolicy)
		}
		return &Signer{policy: policy}, nil
	}

	return nil, cferr.New(cferr.PolicyError,
		cferr.InvalidPolicy)
}

// Sign sends a signature request to the remote CFSSL server,
// receiving a signed certificate or an error in response. The hostname,
// csr, and profileName are used as with a local signing operation, and
// the label is used to select a signing root in a multi-root CA.
func (s *Signer) Sign(req signer.SignRequest) (cert []byte, err error) {
	resp, err := s.remoteOp(req, req.Profile, "sign")
	if err != nil {
		return
	}
	if cert, ok := resp.([]byte); ok {
		return cert, nil
	}
	return
}

// Info sends an info request to the remote CFSSL server, receiving an
// Resp struct or an error in response.
func (s *Signer) Info(req info.Req) (resp *info.Resp, err error) {
	respInterface, err := s.remoteOp(req, req.Profile, "info")
	if err != nil {
		return
	}
	if resp, ok := respInterface.(*info.Resp); ok {
		return resp, nil
	}
	return
}

// Helper function to perform a remote sign or info request.
func (s *Signer) remoteOp(req interface{}, profile, target string) (resp interface{}, err error) {
	jsonData, err := json.Marshal(req)
	if err != nil {
		return nil, cferr.Wrap(cferr.APIClientError, cferr.JSONError, err)
	}

	p, err := signer.Profile(s, profile)
	if err != nil {
		return
	}

	server := client.NewServer(p.RemoteServer)
	if server == nil {
		return nil, cferr.Wrap(cferr.PolicyError, cferr.InvalidRequest,
			errors.New("failed to connect to remote"))
	}

	// There's no auth provider for the "info" method
	if target == "info" {
		resp, err = server.Info(jsonData)
	} else if p.Provider != nil {
		resp, err = server.AuthSign(jsonData, nil, p.Provider)
	} else {
		resp, err = server.Sign(jsonData)
	}

	if err != nil {
		return nil, err
	}

	return
}

// SigAlgo returns the RSA signer's signature algorithm.
func (s *Signer) SigAlgo() x509.SignatureAlgorithm {
	// TODO: implement this as a remote info call
	return x509.UnknownSignatureAlgorithm
}

// SetPolicy sets the signer's signature policy.
func (s *Signer) SetPolicy(policy *config.Signing) {
	s.policy = policy
}

// Policy returns the signer's policy.
func (s *Signer) Policy() *config.Signing {
	return s.policy
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>tsen</groupId>
    <artifactId>tsen.root</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>TSEN :: Root</name>
    <description>TSEN</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jdk.target>1.8</jdk.target>
        <kmf.version>4.5.1</kmf.version>
        <kotlin.version>0.8.11</kotlin.version>
    </properties>

    <modules>
        <module>tsen.model</module>
        <module>tsen.context</module>
        <module>tsen.regulation</module>
        <module>tsen.ihm</module>
        <module>tsen.lob</module>
        <module>tsen.ade</module>
        <module>tsen.webapp</module>
        <module>appli_tsen</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <!--<dependency>
            <groupId>nz.ac.waikato.cms.weka</groupId>
            <artifactId>weka-dev</artifactId>
            <version>3.7.12</version>
        </dependency>-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.9</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!--<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.1.2</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin> -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <developers>

        <developer>
            <name>jezequel quentin</name>
            <id>jezequel.quentin</id>
            <email>quentinj22@gmail.com</email>
            <roles>
                <role>admin</role>
                <role>developer</role>
            </roles>
            <timezone>+1</timezone>
        </developer>
        <developer>
            <name>leprince alexis</name>
            <id>leprince.alexis</id>
            <email>alexis.leprince@etudiant.univ-rennes1.fr</email>
            <roles>
                <role>admin</role>
                <role>developer</role>
            </roles>
            <timezone>+1</timezone>
        </developer>
        <developer>
            <name>vansaingele nicolas</name>
            <id>vansaingele.nicolas</id>
            <email>n.vansaingele@gmail.com</email>
            <roles>
                <role>admin</role>
                <role>developer</role>
            </roles>
            <timezone>+1</timezone>
        </developer>
        <developer>
            <name>leblanc kevin</name>
            <id>leblanc.kevin</id>
            <email>kevin.lb22@gmail.com</email>
            <roles>
                <role>admin</role>
                <role>developer</role>
            </roles>
            <timezone>+1</timezone>
        </developer>

        <developer>
            <name>Mathias Billoir</name>
            <id>mathias.billoir</id>
            <email>mathias.billoir@gmail.com</email>
            <roles>
                <role>developer</role>
            </roles>
            <timezone>+2</timezone>
        </developer>
    </developers>

</project>


text:
package com.bitdubai.reference_niche_wallet.bitcoin_wallet.common.Views;

public class SectionItem implements Item {

    private final String title;

    public SectionItem(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    @Override
    public boolean isSection() {
        return true;
    }

}


text:
#include <cmath>
#include <vector>

#include <fbjni/fbjni.h>

#include "expect.h"

using namespace facebook::jni;

local_ref<jbooleanArray> testMakeBoolArray(alias_ref<jclass>, jint size) {
  return make_boolean_array(size);
}

local_ref<jbyteArray> testMakeByteArray(alias_ref<jclass>, jint size) {
  return make_byte_array(size);
}

local_ref<jcharArray> testMakeCharArray(alias_ref<jclass>, jint size) {
  return make_char_array(size);
}

local_ref<jshortArray> testMakeShortArray(alias_ref<jclass>, jint size) {
  return make_short_array(size);
}

local_ref<jintArray> testMakeIntArray(alias_ref<jclass>, jint size) {
  return make_int_array(size);
}

local_ref<jlongArray> testMakeLongArray(alias_ref<jclass>, jint size) {
  return make_long_array(size);
}

local_ref<jfloatArray> testMakeFloatArray(alias_ref<jclass>, jint size) {
  return make_float_array(size);
}

local_ref<jdoubleArray> testMakeDoubleArray(alias_ref<jclass>, jint size) {
  return make_double_array(size);
}

jboolean testGetSetBooleanArray(alias_ref<jclass>, alias_ref<jbooleanArray> array) {
  EXPECT(array);

  auto n = array->size();
  EXPECT(n == 2);

  auto vec = std::vector<jboolean>(n);
  array->getRegion(0, n, vec.data());
  auto smartbuf = array->getRegion(0, n);

  EXPECT(!vec[0] && vec[1]);
  EXPECT(!smartbuf[0] && smartbuf[1]);

  for (auto i = 0u; i < n; ++i) {
    smartbuf[i] = !smartbuf[i];
  }

  array->setRegion(0, n, smartbuf.get());

  return JNI_TRUE;
}

jboolean testPinBooleanArray(alias_ref<jclass>, alias_ref<jbooleanArray> array) {
  EXPECT(array);

  auto n = static_cast<jboolean>(array->size());
  auto pinned = array->pin();

  EXPECT(!pinned[0] && pinned[1]);

  for (auto i = 0; i < n; ++i) {
    pinned[i] = !pinned[i];
  }

  return JNI_TRUE;
}

constexpr double kEps = 1e-3;

template <typename JArrayType>
jboolean testGetSetArray(alias_ref<jclass>, alias_ref<JArrayType> array) {
  EXPECT(array);
  int n = array->size();
  auto vec = std::vector<typename jtype_traits<JArrayType>::entry_type>(n);
  array->getRegion(0, n, vec.data());
  auto smartbuf = array->getRegion(0, n);

  for (auto i = 0; i < n; ++i) {
    EXPECT(std::abs(static_cast<double>(vec[i] - i)) < kEps);
    EXPECT(std::abs(static_cast<double>(smartbuf[i] - i)) < kEps);
  }

  for (auto i = 0; i < n; ++i) {
    smartbuf[i] *= 2;
  }

  array->setRegion(0, n, smartbuf.get());

  return JNI_TRUE;
}

template <typename JArrayType>
jboolean testPinArray(alias_ref<jclass>, alias_ref<JArrayType> array) {
  EXPECT(array);

  int n = array->size();
  auto pinned = array->pin();

  for (auto i = 0; i < n; ++i) {
    EXPECT(std::abs(static_cast<double>(pinned[i] - i)) < kEps);
  }

  for (auto i = 0; i < n; ++i) {
    pinned[i] *= 2;
  }

  return JNI_TRUE;
}

template <typename JArrayType>
jboolean testPinArrayRegion(alias_ref<jclass>, alias_ref<JArrayType> array) {
  EXPECT(array);
  EXPECT(array->size() > 5);

  int splits[] = {0, 1, 3, static_cast<int>(array->size())};
  for (int i = 0; i < 3; i++) {
    auto pinned = array->pinRegion(splits[i], splits[i + 1] - splits[i]);
    for (int j = 0; j < static_cast<int>(pinned.size()); j++) {
      EXPECT(std::abs(static_cast<double>(pinned[j] - j - splits[i])) < kEps);
      pinned[j] *= 2;
    }
  }
  return JNI_TRUE;
}

template <typename JArrayType>
jboolean testPinArrayCritical(alias_ref<jclass>, alias_ref<JArrayType> array) {
  EXPECT(array);

  int n = array->size();
  auto pinned = array->pinCritical();

  for (auto i = 0; i < n; ++i) {
    EXPECT(std::abs(static_cast<double>(pinned[i] - i)) < kEps);
  }

  for (auto i = 0; i < n; ++i) {
    pinned[i] *= 2;
  }

  return JNI_TRUE;
}

jboolean testIndexOutOfBoundsInRegions(alias_ref<jclass>) {
  constexpr auto N = 7;
  constexpr auto TOO_MUCH = 10;
  constexpr auto NEGATIVE = -1;

  auto array = make_int_array(N);

  try {
    auto buf = array->getRegion(TOO_MUCH, N);
    EXPECT(false);
  } catch (JniException& ex) {
  }

  try {
    auto buf = array->getRegion(NEGATIVE, N);
    EXPECT(false);
  } catch (JniException& ex) {
  }

  try {
    auto vec = std::vector<jint>(TOO_MUCH);
    array->setRegion(0, vec.size(), vec.data());
    EXPECT(false);
  } catch (JniException& ex) {
  }

  try {
    auto vec = std::vector<jint>(1);
    array->setRegion(NEGATIVE, vec.size(), vec.data());
    EXPECT(false);
  } catch (JniException& ex) {
  }

  return JNI_TRUE;
}

jboolean TestBooleanArrayIndexing(alias_ref<jobject> self, alias_ref<jbooleanArray> input, jint idx) {
  auto array = input->pin();
  jboolean value = array[idx];
  return value;
}

jint TestIntegerArrayIndexing(alias_ref<jobject> self, alias_ref<jintArray> input, jint idx) {
  auto array = input->pin();
  jint value = array[idx];
  return value;
}

jsize TestIntegerArraySize(alias_ref<jobject> self, alias_ref<jintArray> input) {
  auto array = input->pin();
  jsize size = array.size();
  return size;
}

alias_ref<jintArray> TestIntegerArrayIncrement(alias_ref<jobject> self, alias_ref<jintArray> input) {
  auto array = input->pin();
  for (size_t ii = 0; ii < array.size(); ii++) {
    array[ii]++;
  }
  return input;
}

void TestIntegerArrayMoveAssignment(alias_ref<jobject> self, alias_ref<jintArray> input) {
  auto array = input->pin();
  array[0] = 0;
  array.release();
}

jboolean isPinnedArrayACopy(alias_ref<jobject>, alias_ref<jintArray> input) {
  return input->pin().isCopy();
}

jboolean testCopiedPinnedArray(alias_ref<jobject>, alias_ref<jintArray> input) {
  EXPECT(input->size() > 0);
  input->pin()[0] = 100;
  auto pin = input->pin();
  EXPECT(pin.isCopy());
  EXPECT(pin[0] == input->pin()[0]);

  pin[0] = 200;
  EXPECT(input->pin()[0] == 100);

  pin.commit();
  EXPECT(input->pin()[0] == 200);
  pin[0] = 300;
  EXPECT(input->pin()[0] == 200);
  pin.abort();
  EXPECT(input->pin()[0] == 200);
  pin = input->pin();
  pin[0] = 400;
  pin.release();
  EXPECT(input->pin()[0] == 400);
  return JNI_TRUE;
}

jboolean testNonCopiedPinnedArray(alias_ref<jobject>, alias_ref<jintArray> input) {
  EXPECT(input->size() > 0);
  auto pin = input->pin();
  EXPECT(!pin.isCopy());
  EXPECT(pin[0] == input->pin()[0]);
  pin.commit();
  EXPECT(pin[0] == input->pin()[0]);
  pin[0] = 100;
  EXPECT(pin[0] == input->pin()[0]);
  input->pin()[0] = 200;
  EXPECT(pin[0] == input->pin()[0]);
  pin.abort();
  return JNI_TRUE;
}

void RegisterPrimitiveArrayTests() {
  registerNatives("com/facebook/jni/PrimitiveArrayTests", {
    makeNativeMethod("nativeTestMakeBooleanArray", testMakeBoolArray),
    makeNativeMethod("nativeTestMakeByteArray", testMakeByteArray),
    makeNativeMethod("nativeTestMakeCharArray", testMakeCharArray),
    makeNativeMethod("nativeTestMakeShortArray", testMakeShortArray),
    makeNativeMethod("nativeTestMakeIntArray", testMakeIntArray),
    makeNativeMethod("nativeTestMakeLongArray", testMakeLongArray),
    makeNativeMethod("nativeTestMakeFloatArray", testMakeFloatArray),
    makeNativeMethod("nativeTestMakeDoubleArray", testMakeDoubleArray),

    makeNativeMethod("nativeTestGetSetBooleanArray", testGetSetBooleanArray),
    makeNativeMethod("nativeTestGetSetByteArray", testGetSetArray<jbyteArray>),
    makeNativeMethod("nativeTestGetSetCharArray", testGetSetArray<jcharArray>),
    makeNativeMethod("nativeTestGetSetShortArray", testGetSetArray<jshortArray>),
    makeNativeMethod("nativeTestGetSetIntArray", testGetSetArray<jintArray>),
    makeNativeMethod("nativeTestGetSetLongArray", testGetSetArray<jlongArray>),
    makeNativeMethod("nativeTestGetSetFloatArray", testGetSetArray<jfloatArray>),
    makeNativeMethod("nativeTestGetSetDoubleArray", testGetSetArray<jdoubleArray>),

    makeNativeMethod("nativeTestPinBooleanArray", testPinBooleanArray),
    makeNativeMethod("nativeTestPinByteArray", testPinArray<jbyteArray>),
    makeNativeMethod("nativeTestPinCharArray", testPinArray<jcharArray>),
    makeNativeMethod("nativeTestPinShortArray", testPinArray<jshortArray>),
    makeNativeMethod("nativeTestPinIntArray", testPinArray<jintArray>),
    makeNativeMethod("nativeTestPinLongArray", testPinArray<jlongArray>),
    makeNativeMethod("nativeTestPinFloatArray", testPinArray<jfloatArray>),
    makeNativeMethod("nativeTestPinDoubleArray", testPinArray<jdoubleArray>),

    makeNativeMethod("nativeTestPinByteArrayRegion", testPinArrayRegion<jbyteArray>),
    makeNativeMethod("nativeTestPinCharArrayRegion", testPinArrayRegion<jcharArray>),
    makeNativeMethod("nativeTestPinShortArrayRegion", testPinArrayRegion<jshortArray>),
    makeNativeMethod("nativeTestPinIntArrayRegion", testPinArrayRegion<jintArray>),
    makeNativeMethod("nativeTestPinLongArrayRegion", testPinArrayRegion<jlongArray>),
    makeNativeMethod("nativeTestPinFloatArrayRegion", testPinArrayRegion<jfloatArray>),
    makeNativeMethod("nativeTestPinDoubleArrayRegion", testPinArrayRegion<jdoubleArray>),

    makeNativeMethod("nativeTestPinByteArrayCritical", testPinArrayCritical<jbyteArray>),
    makeNativeMethod("nativeTestPinCharArrayCritical", testPinArrayCritical<jcharArray>),
    makeNativeMethod("nativeTestPinShortArrayCritical", testPinArrayCritical<jshortArray>),
    makeNativeMethod("nativeTestPinIntArrayCritical", testPinArrayCritical<jintArray>),
    makeNativeMethod("nativeTestPinLongArrayCritical", testPinArrayCritical<jlongArray>),
    makeNativeMethod("nativeTestPinFloatArrayCritical", testPinArrayCritical<jfloatArray>),
    makeNativeMethod("nativeTestPinDoubleArrayCritical", testPinArrayCritical<jdoubleArray>),

    makeNativeMethod("nativeTestIndexOutOfBoundsInRegions", testIndexOutOfBoundsInRegions),

    makeNativeMethod("nativeTestBooleanArrayIndexing",
                     TestBooleanArrayIndexing),
    makeNativeMethod("nativeTestIntegerArrayIndexing",
                     TestIntegerArrayIndexing),
    makeNativeMethod("nativeTestIntegerArraySize",
                     TestIntegerArraySize),
    makeNativeMethod("nativeTestIntegerArrayIncrement",
                     TestIntegerArrayIncrement),
    makeNativeMethod("nativeTestIntegerArrayMoveAssignment",
                     TestIntegerArrayMoveAssignment),

    makeNativeMethod("nativeIsPinnedArrayACopy", isPinnedArrayACopy),
    makeNativeMethod("nativeTestCopiedPinnedArray",
                     testCopiedPinnedArray),
    makeNativeMethod("nativeTestNonCopiedPinnedArray",
                     testNonCopiedPinnedArray),
  });
}


text:
from django.conf.urls.defaults import patterns, url
from app import views

urlpatterns = patterns('',
    # Examples:
    url(r'^$', views.TestView.as_view(), name='test_view'),
)


text:
module Doing
  class DoingExport
    def self.settings
      {
        trigger: 'doing'
      }
    end

    def self.render(wwid, items, variables: {})
      return if items.nil?

      content = Doing::Items.new
      items.each do |item|
        content.add_section(item.section, log: false)
        content.push(item)
      end

      out = []
      content.sections.each do |section|
        out.push(section.original)
        is = content.in_section(section.title).sort_by { |i| [i.date, i.title] }
        is.reverse! if Doing.setting('doing_file_sort').normalize_order == :desc
        is.each { |item| out.push(item.to_s) }
      end

      Doing::Pager.page out.join("\n")
    end

    Doing::Plugins.register 'doing', :export, self
  end
end


text:
{% extends "layout.html" %} {% block page_title %} Example - Forms {% endblock %} {% block content %}

  {% include "includes/phase_banner_alpha.html" %}

  {% include "custom_inc/backlink.html" %}

      <form method="get" action="/design_patterns/routing_questions/dredging" class="form">

      {{formData | safe}}

          Are you doing repairs or alterations to the riverbank?

        <fieldset>
          <legend class="visuallyhidden">
            Are you doing repairs or alterations to the riverbank?
          </legend>

              <input type="radio" name="riverbanks" value="1">
              Yes

              <input type="radio" name="riverbanks" value="0">
              No

        </fieldset>

          <input type="submit" class="button" value="Continue" />

      </form>

{% endblock %}


text:
import copy
import threading
import asyncio
import six
from django.http import HttpResponseBadRequest
from channels.generic.http import AsyncHttpConsumer
from channels.http import AsgiRequest
from channels.db import database_sync_to_async
from .utils import add_default_headers

MAX_PENDING = 10

class Listener(object):
	def __init__(self):
		self.loop = asyncio.get_event_loop()
		self.aevent = asyncio.Event()
		self.user_id = ''
		self.channels = set()
		self.channel_items = {}
		self.overflow = False
		self.error = ''

	def wake_threadsafe(self):
		self.loop.call_soon_threadsafe(self.aevent.set)

class ListenerManager(object):
	def __init__(self):
		self.lock = threading.Lock()
		self.listeners_by_channel = {}

	def add_listener(self, listener):
		self.lock.acquire()
		try:
			for channel in listener.channels:
				clisteners = self.listeners_by_channel.get(channel)
				if clisteners is None:
					clisteners = set()
					self.listeners_by_channel[channel] = clisteners
				clisteners.add(listener)
		finally:
			self.lock.release()

	def remove_listener(self, listener):
		self.lock.acquire()
		try:
			for channel in listener.channels:
				clisteners = self.listeners_by_channel.get(channel)
				clisteners.remove(listener)
				if len(clisteners) == 0:
					del self.listeners_by_channel[channel]
		finally:
			self.lock.release()

	def add_to_queues(self, channel, event):
		self.lock.acquire()
		try:
			wake = []
			listeners = self.listeners_by_channel.get(channel, set())
			for l in listeners:
				items = l.channel_items.get(channel)
				if items is None:
					items = []
					l.channel_items[channel] = items
				if len(items) < MAX_PENDING:
					items.append(event)
					wake.append(l)
				else:
					l.overflow = True
			for l in wake:
				l.wake_threadsafe()
		finally:
			self.lock.release()

	def kick(self, user_id, channel):
		self.lock.acquire()
		try:
			wake = []
			listeners = self.listeners_by_channel.get(channel, set())
			for l in listeners:
				if l.user_id == user_id:
					msg = 'Permission denied to channels: %s' % channel
					l.error = {'condition': 'forbidden', 'text': msg, 'channels': [channel]}
					wake.append(l)
			for l in wake:
				l.wake_threadsafe()
		finally:
			self.lock.release()

listener_manager = ListenerManager()

def get_listener_manager():
	return listener_manager

class EventsConsumer(AsyncHttpConsumer):
	# this function adapted from channels 2.1.5
	async def __call__(self, scope, receive, send):
		"""
		Async entrypoint - concatenates body fragments and hands off control
		to ``self.handle`` when the body has been completely received.
		"""
		self.scope = scope
		self.send = send
		body = []
		try:
			while True:
				message = await receive()
				if message["type"] == "http.disconnect":
					return
				else:
					if "body" in message:
						body.append(message["body"])
					if not message.get("more_body"):
						await self.handle(b"".join(body))
		finally:
			await self.disconnect()

	@database_sync_to_async
	def parse_request(self, request):
		from .eventrequest import EventRequest

		kwargs = self.scope['url_route']['kwargs']

		return EventRequest(request, view_kwargs=kwargs)

	@database_sync_to_async
	def get_events(self, event_request):
		from .eventstream import get_events

		return get_events(event_request)

	async def handle(self, body):
		from django_grip import GripMiddleware
		from .eventrequest import EventRequest
		from .eventstream import EventPermissionError
		from .utils import sse_error_response

		self.listener = None

		request = AsgiRequest(self.scope, body)

		def dummy_get_response(request):
			return None

		gm = GripMiddleware(dummy_get_response)
		gm.process_request(request)

		if 'user' in self.scope:
			request.user = self.scope['user']

		if 'session' in self.scope:
			request.session = self.scope['session']

		try:
			event_request = await self.parse_request(request)
			response = None
		except EventRequest.ResumeNotAllowedError as e:
			response = HttpResponseBadRequest(
				'Invalid request: %s.\n' % str(e))
		except EventRequest.GripError as e:
			if request.grip.proxied:
				response = sse_error_response(
					'internal-error',
					'Invalid internal request.')
			else:
				response = sse_error_response(
					'bad-request',
					'Invalid request: %s.' % str(e))
		except EventRequest.Error as e:
			response = sse_error_response(
				'bad-request',
				'Invalid request: %s.' % str(e))

		# for grip requests, prepare immediate response
		if not response and request.grip.proxied:
			try:
				event_response = await self.get_events(event_request)
				response = event_response.to_http_response(request)
			except EventPermissionError as e:
				response = sse_error_response(
					'forbidden',
					str(e),
					{'channels': e.channels})

		extra_headers = {}
		add_default_headers(extra_headers)

		# if this was a grip request or we encountered an error, respond now
		if response:
			response = gm.process_response(request, response)

			headers = []
			for name, value in response.items():
				if isinstance(name, six.text_type):
					name = name.encode('utf-8')
				if isinstance(value, six.text_type):
					value = value.encode('utf-8')
				headers.append((name, value))

			for name, value in extra_headers.items():
				if isinstance(name, six.text_type):
					name = name.encode('utf-8')
				if isinstance(value, six.text_type):
					value = value.encode('utf-8')
				headers.append((name, value))

			await self.send_response(
				response.status_code,
				response.content,
				headers=headers
			)
			return

		# if we got here then the request was not a grip request, and there
		#   were no errors, so we can begin a local stream response

		headers = [(six.b('Content-Type'), six.b('text/event-stream'))]
		for name, value in extra_headers.items():
			if isinstance(name, six.text_type):
				name = name.encode('utf-8')
			if isinstance(value, six.text_type):
				value = value.encode('utf-8')
			headers.append((name, value))

		await self.send_headers(headers=headers)

		self.listener = Listener()
		self.is_streaming = True

		asyncio.get_event_loop().create_task(self.stream(event_request))

	async def stream(self, event_request):
		from .eventstream import EventPermissionError
		from .utils import sse_encode_event, make_id

		self.listener.user_id = event_request.user.pk if event_request.user else 'anonymous'
		self.listener.channels = event_request.channels

		lm = get_listener_manager()

		lm.add_listener(self.listener)

		first_result = True

		while self.is_streaming:
			try:
				event_response = await self.get_events(event_request)
			except EventPermissionError as e:
				data = {
					'condition': 'forbidden',
					'text': str(e),
					'channels': e.channels,
				}
				body = sse_encode_event('stream-error', data, event_id='error')
				await self.send_body(body.encode('utf-8'))
				break

			last_ids = copy.deepcopy(event_response.channel_last_ids)
			event_id = make_id(last_ids)

			body = ''

			if first_result:
				first_result = False

				# include padding on the first result
				body += ':' + (' ' * 2048) + '\n\n'
				body += 'event: stream-open\ndata:\n\n'

			if len(event_response.channel_reset) > 0:
				body += sse_encode_event(
					'stream-reset',
					{'channels': list(event_response.channel_reset)},
					event_id=event_id)

			for channel, items in event_response.channel_items.items():
				for item in items:
					last_ids[channel] = item.id
					event_id = make_id(last_ids)
					body += sse_encode_event(
						item.type,
						item.data,
						event_id=event_id)

			await self.send_body(body.encode('utf-8'), more_body=True)

			if len(event_response.channel_more) > 0:
				# read again immediately
				continue

			# FIXME: reconcile without re-reading from db

			lm.lock.acquire()
			conflict = False
			if len(self.listener.channel_items) > 0:
				# items were queued while reading from the db. toss them and
				#   read from db again
				self.listener.aevent.clear()
				self.listener.channel_items = {}
				conflict = True
			lm.lock.release()

			if conflict:
				continue

			# if we get here then the client is caught up. time to wait

			while self.is_streaming:
				f = asyncio.ensure_future(self.listener.aevent.wait())
				while True:
					done, _ = await asyncio.wait([f], timeout=20)
					if f in done:
						break
					body = 'event: keep-alive\ndata:\n\n'
					await self.send_body(body.encode('utf-8'), more_body=True)

				if not self.is_streaming:
					break

				lm.lock.acquire()

				channel_items = self.listener.channel_items
				overflow = self.listener.overflow
				error_data = self.listener.error

				self.listener.aevent.clear()
				self.listener.channel_items = {}
				self.listener.overflow = False

				lm.lock.release()

				body = ''
				for channel, items in channel_items.items():
					for item in items:
						if channel in last_ids:
							if item.id is not None:
								last_ids[channel] = item.id
							else:
								del last_ids[channel]
						if last_ids:
							event_id = make_id(last_ids)
						else:
							event_id = None
						body += sse_encode_event(
							item.type,
							item.data,
							event_id=event_id)

				more = True

				if error_data:
					body += sse_encode_event('stream-error', error_data, event_id='error')
					more = False

				if body or not more:
					await self.send_body(body.encode('utf-8'), more_body=more)

				if not more:
					self.is_streaming = False
					break

				if overflow:
					# check db
					break

			event_request.channel_last_ids = last_ids

		lm.remove_listener(self.listener)

	async def disconnect(self):
		self.is_streaming = False
		if self.listener:
			self.listener.aevent.set()


text:
package com.ain.engine.domain.csos;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name="NOTE")
@Getter
@Setter
@ToString
public class Note {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String title;

    private String body;

    @ManyToMany
    private List<Tag> tags;

}


text:
"""Test praw.models.comment_forest."""
from praw.models import Comment, MoreComments, Submission

from .. import IntegrationTest

class TestCommentForest(IntegrationTest):
    def setup(self):
        super(TestCommentForest, self).setup()
        # Responses do not decode well on travis so manually renable gzip.
        self.reddit._core._requestor._http.headers['Accept-Encoding'] = 'gzip'

    def test_replace__all(self):
        with self.recorder.use_cassette(
                'TestCommentForest.test_replace__all',
                match_requests_on=['uri', 'method', 'body']):
            submission = Submission(self.reddit, '3hahrw')
            before_count = len(submission.comments.list())
            skipped = submission.comments.replace_more(None, threshold=0)
            assert len(skipped) == 0
            assert all(isinstance(x, Comment) for x in
                       submission.comments.list())
            assert all(x.submission == submission for x in
                       submission.comments.list())
            assert before_count < len(submission.comments.list())

    def test_replace__all_large(self):
        with self.recorder.use_cassette(
                'TestCommentForest.test_replace__all_large',
                match_requests_on=['uri', 'method', 'body']):
            submission = Submission(self.reddit, 'n49rw')
            skipped = submission.comments.replace_more(None, threshold=0)
            assert len(skipped) == 0
            assert all(isinstance(x, Comment) for x in
                       submission.comments.list())
            assert len(submission.comments.list()) > 1000
            assert len(submission.comments.list()) == \
                len(submission._comments_by_id)

    def test_replace__all_with_comment_limit(self):
        with self.recorder.use_cassette(
                'TestCommentForest.test_replace__all_with_comment_limit',
                match_requests_on=['uri', 'method', 'body']):
            submission = Submission(self.reddit, '3hahrw')
            submission.comment_limit = 10
            skipped = submission.comments.replace_more(None, threshold=0)
            assert len(skipped) == 0
            assert len(submission.comments.list()) >= 500

    def test_replace__skip_at_limit(self):
        with self.recorder.use_cassette(
                'TestCommentForest.test_replace__skip_at_limit',
                match_requests_on=['uri', 'method', 'body']):
            submission = Submission(self.reddit, '3hahrw')
            skipped = submission.comments.replace_more(1)
            assert len(skipped) == 17

    def test_replace__skip_below_threshold(self):
        with self.recorder.use_cassette(
                'TestCommentForest.test_replace__skip_below_threshold',
                match_requests_on=['uri', 'method', 'body']):
            submission = Submission(self.reddit, '3hahrw')
            before_count = len(submission.comments.list())
            skipped = submission.comments.replace_more(16, 5)
            assert len(skipped) == 13
            assert all(x.count < 5 for x in skipped)
            assert all(x.submission == submission for x in skipped)
            assert before_count < len(submission.comments.list())

    def test_replace__skip_all(self):
        with self.recorder.use_cassette(
                'TestCommentForest.test_replace__skip_all',
                match_requests_on=['uri', 'method', 'body']):
            submission = Submission(self.reddit, '3hahrw')
            before_count = len(submission.comments.list())
            skipped = submission.comments.replace_more(limit=0)
            assert len(skipped) == 18
            assert all(x.submission == submission for x in skipped)
            after_count = len(submission.comments.list())
            assert before_count == after_count + len(skipped)

    def test_replace__on_comment_from_submission(self):
        with self.recorder.use_cassette(
                'TestCommentForest.test_replace__on_comment_from_submission',
                match_requests_on=['uri', 'method', 'body']):
            submission = Submission(self.reddit, '3hahrw')
            types = [type(x) for x in submission.comments.list()]
            assert types.count(Comment) == 472
            assert types.count(MoreComments) == 18
            assert submission.comments[0].replies.replace_more() == []
            types = [type(x) for x in submission.comments.list()]
            assert types.count(Comment) == 489
            assert types.count(MoreComments) == 11

    def test_replace__on_direct_comment(self):
        with self.recorder.use_cassette(
                'TestCommentForest.test_replace__on_direct_comment',
                match_requests_on=['uri', 'method', 'body']):
            comment = self.reddit.comment('d8r4im1')
            comment.refresh()
            assert any(isinstance(x, MoreComments) for x in
                       comment.replies.list())
            comment.replies.replace_more()
            assert all(isinstance(x, Comment) for x in
                       comment.replies.list())


text:
package com.company;

import java.util.Observable;

/**
 * Created by tuanlhd on 4/26/16.
 */
public class CompareGuy extends Observable implements Runnable {
    private int[][] wholePic;// array of colors
    private int x;int y;
    private int xOffset;
    private int yOffset;
    private int[] findValue;// histagram
    private int acceptableMatch;

    public CompareGuy(int[][] wholePic, int x, int y, int xOffset, int yOffset, int[] findValue,int acceptableMatch) {
        this.wholePic = wholePic;
        this.x = x;
        this.y = y;
        this.xOffset = xOffset;
        this.yOffset = yOffset;
        this.findValue = findValue;
        this.acceptableMatch = acceptableMatch;
    }

    @Override
    public void run() {
        isSimulate(wholePic,x,y,xOffset,yOffset,findValue);
    }

    /***
     *
     * @param x start position
     * @param y start position
     * @return
     */
    private boolean isSimulate(int[][] wholePic,int x,int y, int xOffset, int yOffset, int[] findValue){
        int wholePicWidth = wholePic.length;
        int wholePiHeight = wholePic[0].length;
        xOffset+=x;
        yOffset+=y;
        if(xOffset>wholePicWidth||yOffset>wholePiHeight)
            return false;
        int[] histogram = MColor.getHistogram(wholePic, x, y, xOffset, yOffset);
        int compareValue=MColor.compareHistogram(findValue,histogram);
        this.setChanged();
        if(compareValue<acceptableMatch){
            this.notifyObservers(new int[]{x,y});
            return true;
        } else {
            this.notifyObservers(new int[]{compareValue,x,y});
            return false;
        }
    }

}


text:
package org.outburstframework.example;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.outburstframework.runner.OutburstTestParameters;
import org.outburstframework.runner.junit.OutburstJUnitRunner;
import org.outburstframework.test.util.http.HTTPUtils;

/**
 *
 * @author Lee Kemp
 *
 */
@RunWith(OutburstJUnitRunner.class)
@OutburstTestParameters(testRuns=40, testLength=30000)
public class HttpTest
{

	@Test()
	public void googleCom() throws Exception
	{
		HTTPUtils.HTTPGet("http://www.google.com/");
	}

	@Test()
	public void yahooCom() throws Exception
	{
		HTTPUtils.HTTPGet("http://www.yahoo.com/");
	}

	@Test()
	public void amazonCom() throws Exception
	{
		HTTPUtils.HTTPGet("http://www.amazon.com/");
	}

	@Test()
	public void sunCom() throws Exception
	{
		HTTPUtils.HTTPGet("http://www.sun.com/");
	}

}


text:
title: Async iterator API
navtitle: Async iterator
description: The Async iterator API is both scalable and elegant. It takes advantage of the native Readable Stream API upon which the parser is build to iterate over the parsed records.
keywords: ['csv', 'parse', 'api', 'async', 'iterator']
sort: 3.4
---

# Async iterator API

The Async iterator API is both scalable and elegant. It takes advantage of the native Readable Stream API upon which the parser is build to iterate over the parsed records.

The [async iterator example](https://github.com/adaltas/node-csv/blob/master/packages/csv-parse/samples/async.iterator.js) below generates a CSV stream which is then parsed and iterated over. For each record, we simulate a slow asynchronous operation. This example is available with the command `node samples/async.iterator.js`.

`embed:packages/csv-parse/samples/async.iterator.js`


text:
import React, { Component } from 'react'
import { Animated } from 'react-native'
import PropTypes from 'prop-types'

export default class FadeInView extends Component<Props> {

  constructor(props) {
    super(props)

    this.state = {
      viewOpacity: new Animated.Value(0),
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.fadeAgain) {
      this.animation(0, (() => { this.animation(1) }))
    }
  }

  componentDidMount() {
    this.animation(1)
  }

  animation(toValue, onComplete) {
    const { duration, delay } = this.props
    const { viewOpacity } = this.state

    Animated.timing(
      viewOpacity,
      {
        toValue: toValue,
        duration: duration,
        delay,
        useNativeDriver: true
      }
    ).start(onComplete || (() => {}))
  }

  render() {
    const { viewOpacity } = this.state
    const { style } = this.props

    return(
      <Animated.View style={[style, { opacity: viewOpacity }]}>
        {this.props.children}
      </Animated.View>
    )
  }
}

FadeInView.propTypes = {
  fadeAgain: PropTypes.bool,
  duration: PropTypes.number,
  delay: PropTypes.number,
  style: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.object,
    PropTypes.string,
    PropTypes.number
  ]),
  children: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.object,
  ]).isRequired
}

FadeInView.defaultProps = {
  fadeAgain: false,
  duration: 500,
  delay: 0
}


text:
<template name="listPotBlimbing">
  {{#contentFor "headerButtonLeft"}}
    {{>ionNavBackButton path="cariPotensi"}}
  {{/contentFor}}
  {{#contentFor "headerTitle"}}

Blimbing

  {{/contentFor}}

  {{#ionView}}

    {{#ionContent}}
    {{#ionList}}

    {{#ionItem}}

            Kecamatan Mantup

                81 Ton/Tahun

            Kecamatan Sugio

                44 Ton/Tahun

            Kecamatan Solokuro

                31 Ton/Tahun

            Kecamatan Paciran

                28 Ton/Tahun

    {{/ionItem}}

    {{/ionList}}
    {{/ionContent}}

  {{/ionView}}

</template>


text:
module Krane
  class TaskConfigValidator
    DEFAULT_VALIDATIONS = %i(
      validate_kubeconfig
      validate_context_exists_in_kubeconfig
      validate_context_reachable
      validate_server_version
      validate_namespace_exists
    ).freeze

    delegate :context, :namespace, :logger, to: :@task_config

    def initialize(task_config, kubectl, kubeclient_builder, only: nil)
      @task_config = task_config
      @kubectl = kubectl
      @kubeclient_builder = kubeclient_builder
      @errors = nil
      @validations = only || DEFAULT_VALIDATIONS
    end

    def valid?
      @errors = []
      @validations.each do |validator_name|
        break if @errors.present?
        send(validator_name)
      end
      @errors.empty?
    end

    def errors
      valid?
      @errors
    end

    private

    def validate_kubeconfig
      @errors += @kubeclient_builder.validate_config_files
    end

    def validate_context_exists_in_kubeconfig
      unless context.present?
        return @errors << "Context can not be blank"
      end

      _, err, st = @kubectl.run("config", "get-contexts", context, "-o", "name",
        use_namespace: false, use_context: false, log_failure: false, attempts: 2)

      unless st.success?
        @errors << if err.match("error: context #{context} not found")
          "Context #{context} missing from your kubeconfig file(s)"
        else
          "Something went wrong. #{err} "
        end
      end
    end

    def validate_context_reachable
      _, err, st = @kubectl.run("get", "namespaces", "-o", "name",
        use_namespace: false, log_failure: false, attempts: 2)

      unless st.success?
        @errors << "Something went wrong connecting to #{context}. #{err} "
      end
    end

    def validate_namespace_exists
      unless namespace.present?
        return @errors << "Namespace can not be blank"
      end

      _, err, st = @kubectl.run("get", "namespace", "-o", "name", namespace,
        use_namespace: false, log_failure: false, attempts: 3)

      unless st.success?
        @errors << if err.match("Error from server [(]NotFound[)]: namespace")
          "Could not find Namespace: #{namespace} in Context: #{context}"
        else
          "Could not connect to kubernetes cluster. #{err}"
        end
      end
    end

    def validate_server_version
      if @kubectl.server_version < Gem::Version.new(MIN_KUBE_VERSION)
        logger.warn(server_version_warning(@kubectl.server_version))
      end
    end

    def server_version_warning(server_version)
      "Minimum cluster version requirement of #{MIN_KUBE_VERSION} not met. "\
      "Using #{server_version} could result in unexpected behavior as it is no longer tested against"
    end
  end
end


text: """Test the grainbin module."""


text: export{AppInsightsDefaults,Angulartics2AppInsights}from"./appinsights";


text:
namespace mojo {

#define ASSERT_ENUM_EQ(media_enum, media_prefix, mojo_prefix, value)    \
  static_assert(media::media_prefix##value ==                           \
                    static_cast<media::media_enum>(mojo_prefix##value), \
                "Mismatched enum: " #media_prefix #value                \
                " != " #mojo_prefix #value)

#define ASSERT_ENUM_EQ_RAW(media_enum, media_enum_value, mojo_enum_value) \
  static_assert(media::media_enum_value ==                                \
                    static_cast<media::media_enum>(mojo_enum_value),      \
                "Mismatched enum: " #media_enum_value " != " #mojo_enum_value)

// BufferingState.
ASSERT_ENUM_EQ(BufferingState, BUFFERING_, BUFFERING_STATE_, HAVE_NOTHING);
ASSERT_ENUM_EQ(BufferingState, BUFFERING_, BUFFERING_STATE_, HAVE_ENOUGH);

// AudioCodec.
ASSERT_ENUM_EQ_RAW(AudioCodec, kUnknownAudioCodec, AUDIO_CODEC_UNKNOWN);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, AAC);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, MP3);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, PCM);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, Vorbis);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, FLAC);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, AMR_NB);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, PCM_MULAW);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, GSM_MS);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, PCM_S16BE);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, PCM_S24BE);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, Opus);
ASSERT_ENUM_EQ(AudioCodec, kCodec, AUDIO_CODEC_, PCM_ALAW);
ASSERT_ENUM_EQ_RAW(AudioCodec, kAudioCodecMax, AUDIO_CODEC_MAX);

// ChannelLayout.
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _NONE);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _UNSUPPORTED);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _MONO);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _STEREO);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _2_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _SURROUND);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _4_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _2_2);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _QUAD);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _5_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _5_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _5_0_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _5_1_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _7_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _7_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _7_1_WIDE);
ASSERT_ENUM_EQ(ChannelLayout,
               CHANNEL_LAYOUT,
               CHANNEL_LAYOUT_k,
               _STEREO_DOWNMIX);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _2POINT1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _3_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _4_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _6_0);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _6_0_FRONT);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _HEXAGONAL);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _6_1);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _6_1_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _6_1_FRONT);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _7_0_FRONT);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _7_1_WIDE_BACK);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _OCTAGONAL);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _DISCRETE);
ASSERT_ENUM_EQ(ChannelLayout,
               CHANNEL_LAYOUT,
               CHANNEL_LAYOUT_k,
               _STEREO_AND_KEYBOARD_MIC);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _4_1_QUAD_SIDE);
ASSERT_ENUM_EQ(ChannelLayout, CHANNEL_LAYOUT, CHANNEL_LAYOUT_k, _MAX);

// SampleFormat.
ASSERT_ENUM_EQ_RAW(SampleFormat, kUnknownSampleFormat, SAMPLE_FORMAT_UNKNOWN);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, SAMPLE_FORMAT_, U8);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, SAMPLE_FORMAT_, S16);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, SAMPLE_FORMAT_, S32);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, SAMPLE_FORMAT_, F32);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, SAMPLE_FORMAT_, PlanarS16);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, SAMPLE_FORMAT_, PlanarF32);
ASSERT_ENUM_EQ(SampleFormat, kSampleFormat, SAMPLE_FORMAT_, Max);

// DemuxerStream Type.  Note: Mojo DemuxerStream's don't have the TEXT type.
ASSERT_ENUM_EQ_RAW(DemuxerStream::Type,
                   DemuxerStream::UNKNOWN,
                   DemuxerStream::TYPE_UNKNOWN);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Type,
                   DemuxerStream::AUDIO,
                   DemuxerStream::TYPE_AUDIO);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Type,
                   DemuxerStream::VIDEO,
                   DemuxerStream::TYPE_VIDEO);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Type,
                   DemuxerStream::NUM_TYPES,
                   DemuxerStream::TYPE_LAST_TYPE + 2);

// DemuxerStream Status.
ASSERT_ENUM_EQ_RAW(DemuxerStream::Status,
                   DemuxerStream::kOk,
                   DemuxerStream::STATUS_OK);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Status,
                   DemuxerStream::kAborted,
                   DemuxerStream::STATUS_ABORTED);
ASSERT_ENUM_EQ_RAW(DemuxerStream::Status,
                   DemuxerStream::kConfigChanged,
                   DemuxerStream::STATUS_CONFIG_CHANGED);

// VideoFormat.
ASSERT_ENUM_EQ_RAW(VideoFrame::Format,
                   VideoFrame::UNKNOWN,
                   VIDEO_FORMAT_UNKNOWN);
ASSERT_ENUM_EQ_RAW(VideoFrame::Format, VideoFrame::YV12, VIDEO_FORMAT_YV12);
ASSERT_ENUM_EQ_RAW(VideoFrame::Format, VideoFrame::YV16, VIDEO_FORMAT_YV16);
ASSERT_ENUM_EQ_RAW(VideoFrame::Format, VideoFrame::I420, VIDEO_FORMAT_I420);
ASSERT_ENUM_EQ_RAW(VideoFrame::Format, VideoFrame::YV12A, VIDEO_FORMAT_YV12A);
#if defined(VIDEO_HOLE)
ASSERT_ENUM_EQ_RAW(VideoFrame::Format, VideoFrame::HOLE, VIDEO_FORMAT_HOLE);
#endif
ASSERT_ENUM_EQ_RAW(VideoFrame::Format,
                   VideoFrame::NATIVE_TEXTURE,
                   VIDEO_FORMAT_NATIVE_TEXTURE);
ASSERT_ENUM_EQ_RAW(VideoFrame::Format, VideoFrame::YV12J, VIDEO_FORMAT_YV12J);
ASSERT_ENUM_EQ_RAW(VideoFrame::Format, VideoFrame::NV12, VIDEO_FORMAT_NV12);
ASSERT_ENUM_EQ_RAW(VideoFrame::Format, VideoFrame::YV24, VIDEO_FORMAT_YV24);
ASSERT_ENUM_EQ_RAW(VideoFrame::Format, VideoFrame::ARGB, VIDEO_FORMAT_ARGB);
ASSERT_ENUM_EQ_RAW(VideoFrame::Format,
                   VideoFrame::FORMAT_MAX,
                   VIDEO_FORMAT_FORMAT_MAX);

// VideoCodec
ASSERT_ENUM_EQ_RAW(VideoCodec, kUnknownVideoCodec, VIDEO_CODEC_UNKNOWN);
ASSERT_ENUM_EQ(VideoCodec, kCodec, VIDEO_CODEC_, H264);
ASSERT_ENUM_EQ(VideoCodec, kCodec, VIDEO_CODEC_, VC1);
ASSERT_ENUM_EQ(VideoCodec, kCodec, VIDEO_CODEC_, MPEG2);
ASSERT_ENUM_EQ(VideoCodec, kCodec, VIDEO_CODEC_, MPEG4);
ASSERT_ENUM_EQ(VideoCodec, kCodec, VIDEO_CODEC_, Theora);
ASSERT_ENUM_EQ(VideoCodec, kCodec, VIDEO_CODEC_, VP8);
ASSERT_ENUM_EQ(VideoCodec, kCodec, VIDEO_CODEC_, VP9);
ASSERT_ENUM_EQ_RAW(VideoCodec, kVideoCodecMax, VIDEO_CODEC_Max);

// VideoCodecProfile
ASSERT_ENUM_EQ(VideoCodecProfile,
               ,
               VIDEO_CODEC_PROFILE_,
               VIDEO_CODEC_PROFILE_UNKNOWN);
ASSERT_ENUM_EQ(VideoCodecProfile,
               ,
               VIDEO_CODEC_PROFILE_,
               VIDEO_CODEC_PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, H264PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, H264PROFILE_BASELINE);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, H264PROFILE_MAIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, H264PROFILE_EXTENDED);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, H264PROFILE_HIGH);
ASSERT_ENUM_EQ(VideoCodecProfile,
               ,
               VIDEO_CODEC_PROFILE_,
               H264PROFILE_HIGH10PROFILE);
ASSERT_ENUM_EQ(VideoCodecProfile,
               ,
               VIDEO_CODEC_PROFILE_,
               H264PROFILE_HIGH422PROFILE);
ASSERT_ENUM_EQ(VideoCodecProfile,
               ,
               VIDEO_CODEC_PROFILE_,
               H264PROFILE_HIGH444PREDICTIVEPROFILE);
ASSERT_ENUM_EQ(VideoCodecProfile,
               ,
               VIDEO_CODEC_PROFILE_,
               H264PROFILE_SCALABLEBASELINE);
ASSERT_ENUM_EQ(VideoCodecProfile,
               ,
               VIDEO_CODEC_PROFILE_,
               H264PROFILE_SCALABLEHIGH);
ASSERT_ENUM_EQ(VideoCodecProfile,
               ,
               VIDEO_CODEC_PROFILE_,
               H264PROFILE_STEREOHIGH);
ASSERT_ENUM_EQ(VideoCodecProfile,
               ,
               VIDEO_CODEC_PROFILE_,
               H264PROFILE_MULTIVIEWHIGH);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, H264PROFILE_MAX);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, VP8PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, VP8PROFILE_ANY);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, VP8PROFILE_MAX);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, VP9PROFILE_MIN);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, VP9PROFILE_ANY);
ASSERT_ENUM_EQ(VideoCodecProfile, , VIDEO_CODEC_PROFILE_, VP9PROFILE_MAX);
ASSERT_ENUM_EQ(VideoCodecProfile,
               ,
               VIDEO_CODEC_PROFILE_,
               VIDEO_CODEC_PROFILE_MAX);

// CdmException
#define ASSERT_CDM_EXCEPTION(value)                                        \
  static_assert(                                                           \
      media::MediaKeys::value ==                                           \
          static_cast<media::MediaKeys::Exception>(CDM_EXCEPTION_##value), \
      "Mismatched CDM Exception")
ASSERT_CDM_EXCEPTION(NOT_SUPPORTED_ERROR);
ASSERT_CDM_EXCEPTION(INVALID_STATE_ERROR);
ASSERT_CDM_EXCEPTION(INVALID_ACCESS_ERROR);
ASSERT_CDM_EXCEPTION(QUOTA_EXCEEDED_ERROR);
ASSERT_CDM_EXCEPTION(UNKNOWN_ERROR);
ASSERT_CDM_EXCEPTION(CLIENT_ERROR);
ASSERT_CDM_EXCEPTION(OUTPUT_ERROR);

// CDM Session Type
#define ASSERT_CDM_SESSION_TYPE(value)                                  \
  static_assert(media::MediaKeys::value ==                              \
                    static_cast<media::MediaKeys::SessionType>(         \
                        ContentDecryptionModule::SESSION_TYPE_##value), \
                "Mismatched CDM Session Type")
ASSERT_CDM_SESSION_TYPE(TEMPORARY_SESSION);
ASSERT_CDM_SESSION_TYPE(PERSISTENT_LICENSE_SESSION);
ASSERT_CDM_SESSION_TYPE(PERSISTENT_RELEASE_MESSAGE_SESSION);

// CDM Key Status
#define ASSERT_CDM_KEY_STATUS(value)                                  \
  static_assert(media::CdmKeyInformation::value ==                    \
                    static_cast<media::CdmKeyInformation::KeyStatus>( \
                        CDM_KEY_STATUS_##value),                      \
                "Mismatched CDM Key Status")
ASSERT_CDM_KEY_STATUS(USABLE);
ASSERT_CDM_KEY_STATUS(INTERNAL_ERROR);
ASSERT_CDM_KEY_STATUS(EXPIRED);
ASSERT_CDM_KEY_STATUS(OUTPUT_NOT_ALLOWED);

// CDM Message Type
#define ASSERT_CDM_MESSAGE_TYPE(value)                                       \
  static_assert(                                                             \
      media::MediaKeys::value == static_cast<media::MediaKeys::MessageType>( \
                                     CDM_MESSAGE_TYPE_##value),              \
      "Mismatched CDM Message Type")
ASSERT_CDM_MESSAGE_TYPE(LICENSE_REQUEST);
ASSERT_CDM_MESSAGE_TYPE(LICENSE_RENEWAL);
ASSERT_CDM_MESSAGE_TYPE(LICENSE_RELEASE);

// static
SubsampleEntryPtr
TypeConverter<SubsampleEntryPtr, media::SubsampleEntry>::Convert(
    const media::SubsampleEntry& input) {
  SubsampleEntryPtr mojo_subsample_entry(SubsampleEntry::New());
  mojo_subsample_entry->clear_bytes = input.clear_bytes;
  mojo_subsample_entry->cypher_bytes = input.cypher_bytes;
  return mojo_subsample_entry.Pass();
}

// static
media::SubsampleEntry
TypeConverter<media::SubsampleEntry, SubsampleEntryPtr>::Convert(
    const SubsampleEntryPtr& input) {
  return media::SubsampleEntry(input->clear_bytes, input->cypher_bytes);
}

// static
DecryptConfigPtr TypeConverter<DecryptConfigPtr, media::DecryptConfig>::Convert(
    const media::DecryptConfig& input) {
  DecryptConfigPtr mojo_decrypt_config(DecryptConfig::New());
  mojo_decrypt_config->key_id = input.key_id();
  mojo_decrypt_config->iv = input.iv();
  mojo_decrypt_config->subsamples =
      Array<SubsampleEntryPtr>::From(input.subsamples());
  return mojo_decrypt_config.Pass();
}

// static
scoped_ptr<media::DecryptConfig>
TypeConverter<scoped_ptr<media::DecryptConfig>, DecryptConfigPtr>::Convert(
    const DecryptConfigPtr& input) {
  return make_scoped_ptr(new media::DecryptConfig(
      input->key_id, input->iv,
      input->subsamples.To<std::vector<media::SubsampleEntry>>()));
}

// static
MediaDecoderBufferPtr TypeConverter<MediaDecoderBufferPtr,
    scoped_refptr<media::DecoderBuffer> >::Convert(
        const scoped_refptr<media::DecoderBuffer>& input) {
  DCHECK(input);

  MediaDecoderBufferPtr mojo_buffer(MediaDecoderBuffer::New());
  if (input->end_of_stream())
    return mojo_buffer.Pass();

  mojo_buffer->timestamp_usec = input->timestamp().InMicroseconds();
  mojo_buffer->duration_usec = input->duration().InMicroseconds();
  mojo_buffer->is_key_frame = input->is_key_frame();
  mojo_buffer->data_size = input->data_size();
  mojo_buffer->side_data_size = input->side_data_size();
  mojo_buffer->front_discard_usec =
      input->discard_padding().first.InMicroseconds();
  mojo_buffer->back_discard_usec =
      input->discard_padding().second.InMicroseconds();
  mojo_buffer->splice_timestamp_usec =
      input->splice_timestamp().InMicroseconds();

  // Note: The side data is always small, so this copy is okay.
  std::vector<uint8_t> side_data(input->side_data(),
                                 input->side_data() + input->side_data_size());
  mojo_buffer->side_data.Swap(&side_data);

  if (input->decrypt_config())
    mojo_buffer->decrypt_config = DecryptConfig::From(*input->decrypt_config());

  // TODO(dalecurtis): We intentionally do not serialize the data section of
  // the DecoderBuffer here; this must instead be done by clients via their
  // own DataPipe.  See http://crbug.com/432960

  return mojo_buffer.Pass();
}

// static
scoped_refptr<media::DecoderBuffer>  TypeConverter<
    scoped_refptr<media::DecoderBuffer>, MediaDecoderBufferPtr>::Convert(
        const MediaDecoderBufferPtr& input) {
  if (!input->data_size)
    return media::DecoderBuffer::CreateEOSBuffer();

  scoped_refptr<media::DecoderBuffer> buffer(
      new media::DecoderBuffer(input->data_size));
  if (input->side_data_size)
    buffer->CopySideDataFrom(&input->side_data.front(), input->side_data_size);

  buffer->set_timestamp(
      base::TimeDelta::FromMicroseconds(input->timestamp_usec));
  buffer->set_duration(
      base::TimeDelta::FromMicroseconds(input->duration_usec));

  if (input->is_key_frame)
    buffer->set_is_key_frame(true);

  if (input->decrypt_config) {
    buffer->set_decrypt_config(
        input->decrypt_config.To<scoped_ptr<media::DecryptConfig>>());
  }

  media::DecoderBuffer::DiscardPadding discard_padding(
      base::TimeDelta::FromMicroseconds(input->front_discard_usec),
      base::TimeDelta::FromMicroseconds(input->back_discard_usec));
  buffer->set_discard_padding(discard_padding);
  buffer->set_splice_timestamp(
      base::TimeDelta::FromMicroseconds(input->splice_timestamp_usec));

  // TODO(dalecurtis): We intentionally do not deserialize the data section of
  // the DecoderBuffer here; this must instead be done by clients via their
  // own DataPipe.  See http://crbug.com/432960

  return buffer;
}

// static
AudioDecoderConfigPtr
TypeConverter<AudioDecoderConfigPtr, media::AudioDecoderConfig>::Convert(
    const media::AudioDecoderConfig& input) {
  AudioDecoderConfigPtr config(AudioDecoderConfig::New());
  config->codec = static_cast<AudioCodec>(input.codec());
  config->sample_format =
      static_cast<SampleFormat>(input.sample_format());
  config->channel_layout =
      static_cast<ChannelLayout>(input.channel_layout());
  config->samples_per_second = input.samples_per_second();
  if (input.extra_data()) {
    std::vector<uint8_t> data(input.extra_data(),
                              input.extra_data() + input.extra_data_size());
    config->extra_data.Swap(&data);
  }
  config->seek_preroll_usec = input.seek_preroll().InMicroseconds();
  config->codec_delay = input.codec_delay();
  config->is_encrypted = input.is_encrypted();
  return config.Pass();
}

// static
media::AudioDecoderConfig
TypeConverter<media::AudioDecoderConfig, AudioDecoderConfigPtr>::Convert(
    const AudioDecoderConfigPtr& input) {
  media::AudioDecoderConfig config;
  config.Initialize(
      static_cast<media::AudioCodec>(input->codec),
      static_cast<media::SampleFormat>(input->sample_format),
      static_cast<media::ChannelLayout>(input->channel_layout),
      input->samples_per_second,
      input->extra_data.size() ? &input->extra_data.front() : NULL,
      input->extra_data.size(),
      input->is_encrypted,
      false,
      base::TimeDelta::FromMicroseconds(input->seek_preroll_usec),
      input->codec_delay);
  return config;
}

// static
VideoDecoderConfigPtr
TypeConverter<VideoDecoderConfigPtr, media::VideoDecoderConfig>::Convert(
    const media::VideoDecoderConfig& input) {
  VideoDecoderConfigPtr config(VideoDecoderConfig::New());
  config->codec = static_cast<VideoCodec>(input.codec());
  config->profile = static_cast<VideoCodecProfile>(input.profile());
  config->format = static_cast<VideoFormat>(input.format());
  config->coded_size = Size::From(input.coded_size());
  config->visible_rect = Rect::From(input.visible_rect());
  config->natural_size = Size::From(input.natural_size());
  if (input.extra_data()) {
    std::vector<uint8_t> data(input.extra_data(),
                              input.extra_data() + input.extra_data_size());
    config->extra_data.Swap(&data);
  }
  config->is_encrypted = input.is_encrypted();
  return config.Pass();
}

// static
media::VideoDecoderConfig
TypeConverter<media::VideoDecoderConfig, VideoDecoderConfigPtr>::Convert(
    const VideoDecoderConfigPtr& input) {
  media::VideoDecoderConfig config;
  config.Initialize(
      static_cast<media::VideoCodec>(input->codec),
      static_cast<media::VideoCodecProfile>(input->profile),
      static_cast<media::VideoFrame::Format>(input->format),
      input->coded_size.To<gfx::Size>(),
      input->visible_rect.To<gfx::Rect>(),
      input->natural_size.To<gfx::Size>(),
      input->extra_data.size() ? &input->extra_data.front() : NULL,
      input->extra_data.size(),
      input->is_encrypted,
      false);
  return config;
}

// static
CdmKeyInformationPtr
TypeConverter<CdmKeyInformationPtr, media::CdmKeyInformation>::Convert(
    const media::CdmKeyInformation& input) {
  CdmKeyInformationPtr info(CdmKeyInformation::New());
  std::vector<uint8_t> key_id_copy(input.key_id);
  info->key_id.Swap(&key_id_copy);
  info->status = static_cast<CdmKeyStatus>(input.status);
  info->system_code = input.system_code;
  return info.Pass();
}

// static
scoped_ptr<media::CdmKeyInformation> TypeConverter<
    scoped_ptr<media::CdmKeyInformation>,
    CdmKeyInformationPtr>::Convert(const CdmKeyInformationPtr& input) {
  scoped_ptr<media::CdmKeyInformation> info(new media::CdmKeyInformation);
  info->key_id = input->key_id.storage();
  info->status =
      static_cast<media::CdmKeyInformation::KeyStatus>(input->status);
  info->system_code = input->system_code;
  return info.Pass();
}

}  // namespace mojo


text:
import Service from '@ember/service';
import hbs from 'htmlbars-inline-precompile';
import {click, find, render} from '@ember/test-helpers';
import {describe, it} from 'mocha';
import {expect} from 'chai';
import {setupRenderingTest} from 'ember-mocha';

const featureStub = Service.extend({
    testFlag: true
});

describe('Integration: Component: gh-feature-flag', function () {
    setupRenderingTest();

    beforeEach(function () {
        this.owner.register('service:feature', featureStub);
    });

    it('renders properties correctly', async function () {
        await render(hbs`<GhFeatureFlag @flag="testFlag" />`);
        expect(find('label').getAttribute('for')).to.equal(find('input[type="checkbox"]').id);
    });

    it('renders correctly when flag is set to true', async function () {
        await render(hbs`<GhFeatureFlag @flag="testFlag" />`);
        expect(find('label input[type="checkbox"]').checked).to.be.true;
    });

    it('renders correctly when flag is set to false', async function () {
        let feature = this.owner.lookup('service:feature');
        feature.set('testFlag', false);

        await render(hbs`<GhFeatureFlag @flag="testFlag" />`);
        expect(find('label input[type="checkbox"]').checked).to.be.false;
    });

    it('updates to reflect changes in flag property', async function () {
        await render(hbs`<GhFeatureFlag @flag="testFlag" />`);
        expect(find('label input[type="checkbox"]').checked).to.be.true;

        await click('label');
        expect(find('label input[type="checkbox"]').checked).to.be.false;
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavaScriptLibraryMappings">
    <file url="file://$PROJECT_DIR$" libraries="{pchat node_modules}" />
    <file url="PROJECT" libraries="{ejs-DefinitelyTyped, express-DefinitelyTyped, node-DefinitelyTyped}" />
  </component>
</project>


text:
[![Maven Central](https://img.shields.io/maven-central/v/com.tinify/tinify.svg)](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.tinify%22%20AND%20a%3A%22tinify%22)
[![MIT License](http://img.shields.io/badge/license-MIT-green.svg) ](https://github.com/tinify/tinify-java/blob/main/LICENSE)
[![Java CI/CD](https://github.com/tinify/tinify-java/actions/workflows/ci-cd.yml/badge.svg)](https://github.com/tinify/tinify-java/actions/workflows/ci-cd.yml)

# Tinify API client for Java

Java client for the Tinify API, used for [TinyPNG](https://tinypng.com) and [TinyJPG](https://tinyjpg.com). Tinify compresses your images intelligently. Read more at [http://tinify.com](http://tinify.com).

## Documentation

[Go to the documentation for the Java client](https://tinypng.com/developers/reference/java).

## Installation

Install the API client via Maven:

```xml
<dependency>
  <groupId>com.tinify</groupId>
  <artifactId>tinify</artifactId>
  <version>1.8.0</version>
</dependency>
```

## Usage

```java
import com.tinify.*;
import java.io.IOException;

public class Compress {
  public static void main(String[] args) throws java.io.IOException {
    Tinify.setKey("YOUR_API_KEY");
    Tinify.fromFile("unoptimized.png").toFile("optimized.png");
  }
}
```

## Running tests

```
mvn test
```

### Integration tests

```
TINIFY_KEY=$YOUR_API_KEY mvn -Pintegration integration-test
```

## License

This software is licensed under the MIT License. [View the license](LICENSE).


text:
/**
 *
 * Wait for an element (selected by css selector) for the provided amount of
 * milliseconds to be present within the DOM. Returns true if the selector
 * matches at least one element that exists in the DOM. If the reverse flag
 * is true, the command will instead return true if the selector does not
 * match any elements.
 *
 * @param {String}   selector CSS selector to query
 * @param {Number=}  ms       time in ms (default: 500)
 * @param {Boolean=} reverse  if true it instead waits for the selector to not match any elements (default: false)
 *
 * @uses util/waitUntil, property/isExisting
 * @type utility
 *
 */

import { CommandError, isTimeoutError } from '../utils/ErrorHandler'

let waitForExist = function (selector, ms, reverse) {
    /**
     * we can't use default values for function parameter here because this would
     * break the ability to chain the command with an element if reverse is used, like
     *
     * ```js
     * var elem = browser.element('#elem');
     * elem.waitForXXX(10000, true);
     * ```
     */
    reverse = typeof reverse === 'boolean' ? reverse : false

    /*!
     * ensure that ms is set properly
     */
    if (typeof ms !== 'number') {
        ms = this.options.waitforTimeout
    }

    return this.waitUntil(() => {
        return this.isExisting(selector).then((isExisting) => {
            if (!Array.isArray(isExisting)) {
                return isExisting !== reverse
            }

            let result = reverse
            for (let val of isExisting) {
                if (!reverse) {
                    result = result || val
                } else {
                    result = result && val
                }
            }

            return result !== reverse
        })
    }, ms).catch((e) => {
        if (isTimeoutError(e)) {
            let isReversed = reverse ? '' : 'not '
            throw new CommandError(`element (${selector}) still ${isReversed}existing after ${ms}ms`)
        }
        throw e
    })
}

export default waitForExist


text:
class AddRegionReferenceToMovie < ActiveRecord::Migration
  def change
    add_reference :movies, :region, index: true
  end
end


text:
@implementation UIView (Frame)
//加属性第一种方法,写@dynamic自动生成get,set方法
//@dynamic x;
//@dynamic y;
//@dynamic width;
//@dynamic heigth;
//centerX属性的get,set
- (void)setZw_centerX:(CGFloat)zw_centerX
{
    CGPoint center = self.center;
    center.x = zw_centerX;
    self.center = center;
}
- (CGFloat)zw_centerX
{
    return self.center.x;
}
//centerY属性的get,set
- (void)setZw_centerY:(CGFloat)zw_centerY
{
    CGPoint center = self.center;
    center.y = zw_centerY;
    self.center = center;
}
- (CGFloat)zw_centerY
{
    return self.center.y;
}

- (void)setZw_x:(CGFloat)zw_x {
    CGRect frame = self.frame;
    frame.origin.x = zw_x;
    self.frame = frame;
}
- (CGFloat)zw_x {
    return self.frame.origin.x;
}

- (void)setZw_y:(CGFloat)zw_y {
    CGRect frame = self.frame;
    frame.origin.y = zw_y;
    self.frame = frame;
}
- (CGFloat)zw_y {
    return self.frame.origin.y;
}

-(void)setZw_width:(CGFloat)zw_width {
    CGRect frame = self.frame;
    frame.size.width = zw_width;
    self.frame = frame;
}
- (CGFloat)zw_width {
    return self.frame.size.width;
}

- (void)setZw_height:(CGFloat)zw_height {
    CGRect frame = self.frame;
    frame.size.height = zw_height;
    self.frame = frame;
}
- (CGFloat)zw_height {
    return self.frame.size.height;
}

- (void)setZw_origin:(CGPoint)zw_origin
{
    CGRect frame = self.frame;
    frame.origin = zw_origin;
    self.frame = frame;
}
- (CGPoint)zw_origin
{
    return self.frame.origin;
}

- (void)setZw_size:(CGSize)zw_size
{
    CGRect frame = self.frame;
    frame.size = zw_size;
    self.frame = frame;
}

- (CGSize)zw_size
{
    return self.frame.size;
}
@end


text:
@interface MainViewController : UIViewController <FlipsideViewControllerDelegate, UIPopoverControllerDelegate, UITextViewDelegate>

@property (strong, nonatomic) UIPopoverController *flipsidePopoverController;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (strong, nonatomic) IBOutlet UIBarButtonItem *btDismissKeyboard;
@property (weak, nonatomic) IBOutlet UINavigationBar *navBar;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segControlFileType;

- (IBAction)btLoadProfileTouched:(id)sender;
- (IBAction)dismissKeyboard:(id)sender;
- (IBAction)segControlValueChanged:(id)sender;

@end