text:
@interface CPSegmentControl ()
{
    float currentX;
    int i;
    NSArray *array;
}

@end

@implementation CPSegmentControl

- (instancetype)initWithFrame:(CGRect)frame items:(NSArray<NSString*> *)items
{
    self = [super initWithFrame:frame];
    if (self) {
        array = items;

        if (items && items.count > 0) {
            i = 0;
            for (NSString *string in items) {
                [self createItemWithText:string];
                i++;
            }

            [self setSelectedIndex:0];
        }
    }
    return self;
}

- (void)createItemWithText:(NSString *)text {
    CGFloat itemW = self.frame.size.width / self.items.count;
    CGFloat itemH = self.frame.size.height;

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(currentX, 0, itemW, itemH)];
    [button setTitle:text forState:UIControlStateNormal];
    [[button titleLabel] setFont:[UIFont systemFontOfSize:itemH / 2]];
    [button addTarget:self action:@selector(clickedItemButton:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button];

    currentX += itemW;

    if (self.items.count > 2 && i < self.items.count - 1) {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(currentX - 1, 0, 2, self.frame.size.height)];
        [line setBackgroundColor:self.selectedColor];
        [self addSubview:line];
    }
}

#pragma mark - Buttons Action

- (void)clickedItemButton:(UIButton *)button {
    float animationDuration = 0.4;

    [UIView animateWithDuration:animationDuration animations:^{
        [button setBackgroundColor:self.selectedColor];
        for (UIButton *but in self.subviews) {
            if ([but isKindOfClass:[UIButton class]]) {
                if (but != button) {
                    [but setBackgroundColor:self.color];
                }
            }
            else if ([button isKindOfClass:[UIView class]]) {
                [button setBackgroundColor:self.selectedColor];
            }
        }
    }];

    [UIView transitionWithView:[button titleLabel]
                      duration:animationDuration
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
        [button setTitleColor:self.color forState:UIControlStateNormal];
    } completion:nil];

    for (UIButton *but in self.subviews) {
        if ([but isKindOfClass:[UIButton class]]) {
            if (but != button) {
                [UIView transitionWithView:[but titleLabel]
                                  duration:animationDuration
                                   options:UIViewAnimationOptionTransitionCrossDissolve
                                animations:^{
                    [but setTitleColor:self.selectedColor forState:UIControlStateNormal];
                } completion:nil];
            }
        }
    }
}

#pragma mark - Getters

- (UIColor *)selectedColor {
    return self.selectedColor = _selectedColor != nil ? _selectedColor : [UIColor blueColor];
}

- (UIColor *)color {
    return self.color = _color != nil ? _color : [UIColor whiteColor];
}

- (NSString *)selectedItem {
    return [self.items objectAtIndex:self.selectedIndex];
}

- (NSArray *)items {
    return array;
}

#pragma mark - Setters

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    int index = 0;
    for (UIButton *button in self.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            if (index == selectedIndex) {
                [button setTitleColor:self.color forState:UIControlStateNormal];
                [button setBackgroundColor:self.selectedColor];
            }
            else {
                [button setTitleColor:self.selectedColor forState:UIControlStateNormal];
                [button setBackgroundColor:self.color];
            }
            index++;
        }
        else if ([button isKindOfClass:[UIView class]]) {
            [button setBackgroundColor:self.selectedColor];
        }
    }
}

- (void)setFont:(UIFont *)font {
    for (UIButton *button in self.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            [[button titleLabel] setFont:font];
        }
    }
}

@end


text:
var https = require('https');
var solrApi={
	getRequestParam: function(options){
		var requestParam={
		    "search_intent": options.search_intent,
		    "min_inr": options.minRent,
		    "max_inr": options.maxrent,//
		    "house_type": options.houseTypes,
		    "bed_rooms": options.bedRooms,
		    "page": 1,
		    "city": options.cityName,
		    "show_ungrouped_results": 0,//?
		    "physically_verified": 0,//?
		    "bachelors_allowed": "", //?
		    "time_stamp": options.time_stamp,
		    "request_id": options.request_id,
		    "fetch_max": 1,
		    "number_of_children": "2",
		    "mapBounds": [options.lat1, options.lng1, options.lat2, options.lng2],
		    "srtby": "bestquality",
		    "page_size": 30
			};
			return requestParam;
	},
	getJsonDataFromUrl: function  (options, callback) {
		var http = require('http');
		var req = http.request(options, function(res){
			var responseString = '';
			res.setEncoding('utf-8');
			var responseString = '';
			res.on('data', function(data) {
				responseString += data;
			});
			res.on('end', function() {
				callback(null, responseString);
			});
		});
		req.on('error', callback);
		req.end();
	},
	getJsonData: function (options, callback) {
		var dataString = JSON.stringify(this.getRequestParam(options));
		var headers = {
			'Content-Type': 'application/json',
			'Content-Length': dataString.length
		};
		var requestOptions = {
			host: "www.commonfloor.com",
			path: "/nitro/search/search-results",
			method: "POST",
			headers: headers
		};
		var req = https.request(requestOptions, function(res) {
			res.setEncoding('utf-8');
			var responseString = '';
			res.on('data', function(data) {
				responseString += data;
			});
			res.on('end', function() {
				callback(null, responseString);
			});
		});
		req.on('error', callback);
		req.end(dataString);
	}
}
module.exports=solrApi;

redpajama_set_name: RedPajamaGithub


text:
#ifndef PageSerializer_h
#define PageSerializer_h

#include "core/CoreExport.h"
#include "platform/heap/Handle.h"
#include "platform/weborigin/KURL.h"
#include "platform/weborigin/KURLHash.h"
#include "wtf/HashMap.h"
#include "wtf/ListHashSet.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/Vector.h"

namespace blink {

class Attribute;
class FontResource;
class ImageResource;
class CSSRule;
class CSSStyleSheet;
class CSSValue;
class Document;
class LocalFrame;
class Page;
class LayoutObject;
class Resource;
class SharedBuffer;
class StylePropertySet;

struct SerializedResource;

// This class is used to serialize a page contents back to text (typically HTML).
// It serializes all the page frames and retrieves resources such as images and CSS stylesheets.
class CORE_EXPORT PageSerializer final {
    STACK_ALLOCATED();
public:
    class Delegate {
        USING_FAST_MALLOC(Delegate);
    public:
        virtual ~Delegate() { }
        virtual bool shouldIgnoreAttribute(const Attribute&) = 0;
    };

    PageSerializer(Vector<SerializedResource>*, PassOwnPtr<Delegate>);

    // Initiates the serialization of the frame's page. All serialized content and retrieved
    // resources are added to the Vector passed to the constructor. The first resource in that
    // vector is the top frame serialized content.
    void serialize(Page*);

    void registerRewriteURL(const String& from, const String& to);
    void setRewriteURLFolder(const String&);

    KURL urlForBlankFrame(LocalFrame*);

    Delegate* delegate();

    static String markOfTheWebDeclaration(const KURL&);

private:
    void serializeFrame(LocalFrame*);

    // Serializes the stylesheet back to text and adds it to the resources if URL is not-empty.
    // It also adds any resources included in that stylesheet (including any imported stylesheets and their own resources).
    void serializeCSSStyleSheet(CSSStyleSheet&, const KURL&);

    // Serializes the css rule (including any imported stylesheets), adding referenced resources.
    void serializeCSSRule(CSSRule*);

    bool shouldAddURL(const KURL&);

    void addToResources(Resource *, PassRefPtr<SharedBuffer>, const KURL&);
    void addImageToResources(ImageResource*, LayoutObject*, const KURL&);
    void addFontToResources(FontResource*);

    void retrieveResourcesForProperties(const StylePropertySet*, Document&);
    void retrieveResourcesForCSSValue(CSSValue*, Document&);

    Vector<SerializedResource>* m_resources;
    ListHashSet<KURL> m_resourceURLs;

    using BlankFrameURLMap = WillBeHeapHashMap<RawPtrWillBeMember<LocalFrame>, KURL>;
    BlankFrameURLMap m_blankFrameURLs;
    HashMap<String, String> m_rewriteURLs;
    String m_rewriteFolder;
    unsigned m_blankFrameCounter;

    OwnPtr<Delegate> m_delegate;
};

} // namespace blink

#endif // PageSerializer_h


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Services.Scheduling
{
    using System;
    using System.Data;
    using System.Text;

    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Instrumentation;

    [Serializable]
    public class ScheduleHistoryItem : ScheduleItem
    {
        private static readonly ILog _tracelLogger = LoggerSource.Instance.GetLogger(typeof(ScheduleHistoryItem));

        private StringBuilder _LogNotes;
        private int _ScheduleHistoryID;
        private string _Server;
        private DateTime _StartDate;
        private bool _Succeeded;

        /// <summary>
        /// Initializes a new instance of the <see cref="ScheduleHistoryItem"/> class.
        /// </summary>
        public ScheduleHistoryItem()
        {
            this._ScheduleHistoryID = Null.NullInteger;
            this._StartDate = Null.NullDate;
            this.EndDate = Null.NullDate;
            this._Succeeded = Null.NullBoolean;
            this._LogNotes = new StringBuilder();
            this._Server = Null.NullString;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ScheduleHistoryItem"/> class.
        /// </summary>
        /// <param name="objScheduleItem"></param>
        public ScheduleHistoryItem(ScheduleItem objScheduleItem)
        {
            this.AttachToEvent = objScheduleItem.AttachToEvent;
            this.CatchUpEnabled = objScheduleItem.CatchUpEnabled;
            this.Enabled = objScheduleItem.Enabled;
            this.NextStart = objScheduleItem.NextStart;
            this.ObjectDependencies = objScheduleItem.ObjectDependencies;
            this.ProcessGroup = objScheduleItem.ProcessGroup;
            this.RetainHistoryNum = objScheduleItem.RetainHistoryNum;
            this.RetryTimeLapse = objScheduleItem.RetryTimeLapse;
            this.RetryTimeLapseMeasurement = objScheduleItem.RetryTimeLapseMeasurement;
            this.ScheduleID = objScheduleItem.ScheduleID;
            this.ScheduleSource = objScheduleItem.ScheduleSource;
            this.ThreadID = objScheduleItem.ThreadID;
            this.TimeLapse = objScheduleItem.TimeLapse;
            this.TimeLapseMeasurement = objScheduleItem.TimeLapseMeasurement;
            this.TypeFullName = objScheduleItem.TypeFullName;
            this.Servers = objScheduleItem.Servers;
            this.FriendlyName = objScheduleItem.FriendlyName;
            this._ScheduleHistoryID = Null.NullInteger;
            this._StartDate = Null.NullDate;
            this.EndDate = Null.NullDate;
            this._Succeeded = Null.NullBoolean;
            this._LogNotes = new StringBuilder();
            this._Server = Null.NullString;
            this.ScheduleStartDate = objScheduleItem.ScheduleStartDate != Null.NullDate
                                    ? objScheduleItem.ScheduleStartDate
                                    : Null.NullDate;
        }

        public double ElapsedTime
        {
            get
            {
                try
                {
                    if (this.EndDate == Null.NullDate && this._StartDate != Null.NullDate)
                    {
                        return DateTime.Now.Subtract(this._StartDate).TotalSeconds;
                    }
                    else if (this._StartDate != Null.NullDate)
                    {
                        return this.EndDate.Subtract(this._StartDate).TotalSeconds;
                    }
                    else
                    {
                        return 0;
                    }
                }
                catch
                {
                    return 0;
                }
            }
        }

        public bool Overdue
        {
            get
            {
                if (this.NextStart < DateTime.Now && this.EndDate == Null.NullDate)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public double OverdueBy
        {
            get
            {
                try
                {
                    if (this.NextStart <= DateTime.Now && this.EndDate == Null.NullDate)
                    {
                        return Math.Round(DateTime.Now.Subtract(this.NextStart).TotalSeconds);
                    }
                    else
                    {
                        return 0;
                    }
                }
                catch
                {
                    return 0;
                }
            }
        }

        public double RemainingTime
        {
            get
            {
                try
                {
                    if (this.NextStart > DateTime.Now && this.EndDate == Null.NullDate)
                    {
                        return Math.Round(this.NextStart.Subtract(DateTime.Now).TotalSeconds);
                    }
                    else
                    {
                        return 0;
                    }
                }
                catch
                {
                    return 0;
                }
            }
        }

        /// <inheritdoc/>
        public override DateTime NextStart { get; set; }

        public DateTime EndDate { get; set; }

        public string LogNotes
        {
            get
            {
                return this._LogNotes.ToString();
            }

            set
            {
                this._LogNotes = new StringBuilder(value);
            }
        }

        public int ScheduleHistoryID
        {
            get
            {
                return this._ScheduleHistoryID;
            }

            set
            {
                this._ScheduleHistoryID = value;
            }
        }

        public string Server
        {
            get
            {
                return this._Server;
            }

            set
            {
                this._Server = value;
            }
        }

        public DateTime StartDate
        {
            get
            {
                return this._StartDate;
            }

            set
            {
                this._StartDate = value;
            }
        }

        public bool Succeeded
        {
            get
            {
                return this._Succeeded;
            }

            set
            {
                this._Succeeded = value;
                if (_tracelLogger.IsDebugEnabled)
                {
                    _tracelLogger.Debug($"ScheduleHistoryItem.Succeeded Info (ScheduledTask {(value == false ? "Start" : "End")}): {this.FriendlyName}");
                }
            }
        }

        public virtual void AddLogNote(string notes)
        {
            this._LogNotes.Append(notes);
            if (_tracelLogger.IsTraceEnabled)
            {
                _tracelLogger.Trace(notes.Replace(@"<br/>", Environment.NewLine));
            }
        }

        /// <inheritdoc/>
        public override void Fill(IDataReader dr)
        {
            this.ScheduleHistoryID = Null.SetNullInteger(dr["ScheduleHistoryID"]);
            this.StartDate = Null.SetNullDateTime(dr["StartDate"]);
            this.EndDate = Null.SetNullDateTime(dr["EndDate"]);
            this.Succeeded = Null.SetNullBoolean(dr["Succeeded"]);
            this.LogNotes = Null.SetNullString(dr["LogNotes"]);
            this.Server = Null.SetNullString(dr["Server"]);
            this.FillInternal(dr);
        }
    }
}


text:
package ru.creditnet.progressbar;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;

import static ru.creditnet.progressbar.ConsoleProgressBar.DEFAULT_TICK_MILLIS;

/**
 * @author antivoland
 */
public class DrunkPiratesTest {
    private static final Logger LOG = LoggerFactory.getLogger(DrunkPiratesTest.class);
    private static final int PIRATES = 999;
    private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(PIRATES);

    @AfterClass
    public static void destroy() {
        THREAD_POOL.shutdownNow();
    }

    @Test
    public void testLesser() throws Exception {
        test(PIRATES - 1);
        test(PIRATES / 2);
    }

    @Test
    public void testExact() throws Exception {
        test(PIRATES);
    }

    @Test
    public void testGreater() throws Exception {
        test(PIRATES + 1);
        test(PIRATES * 2);
    }

    public void test(int bottles) throws Exception {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try (ConsoleProgressBar bar = new ConsoleProgressBar(bottles, new PrintStream(buffer), DEFAULT_TICK_MILLIS)) {
            CountDownLatch start = new CountDownLatch(1);
            CountDownLatch finish = new CountDownLatch(PIRATES);
            Stream.generate(() -> drink(start, finish, bar)).limit(PIRATES).forEach(THREAD_POOL::submit);
            start.countDown();
            finish.await();
        }

        ProgressState expected = new ProgressState(bottles);
        expected.stepBy(PIRATES);
        String expectedPercentage = ConsoleDrawer.PERCENTAGE_FORMAT.apply(expected.max(), expected.current());
        String expectedAbsoluteRatio = ConsoleDrawer.ABSOLUTE_RATIO_FORMAT.apply(expected.max(), expected.current());

        String actual = buffer.toString();
        Assert.assertTrue(actual.contains(expectedPercentage));
        Assert.assertTrue(actual.contains(expectedAbsoluteRatio));
        LOG.info(String.format("%s bottles of beer on the wall, %s bottles of beer were drunk", expected.max() - expected.current(), expectedPercentage.trim()));
    }

    private Runnable drink(CountDownLatch start, CountDownLatch finish, ConsoleProgressBar bar) {
        return () -> {
            try {
                start.await();
                bar.step();
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                finish.countDown();
            }
        };
    }
}


text:
"""Wrapper to stack multiple gym.spaces.Box observations.

Note: Unlike atari_wrappers.py we do not use LazyFrames to ensure observations
don't repeat memory, and we only support 1D observations.
"""

import collections

import gym
from gym import spaces
import numpy as np
from tf_agents.environments import py_environment
from tf_agents.environments import wrappers
from tf_agents.specs import array_spec
from tf_agents.trajectories import time_step as ts
from tf_agents.typing import types

class FrameStackWrapper(gym.Wrapper):
  """Env wrapper to Stack k last frames."""

  def __init__(self, env, k):
    if not isinstance(env.observation_space, spaces.Box):
      raise ValueError('env %s does not use spaces.Box.' % str(env))
    super(FrameStackWrapper, self).__init__(env)

    if not isinstance(k, int):
      raise ValueError('Expected integer k')
    self.k = k
    self.frames = collections.deque([], maxlen=k)
    obs = env.observation_space
    if len(obs.shape) != 1:
      raise ValueError('Only 1D observations supported.')
    self.observation_space = spaces.Box(
        low=np.tile(obs.low.tolist(), k),
        high=np.tile(obs.high.tolist(), k),
        dtype=obs.dtype)
    self._max_episode_steps = env._max_episode_steps  # pylint: disable=protected-access

  def reset(self):
    ob = self.env.reset()
    for _ in range(self.k):
      self.frames.append(ob)
    return self._get_ob()

  def step(self, action):
    ob, reward, done, info = self.env.step(action)
    self.frames.append(ob)
    return self._get_ob(), reward, done, info

  def _get_ob(self):
    assert len(self.frames) == self.k
    return np.concatenate(self.frames)

def stack_expert_frames(expert_data, k):
  """Stack exert (s, a, s', d, r) tuples from the flattened data format."""
  if not isinstance(expert_data, dict):
    raise ValueError('Expected dict expert data.')

  stacked_data = {key: [] for key in expert_data}

  def _reset_to_frame(i):
    state = collections.deque([], maxlen=k)
    for _ in range(k):
      state.append(expert_data['states'][i])
    return state

  state = _reset_to_frame(0)
  nsteps = expert_data['dones'].shape[0]

  for i, done in enumerate(expert_data['dones']):
    # Calculate the stacked tuple and append.
    stacked_data['states'].append(np.concatenate(state))
    stacked_data['actions'].append(expert_data['actions'][i])
    state.append(expert_data['next_states'][i])
    stacked_data['next_states'].append(np.concatenate(state))
    stacked_data['dones'].append(done)
    if 'rewards' in stacked_data:
      stacked_data['rewards'].append(expert_data['rewards'][i])

    if done and (i + 1) < nsteps:
      state = _reset_to_frame(i + 1)

  for key, value in stacked_data.items():
    stacked_data[key] = np.stack(value)
    assert stacked_data[key].shape[0] == nsteps

  return stacked_data

class FrameStackWrapperTfAgents(wrappers.PyEnvironmentBaseWrapper):
  """Env wrapper to stack k last frames.

  Maintains a circular buffer of the last k frame observations and returns
  TimeStep including a concatenated state vector (with the last frames action,
  reward, etc). Used to train models with multi-state context.

  Note, the first frame's state is replicated k times to produce a state vector
  sequence of [s_0, s_0, ..., s_0], [s_0, s_0, ..., s_1], etc.
  """

  def __init__(self, env, k):
    super(FrameStackWrapperTfAgents, self).__init__(env)

    obs_spec: array_spec.ArraySpec = self._env.observation_spec()
    if not isinstance(obs_spec, array_spec.ArraySpec):
      raise ValueError('Unsupported observation_spec %s' % str(obs_spec))
    if len(obs_spec.shape) != 1 and len(obs_spec.shape) != 3:
      raise ValueError(
          'Only 1D or 3D observations supported (found shape %s)' % (
              str(obs_spec.shape)))

    if len(obs_spec.shape) == 1:
      self._stacked_observation_spec = array_spec.ArraySpec(
          shape=(obs_spec.shape[0] * k,),
          dtype=obs_spec.dtype,
          name=obs_spec.name + '_stacked')
    else:
      self._stacked_observation_spec = array_spec.ArraySpec(
          shape=(obs_spec.shape[0:2] + (obs_spec.shape[2] * k,)),
          dtype=obs_spec.dtype,
          name=obs_spec.name + '_stacked')

    self._k: int = k
    self._timesteps = collections.deque([], maxlen=k)
    if hasattr(env, '_max_episode_steps'):
      self._max_episode_steps = env._max_episode_steps  # pylint: disable=protected-access

  def _reset(self):
    timestep = self._env.reset()
    assert isinstance(timestep, ts.TimeStep), (
        'Expected TimeStep, got %s' % type(timestep))
    for _ in range(self._k):
      self._timesteps.append(timestep)
    return self._get_timestep(timestep)

  def _step(self, action):
    timestep = self._env.step(action)
    assert isinstance(timestep, ts.TimeStep), (
        'Expected TimeStep, got %s' % type(timestep))
    self._timesteps.append(timestep)
    return self._get_timestep(timestep)

  def _get_timestep(self, time_step):
    assert len(self._timesteps) == self._k
    time_step = time_step._asdict()
    time_step['observation'] = np.concatenate([
        frame.observation for frame in self._timesteps], axis=-1)
    # assert self.observation_spec().shape == time_step['observation'].shape
    return ts.TimeStep(**time_step)

  def observation_spec(self):
    return self._stacked_observation_spec


text:
const config = {
  port: '5001',
  database: 'localhost/wheretogo-test',
};

module.exports = config;


text:
//
//  KTSecretColorChooserViewController.m
//
//  Created by Kenny Tang on 4/29/14.
//  Copyright (c) 2014 Corgitoergosum. All rights reserved.
//

#import "KTSecretColorChooserViewController.h"

typedef NS_ENUM(NSUInteger, KTSecretDefaultColor)
{
    KTSecretDefaultColorEmeraldSea = 0,
    KTSecretDefaultColorHopscotch,
    KTSecretDefaultColorLavender,
    KTSecretDefaultColorBurst,
    KTSecretDefaultColorCupid,
    KTSecretDefaultColorPeony,
    KTSecretDefaultColorMidnight,
    KTSecretDefaultColorWhite
};

static NSString * const kKTSecretColorChooserViewControllerCellIdentifier = @"kKTSecretColorChooserViewControllerCellIdentifier";
static CGFloat const kKTSecretColorChooserViewControllerDefaultCellHeight = 380.0f;

@interface KTSecretColorChooserViewController ()<
UICollectionViewDataSource,
UICollectionViewDelegate
>

/**
 *  Collection view which holds each color as a cell.
 */
@property (nonatomic, strong) UICollectionView *collectionView;

/**
 *  Normal layout: each cell is wide as the screen bounds' width.
 */
@property (nonatomic, strong) UICollectionViewFlowLayout *defaultLayout;

/**
 *  Compressed layout: this is what makes the "rainbow" view. All cells resized to fit on the screen bounds' width.
 */
@property (nonatomic, strong) UICollectionViewFlowLayout *paletteLayout;

/**
 *  Long Press gesture recognizer toggles between the two layout modes.
 */
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGestureRecognizer;

/**
 *  Gesture recognizers for vertical swipes. Mainly for passing through to delegate.
 */
@property (nonatomic, strong) UISwipeGestureRecognizer *swipeUpGestureRecognizer;
@property (nonatomic, strong) UISwipeGestureRecognizer *swipeDownGestureRecognizer;

/**
 *  The various cell sizes for each layout
 */
@property (nonatomic) CGSize defaultCellSize;
@property (nonatomic) CGSize paletteCellSize;

/**
 *  The currently selected cell size
 */
@property (nonatomic) CGSize currentCellSize;

/**
 *  Tap gesture recognizer decides whether to propagate tap gestures to a delegate.
 */
@property (nonatomic, strong) UITapGestureRecognizer *tapGestureRecognizer;

/**
 *  Semi-transparent view that is displayed on a long press to indicate which color is being selected.
 */
@property (nonatomic, strong) UIView *hoverColorView;

/**
 *  NSDictionary of colors made available for selection
 */
@property (nonatomic, strong) NSDictionary *colorsDict;

/**
 *  Array of color names made available for selection
 */
@property (nonatomic, strong) NSDictionary *colorNamesDict;

@end

@implementation KTSecretColorChooserViewController

#pragma mark - Public

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self addSubviewTree];
    [self constrainViews];

    [self setUpGestureRecognizers];

    self.currentCellSize = self.defaultCellSize;
    [self.collectionView reloadData];

}

- (void)loadView
{
    self.view = [self mainView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Initialization

- (void)setUpGestureRecognizers
{
    UIView *collectionView = self.collectionView;
    [collectionView addGestureRecognizer:self.longPressGestureRecognizer];
    [collectionView addGestureRecognizer:self.tapGestureRecognizer];
    [collectionView addGestureRecognizer:self.swipeUpGestureRecognizer];
    [collectionView addGestureRecognizer:self.swipeDownGestureRecognizer];

    [self.swipeUpGestureRecognizer requireGestureRecognizerToFail:self.longPressGestureRecognizer];
    [self.swipeDownGestureRecognizer requireGestureRecognizerToFail:self.longPressGestureRecognizer];

}

- (UIView *)mainView
{
    UIView *mainView = [UIView new];
    mainView.translatesAutoresizingMaskIntoConstraints = NO;
    mainView.alpha = 0.9;
    mainView.clipsToBounds = YES;
    return mainView;
}

- (void)addSubviewTree
{
    [self.view addSubview:self.collectionView];
    [self.collectionView addSubview:self.hoverColorView];
}

- (void)constrainViews
{
    NSDictionary *viewsDict = @{@"collectionView":self.collectionView};

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[collectionView]|" options:0 metrics:nil views:viewsDict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[collectionView]|" options:0 metrics:nil views:viewsDict]];

}

#pragma mark - Private

#pragma mark - Private properties

- (UISwipeGestureRecognizer*) swipeUpGestureRecognizer
{
    if (!_swipeUpGestureRecognizer) {
        _swipeUpGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleUpSwipe:)];
        _swipeUpGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
    }
    return _swipeUpGestureRecognizer;
}

- (UISwipeGestureRecognizer*) swipeDownGestureRecognizer
{
    if (!_swipeDownGestureRecognizer) {
        _swipeDownGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleDownSwipe:)];
        _swipeDownGestureRecognizer.direction = UISwipeGestureRecognizerDirectionDown;
    }
    return _swipeDownGestureRecognizer;
}

- (UICollectionViewFlowLayout*) defaultLayout
{
    if (!_defaultLayout){
        _defaultLayout = [UICollectionViewFlowLayout new];
        _defaultLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _defaultLayout.itemSize = self.defaultCellSize;
        _defaultLayout.minimumInteritemSpacing = 0.0f;
        _defaultLayout.minimumLineSpacing = 0.0f;
    }
    return _defaultLayout;
}

- (UICollectionViewFlowLayout*) paletteLayout
{
    if (!_paletteLayout){
        _paletteLayout = [UICollectionViewFlowLayout new];
        _paletteLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _paletteLayout.itemSize = self.paletteCellSize;
        _paletteLayout.minimumInteritemSpacing = 0.0f;
        _paletteLayout.minimumLineSpacing = 0.0f;
    }
    return _paletteLayout;
}

- (UICollectionView*)collectionView
{
    if (!_collectionView){
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.defaultLayout];
        _collectionView.translatesAutoresizingMaskIntoConstraints = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.clipsToBounds = YES;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:kKTSecretColorChooserViewControllerCellIdentifier];
    }
    return _collectionView;
}

- (NSDictionary*) colorsDict
{
    if (!_colorsDict){
        _colorsDict = @{
                        @(KTSecretDefaultColorWhite)        :   [UIColor whiteColor],
                        @(KTSecretDefaultColorEmeraldSea)   :   [UIColor colorWithRed:18.0f/255.0f green:133.0f/255.0f blue:116.0/255.0f alpha:1.0],
                        @(KTSecretDefaultColorHopscotch)    :   [UIColor colorWithRed:157.0f/255.0f green:105.0f/255.0f blue:183.0/255.0f alpha:1.0],
                        @(KTSecretDefaultColorLavender)     :   [UIColor colorWithRed:100.0f/255.0f green:57.0f/255.0f blue:144.0/255.0f alpha:1.0],
                        @(KTSecretDefaultColorBurst)        :   [UIColor colorWithRed:213.0f/255.0f green:100.0f/255.0f blue:12.0f/255.0f alpha:1.0],
                        @(KTSecretDefaultColorCupid)        :   [UIColor colorWithRed:157.0f/255.0f green:30.0f/255.0f blue:38.0f/255.0f alpha:1.0],
                        @(KTSecretDefaultColorPeony)        :   [UIColor colorWithRed:220.0f/255.0f green:72.0f/255.0f blue:99.0f/255.0f alpha:1.0],
                        @(KTSecretDefaultColorMidnight)     :  [UIColor colorWithRed:39.0f/255.0f green:36.0f/255.0f blue:32.0f/255.0f alpha:1.0]
                        };
    }
    return _colorsDict;
}

- (NSDictionary*) colorNamesDict
{
    if (!_colorNamesDict){
        _colorNamesDict = @{
                            @(KTSecretDefaultColorEmeraldSea)   :   NSLocalizedString(@"Emerald Sea", nil),
                            @(KTSecretDefaultColorHopscotch)    :   NSLocalizedString(@"Hopscotch", nil),
                            @(KTSecretDefaultColorLavender)     :   NSLocalizedString(@"Lavender", nil),
                            @(KTSecretDefaultColorBurst)        :   NSLocalizedString(@"Burst", nil),
                            @(KTSecretDefaultColorCupid)        :   NSLocalizedString(@"Cupid", nil),
                            @(KTSecretDefaultColorPeony)        :   NSLocalizedString(@"Peony", nil),
                            @(KTSecretDefaultColorMidnight)     :   NSLocalizedString(@"Midnight", nil),
                            @(KTSecretDefaultColorWhite)        :   NSLocalizedString(@"Default", nil)
                            };
    }
    return _colorNamesDict;
}

- (UILongPressGestureRecognizer*) longPressGestureRecognizer
{
    if (!_longPressGestureRecognizer) {
        _longPressGestureRecognizer = [UILongPressGestureRecognizer new];
        [_longPressGestureRecognizer addTarget:self action:@selector(handleLongPressGesture:)];
    }
    return _longPressGestureRecognizer;
}

- (UITapGestureRecognizer*) tapGestureRecognizer
{
    if (!_tapGestureRecognizer) {
        _tapGestureRecognizer = [UITapGestureRecognizer new];
        [_tapGestureRecognizer addTarget:self action:@selector(handleTapGesture:)];
    }
    return _tapGestureRecognizer;
}

- (CGSize) defaultCellSize
{
    return CGSizeMake([[UIScreen mainScreen] bounds].size.width, kKTSecretColorChooserViewControllerDefaultCellHeight);
}

- (CGSize) paletteCellSize
{
    return CGSizeMake(([[UIScreen mainScreen] bounds].size.width)/[self.colorsDict count], kKTSecretColorChooserViewControllerDefaultCellHeight);
}

- (UIView*)hoverColorView
{
    if (!_hoverColorView) {
        _hoverColorView = [UIView new];

        float screenWidth = [[UIScreen mainScreen] bounds].size.width;
        float hoverViewWidth = screenWidth/[self.colorsDict count];

        _hoverColorView.frame = CGRectMake(0, 0, hoverViewWidth, self.view.frame.size.height);
        _hoverColorView.backgroundColor = [UIColor lightTextColor];
        _hoverColorView.alpha = 0.4;
        _hoverColorView.hidden = YES;
    }
    return _hoverColorView;
}

#pragma mark - Initialization helpers

#pragma mark - Event handlers

- (void)handleLongPressGesture:(UILongPressGestureRecognizer*)sender
{
    if (sender.state == UIGestureRecognizerStateEnded) {
        [self handleLongPressEnded:sender];

    }else if (sender.state == UIGestureRecognizerStateChanged) {
        [self handleLongPressMoved:sender];

    }else {
        [self handleLongPressStarted:sender];
    }
}

- (void)handleTapGesture:(UITapGestureRecognizer*)sender
{
//    [self.delegate sec
}

#pragma mark - Long Press Activated handlers

- (void)handleLongPressEnded:(UILongPressGestureRecognizer*)sender
{
    self.currentCellSize = self.defaultCellSize;

    // find the selected color
    CGPoint locationInView = [sender locationInView:self.collectionView];
    NSIndexPath *selectedCellIndexPath = [self.collectionView indexPathForItemAtPoint:locationInView];
    UIColor *selectedColor = self.colorsDict[@(selectedCellIndexPath.item)];

    // change to default layout
    CGFloat selectedCellRectX = self.currentCellSize.width*selectedCellIndexPath.item+1;
    self.hoverColorView.hidden = YES;
    [self.collectionView setCollectionViewLayout:self.defaultLayout animated:YES];
    [self.collectionView scrollRectToVisible:CGRectMake(selectedCellRectX, 0, [[UIScreen mainScreen] bounds].size.width, 20.0f) animated:NO];

    // update delegate on selected color
    NSString *colorName = self.colorNamesDict[@(selectedCellIndexPath.item)];
    [self updateDelegateSelectedColor:selectedColor name:colorName];
}

- (void)handleLongPressStarted:(UILongPressGestureRecognizer*)sender
{
    // change to palette layout
    [self.collectionView setCollectionViewLayout:self.paletteLayout animated:YES];
}

- (void)handleLongPressMoved:(UILongPressGestureRecognizer*)sender
{
    // find the cell at touch point
    CGPoint locationInView = [sender locationInView:self.collectionView];
    NSIndexPath *hoverCellIndexPath = [self.collectionView indexPathForItemAtPoint:locationInView];
    UICollectionViewCell *colorCell = [self.collectionView cellForItemAtIndexPath:hoverCellIndexPath];

    // move hover view over cell at touch point
    self.hoverColorView.frame = colorCell.frame;
    self.hoverColorView.hidden = NO;

}

#pragma mark - UIScrollViewDelegate methods

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // find the cell at touch point
    UICollectionViewCell *cell = [[self.collectionView visibleCells] firstObject];
    NSIndexPath *cellIndexPath = [self.collectionView indexPathForCell:cell];

    // use index to find color
    UIColor *selectedColor = self.colorsDict[@(cellIndexPath.item)];

    // update delegate on selected color
    NSString *colorName = self.colorNamesDict[@(cellIndexPath.item)];
    [self updateDelegateSelectedColor:selectedColor name:colorName];
}

#pragma mark - UICollectionViewDataSource methods

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView*)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.colorsDict count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kKTSecretColorChooserViewControllerCellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = self.colorsDict[@(indexPath.item)];

    return cell;
}

#pragma mark - Long Press Ended helper

- (void)updateDelegateSelectedColor:(UIColor*)color name:(NSString*)name
{
    if ([self.delegate respondsToSelector:@selector(secretColorChooserViewController:didSelectColor:name:)]) {

        [self.delegate secretColorChooserViewController:self didSelectColor:color name:name];
    }
}

#pragma mark - UISwipeGestureRecognizer delegate methods

- (void)handleUpSwipe:(UISwipeGestureRecognizer*)gestureRecognizer
{
    if ([self.delegate respondsToSelector:@selector(secretColorChooserViewController:didSwipeUp:)]) {
        [self.delegate secretColorChooserViewController:self didSwipeUp:YES];
    }
}

- (void)handleDownSwipe:(UISwipeGestureRecognizer*)gestureRecognizer
{
    if ([self.delegate respondsToSelector:@selector(secretColorChooserViewController:didSwipeDown:)]) {
        [self.delegate secretColorChooserViewController:self didSwipeDown:YES];
    }
}

@end


text:
/* -*- Mode: C; indent-tabs-mode:nil; c-basic-offset:8 -*- */

/*
 * This file is part of The Croco Library
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of version 2.1 of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 * See COPYRIGHTS file for copyright information
 */

#include <stdio.h>
#include "cr-input.h"
#include "string.h"

/**
 *@file
 *Some test facilities for the #CRInput class.
 */

/**
 *The options data structure.
 *The variable of this data structure are set
 *during the  parsing the command line by the
 *parse_command_line() function.
 */
struct Options {
        gboolean display_help;
        gboolean display_about;
        gchar **files_list;
};

static void
  display_help (char *prg_name);

static void
  display_about (char *prg_name);

static void
  parse_command_line (int a_argc, char **a_argv, struct Options *a_options);

static enum CRStatus
  test_cr_input_read_char (guchar * a_file_uri);

/**
 *Displays the usage of the test
 *facility.
 *@param a_argc the argc variable passed to the main function.
 *@param a_argv the argv variable passed to the main function.
 */
static void
display_help (char *prg_name)
{
        g_print ("\n\n");
        g_print ("usage: %s <file-to-parse>\n", prg_name);
        g_print ("\t <file-to-parse>: the file to parse\n");
        g_print ("\n\n");
        g_print ("This test just reads the file character per character\nand sends each character to stdout\n");
        g_print ("\n\n");
}

/**
 *Displays the about text.
 *@param a_argc the argc variable passed to the main function.
 *@param a_argv the argv variable passed to the main function.
 */
static void
display_about (char *prg_name)
{
        g_print ("\n\n");
        g_print ("%s is a libcroco CRInput class test program.\n", prg_name);
        g_print ("It should run on GNU compliants systems.\n");
        g_print ("\n\n");
        g_print ("Initial author: Dodji Seketeli <dodji@seketeli.org>.\n");
        g_print ("\n\n");
}

/**
 *Parses the command line and updates an abstract "options" data structure.
 *@param a_argc the argc variable passed to the main function by the OS.
 *@param a_argv the argv variable passed to the main function by the OS.
 *@param a_options out parameter. The abstraction of the parsed the options.
 */
static void
parse_command_line (int a_argc, char **a_argv, struct Options *a_options)
{
        int i = 0;

        g_return_if_fail (a_options);

        memset (a_options, 0, sizeof (struct Options));

        for (i = 1; i < a_argc; i++) {
                if (a_argv[i][0] != '-')
                        break;

                if (!strcmp (a_argv[i], "-h")
                    || !strcmp (a_argv[i], "--help")) {
                        a_options->display_help = TRUE;
                }
                if (!strcmp (a_argv[i], "--about")) {
                        a_options->display_about = TRUE;
                }
        }

        if (i >= a_argc) {
                /*No file parameter where given */
                a_options->files_list = NULL;
        } else {
                a_options->files_list = &a_argv[i];
        }
}

/**
 *The test of the cr_input_read_byte() method.
 *Reads the each byte of a_file_uri using the
 *cr_input_read_byte() method. Each byte is send to
 *stdout.
 *@param a_file_uri the file to read.
 *@return CR_OK upon successfull completion of the
 *function, an error code otherwise.
 */
enum CRStatus
test_cr_input_read_char (guchar * a_file_uri)
{
        enum CRStatus status = CR_OK;
        CRInput *input = NULL;
        guint32 c = 0;

        g_return_val_if_fail (a_file_uri, CR_BAD_PARAM_ERROR);

        input = cr_input_new_from_uri (a_file_uri, CR_UTF_8);

        if (!input) {
                cr_utils_trace_debug ("Input Stream creation failed.");
                return CR_ERROR;
        }

        for (status = CR_OK; status == CR_OK;) {
                status = cr_input_read_char (input, &c);

                if (status == CR_OK) {
                        printf ("%c", c);
                        fflush (stdout);
                }
        }

        if (status == CR_END_OF_INPUT_ERROR) {
                status = CR_OK;
        }

        cr_input_destroy (input);
        input = NULL;

        return status;
}

/**
 *The entry point of the testing routine.
 */
int
main (int argc, char **argv)
{
        struct Options options;

        parse_command_line (argc, argv, &options);

        if (options.display_help == TRUE) {
                display_help (argv[0]);
                return 0;
        }

        if (options.display_about == TRUE) {
                display_about (argv[0]);
                return 0;
        }

        if (options.files_list == NULL) {
                display_help (argv[0]);
                return 0;
        }

        test_cr_input_read_char (options.files_list[0]);

        return 0;
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Brozerly</title>
<link rel="shortcut icon" type="image/x-icon" href="https://www.brozerly.com/public/favicon.ico"/>
<link rel="icon" type="image/x-icon" href="https://www.brozerly.com/public/favicon.ico"/>

<meta http-equiv="Content-Language" content="fr">

<link rel="alternate" hreflang="es" href='https://www.brozerly.com/index'/>
<link rel="alternate" hreflang="fr" href='https://www.brozerly.com/fr/index'/>
<link rel="alternate" hreflang="eu" href='https://www.brozerly.com/eu/index'/>
<link rel="alternate" hreflang="en" href='https://www.brozerly.com/en/index'/>

<link rel="canonical" href='https://www.brozerly.com/fr/'/>

<meta property="description"
      content="Gratuite et sans frais !. L'amitié est la meilleure des protections. Brozerly est ton application de crowdfunding pour les besoins personnels. La première application sociale d'entraide pour les besoins personnels.. Brozerly te permets de demander de l'aide à ton réseau d'amis afin que te amis puissent t'aider à remplacer ou acheter l'objet dont tu rêves. Crowdfunding app."/>
<meta name="description"
      content="Gratuite et sans frais !. L'amitié est la meilleure des protections. Brozerly est ton application de crowdfunding pour les besoins personnels. La première application sociale d'entraide pour les besoins personnels.. Brozerly te permets de demander de l'aide à ton réseau d'amis afin que te amis puissent t'aider à remplacer ou acheter l'objet dont tu rêves. Crowdfunding app."/>

<meta http-equiv="cleartype" content="on"/>
<meta name="MobileOptimized" content="320"/>
<meta name="HandheldFriendly" content="True"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

<meta property="fb:app_id" content="511393345697381"/>
<meta property="al:ios:url" content="com.brozerly.app://home"/>
<meta property="al:ios:app_store_id" content="1076641036"/>
<meta property="al:ios:app_name" content="Brozerly"/>
<meta property="al:android:url" content="com.brozerly.app://home"/>
<meta property="al:android:app_name" content="Brozerly"/>
<meta property="al:android:package" content="com.brozerly.app"/>
<meta property="al:web:url" content="https://www.brozerly.com"/>

<meta name="twitter:card" content="app"/>
<meta name="twitter:site" content="@Brozerly"/>
<meta name="twitter:creator" content="@Brozerly"/>
<meta name="twitter:app:country" content="FR"/>
<meta name="twitter:app:name:iphone" content="Brozerly"/>
<meta name="twitter:app:id:iphone" content="1076641036"/>
<meta name="twitter:app:url:iphone" content="com.brozerly.app://home"/>
<meta name="twitter:app:name:ipad" content="Brozerly"/>
<meta name="twitter:app:id:ipad" content="1076641036"/>
<meta name="twitter:app:url:ipad" content="com.brozerly.app://home"/>
<meta name="twitter:app:name:googleplay" content="Brozerly"/>
<meta name="twitter:app:id:googleplay" content="com.brozerly.app"/>
<meta name="twitter:app:url:googleplay" content="com.brozerly.app://home"/>

<meta name="p:domain_verify" content="7b3b1baab2188e3b334affe642df77cf"/>

<meta property="og:url" content='https://www.brozerly.com/fr/'/>
<meta property="og:type" content="website"/>
<meta property="og:title" content="Brozerly"/>
<meta property="og:description" content="Gratuite et sans frais !. L'amitié est la meilleure des protections. Brozerly est ton application de crowdfunding pour les besoins personnels. La première application sociale d'entraide pour les besoins personnels.. Brozerly te permets de demander de l'aide à ton réseau d'amis afin que te amis puissent t'aider à remplacer ou acheter l'objet dont tu rêves. Crowdfunding app."/>
<meta property="og:locale" content="fr_FR"/>
<meta property="og:locale:alternate" content="fr_FR" />
<meta property="og:locale:alternate" content="eu_ES" />
<meta property="og:locale:alternate" content="en_GB" />
<meta property="og:image" content='https://www.brozerly.com/public/lang/fr/Landing.png'/>
<meta property="og:image" content='https://www.brozerly.com/public/lang/fr/phone_BrozerlyApp.png'/>
<meta property="og:rich_attachment" content="true"/>

<link href="https://fonts.googleapis.com/css?family=Fredoka+One|Pacifico" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:700,400,300,100" rel="stylesheet" type="text/css"/>
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:700,400, 300" rel="stylesheet" type="text/css"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css">

<link rel="stylesheet" href='/css/style.css' type="text/css">
<link rel="stylesheet" href='/css/index.css' type="text/css">
<link rel="stylesheet" href='/css/cookies.css' type="text/css">

brozerly

Brozerly

FAQ

Support

            FR - Français
            arrow_drop_down

        ES - Español

        FR - Français

        EU - Euskara

        EN - English

La première application sociale d'entraide pour les besoins personnels.

Gratuite et sans frais !

Brozerly te permets de demander de l'aide à ton réseau d'amis afin que te amis puissent t'aider à remplacer ou acheter l'objet dont tu rêves.

      
      Se connecter

L'amitié c'est pouvoir compter l'un sur l'autre.

    

1. Crée ton réseau d'amis

Crée ton réseau sur Brozerly, invite tes amis ou connecte-toi avec d'autres membres de la communauté.

    

2. Demande de l'aide à tes amis

Lance un SOS pour demander de l'aide, c'est toi qui décide si tu veux lancer un SOS public ou privé (réservé aux membres de ton réseau d'amis).

    

3. Echange

Echange des messages avec tes amis, réponds aux commentaires laissés sur tes objets ou SOS

      

4. Collecte

Les membres de ton réseau d'amis peuvent s'ils le souhaitent contribuer à tes SOS en te faisant un don que tu recevras sur ton compte bancaire.

    

Disponibilité

Brozerly est disponible sous IOD, Android et Web.

    

Confidentialité

Contrairement aux autres applications, Brozerly est totalement privé.

Paiements

      La sécurité des transactions est notre première préoccupation, nous avons choisi de faire confiance au leader des paiements électroniques Stripe.

Télécharger Brozerly maintenant.

      
      Se connecter

Nos Partenaires

Nous suivre.

Facebook

Twitter

Google +

Brozerly

Se connecter

Support

FAQ

Conditions d'utilisation.

Confidentialité

          FR - Français
          arrow_drop_down

© 2018 Brozerly

        ES - Español

        FR - Français

        EU - Euskara

        EN - English


text:
published: true
title: Simplicity
tags: simplicity mental-model
---
> Simplicity is prerequisite for reliability. - [Edsger Dijkstra](https://www.brainyquote.com/quotes/edsger_dijkstra_204332)

> Simplicity is the Ultimate Sophistication - [?](https://quoteinvestigator.com/2015/04/02/simple/)

- [Simple Made Easy](https://www.infoq.com/presentations/Simple-Made-Easy/) - [HN](https://news.ycombinator.com/item?id=23904300)


text:
@class NSString;

@interface UINavigationController (Delegate) <UINavigationControllerDelegate>
- (long long)positionForBar:(id)arg1;
- (void)navigationController:(id)arg1 didShowViewController:(id)arg2 animated:(_Bool)arg3;
- (void)navigationController:(id)arg1 willShowViewController:(id)arg2 animated:(_Bool)arg3;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end


text:
# Java I: Day 3
*(A link to these notes may be found at http://www.cs.utexas.edu/~nclement/aces/)*

## Intro

### Review last class: strings

### Goals for this class: static methods, variables

## What is Java

### Bytecode compiler -- translates high-level syntax to machine code

- Runs on a "virtual machine"

The virtual machine allows a single Java program to run on lots of different
underlying hardware architectures (e.g., phones, desktops, mainframes).

### Statically typed

All variables in a program have an associated type. Variables of different
types, in general, cannot be used interchangeably.

### Garbage-collected

Memory is managed for you by the virtual machine.

### Object-oriented

Code is grouped into logical "objects" that combine data with functions for
manipulating the data.

We won't talk much about this in this class; it's powerful but complicated!

## Program entry point: main

When a Java class is run as the "main" program, the following method is called:

```java
public static void main(String[] args) { ... }
```

## Comments

Use comments to annotate your code.

    /* everything between /* and */ is a comment */

    // everything from // to the end of the line is a comment

## Methods

Methods group together logical chunks of operations.

To define a method:

```java
public static void methodName() {
// ... put statements here, like System.out.println("hi");
}
```

To invoke or "call" a method:

    methodName();

### Important to have good names
```java
public static void c() { ... } // not so great

public static void printChorus() { ... } // better!
```

### Bottom-up way of defining methods

To define methods "bottom-up", think of your program as a long sequence of
commands to be executed. Then find repetition in the sequence, and replace
repeated chunks with methods.

### Top-down way of defining methods

To define methods "top-down", think of how your program "should" work and write
method calls. Then define those methods.

### Methods can call each other!

If there is a loop in a sequence of method calls, your program will run without
stopping, until it runs out of memory. This generates a Stack Overflow!

## Variables

A variable is a name for a place in the computer's memory.

In Java, a variable holds a specific type of information.

Java has several "primitive" ("built-in") types:

- `int` -- an integer value ("whole number": positive, zero, or negative)
- `double` -- a real ("decimal") value
- `String` -- a sequence of characters
- `boolean` -- true or false

Assigning the wrong type to a variable can produce an error!

### Steps for using

1. Declare the variable: `int x`
2. Assign a value to it: `x = 3`
3. Use it: `System.out.println(x)`

### Managing Types
Java can automatically convert between some types:
- Going from an `int` to a `double` is okay

However, going from some types is not okay

- What is the `int` version of 2.6? Is it 2? Is it 3?

Make sure you understand type conversion when doing simple arithmetic. For example, try the following:
```java
System.out.println(4/5);
System.out.println(4.0/5);
System.out.println(4/5*5);
```
## Order of operations (PEMDAS)

- Parentheses
- Exponents (not used in Java)
- Multiplication
- Division
- Addition
- Subtraction

## Homework

### Method Exercises

- https://practiceit.cs.washington.edu/problem/view/bjp3/chapter1/e9-Egg
- https://practiceit.cs.washington.edu/problem/view/bjp3/chapter1/e16-Shining
- https://practiceit.cs.washington.edu/problem/view/bjp3/chapter1/e13-StarFigures

### Variable Exercises

- https://practiceit.cs.washington.edu/problem/view/bjp3/chapter2/s2-expressions1
- https://practiceit.cs.washington.edu/problem/view/bjp3/chapter2/s3-expressions2
- https://practiceit.cs.washington.edu/problem/view/bjp3/chapter2/s4-expressions3

## More Info

- http://www.cs.utexas.edu/~scottm/cs312/handouts/slides/topic3staticMethods_StructuredProgramming.pdf
- http://www.cs.utexas.edu/~scottm/cs312/handouts/slides/topic4_expressions_and_variables.pdf
- https://learnjavathehardway.org/book/ex05.html
- https://learnjavathehardway.org/book/ex06.html
- https://learnjavathehardway.org/book/ex11.html


text:
// ------------------------------------------------------------------------------
//  <auto-generated>
//      This code was generated by SpecFlow (https://www.specflow.org/).
//      SpecFlow Version:3.7.0.0
//      SpecFlow Generator Version:3.7.0.0
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </auto-generated>
// ------------------------------------------------------------------------------
#region Designer generated code
#pragma warning disable
namespace PicklesDoc.Pickles.DocumentationBuilders.Markdown.AcceptanceTests.Features
{
    using TechTalk.SpecFlow;
    using System;
    using System.Linq;

    [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "3.7.0.0")]
    [System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [NUnit.Framework.TestFixtureAttribute()]
    [NUnit.Framework.DescriptionAttribute("Scenario Outlines")]
    public partial class ScenarioOutlinesFeature
    {

        private TechTalk.SpecFlow.ITestRunner testRunner;

        private string[] _featureTags = ((string[])(null));

#line 1 "Scenario Outline.feature"
#line hidden

        [NUnit.Framework.OneTimeSetUpAttribute()]
        public virtual void FeatureSetup()
        {
            testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner();
            TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Features", "Scenario Outlines", "    In order to document the Scenario Outlines\r\n    As a reader of the generated " +
                    "documentation\r\n    I want the scenario outlines to appear with steps and example" +
                    "s below the feature heading.", ProgrammingLanguage.CSharp, ((string[])(null)));
            testRunner.OnFeatureStart(featureInfo);
        }

        [NUnit.Framework.OneTimeTearDownAttribute()]
        public virtual void FeatureTearDown()
        {
            testRunner.OnFeatureEnd();
            testRunner = null;
        }

        [NUnit.Framework.SetUpAttribute()]
        public virtual void TestInitialize()
        {
        }

        [NUnit.Framework.TearDownAttribute()]
        public virtual void TestTearDown()
        {
            testRunner.OnScenarioEnd();
        }

        public virtual void ScenarioInitialize(TechTalk.SpecFlow.ScenarioInfo scenarioInfo)
        {
            testRunner.OnScenarioInitialize(scenarioInfo);
            testRunner.ScenarioContext.ScenarioContainer.RegisterInstanceAs<NUnit.Framework.TestContext>(NUnit.Framework.TestContext.CurrentContext);
        }

        public virtual void ScenarioStart()
        {
            testRunner.OnScenarioStart();
        }

        public virtual void ScenarioCleanup()
        {
            testRunner.CollectScenarioErrors();
        }

        [NUnit.Framework.TestAttribute()]
        [NUnit.Framework.DescriptionAttribute("Output has simple scenario outline")]
        public virtual void OutputHasSimpleScenarioOutline()
        {
            string[] tagsOfScenario = ((string[])(null));
            System.Collections.Specialized.OrderedDictionary argumentsOfScenario = new System.Collections.Specialized.OrderedDictionary();
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Output has simple scenario outline", null, tagsOfScenario, argumentsOfScenario, this._featureTags);
#line 6
this.ScenarioInitialize(scenarioInfo);
#line hidden
            bool isScenarioIgnored = default(bool);
            bool isFeatureIgnored = default(bool);
            if ((tagsOfScenario != null))
            {
                isScenarioIgnored = tagsOfScenario.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any();
            }
            if ((this._featureTags != null))
            {
                isFeatureIgnored = this._featureTags.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any();
            }
            if ((isScenarioIgnored || isFeatureIgnored))
            {
                testRunner.SkipScenario();
            }
            else
            {
                this.ScenarioStart();
#line 8
    testRunner.Given("I have a feature called \'My Scenario Outline Feature\'", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given ");
#line hidden
#line 10
    testRunner.And("I have a scenario outline called \'Scenario Outline with Single Example\'", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line hidden
                TechTalk.SpecFlow.Table table11 = new TechTalk.SpecFlow.Table(new string[] {
                            "Keyword",
                            "Step"});
                table11.AddRow(new string[] {
                            "Given",
                            "I have a simple given step for <data_one>"});
                table11.AddRow(new string[] {
                            "And",
                            "I have second given for <data_two>"});
#line 12
    testRunner.And("I have the scenario steps", ((string)(null)), table11, "And ");
#line hidden
                TechTalk.SpecFlow.Table table12 = new TechTalk.SpecFlow.Table(new string[] {
                            "Scenario",
                            "data_one",
                            "data_two"});
                table12.AddRow(new string[] {
                            "First",
                            "one",
                            "wun"});
                table12.AddRow(new string[] {
                            "Second",
                            "two",
                            "too"});
                table12.AddRow(new string[] {
                            "Third",
                            "three",
                            "tree"});
#line 17
    testRunner.And("I have an examples table", ((string)(null)), table12, "And ");
#line hidden
#line 23
    testRunner.When("I generate Markdown output", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
                TechTalk.SpecFlow.Table table13 = new TechTalk.SpecFlow.Table(new string[] {
                            "Content"});
                table13.AddRow(new string[] {
                            "#### Scenario Outline: Scenario Outline with Single Example"});
                table13.AddRow(new string[] {
                            ">"});
                table13.AddRow(new string[] {
                            "> **Given** I have a simple given step for \\<data_one\\>"});
                table13.AddRow(new string[] {
                            ">"});
                table13.AddRow(new string[] {
                            "> **And** I have second given for \\<data_two\\>"});
                table13.AddRow(new string[] {
                            ">"});
                table13.AddRow(new string[] {
                            "> Examples:"});
                table13.AddRow(new string[] {
                            ">"});
                table13.AddRow(new string[] {
                            "> | Scenario | data_one | data_two |"});
                table13.AddRow(new string[] {
                            "> | --- | --- | --- |"});
                table13.AddRow(new string[] {
                            "> | First | one | wun |"});
                table13.AddRow(new string[] {
                            "> | Second | two | too |"});
                table13.AddRow(new string[] {
                            "> | Third | three | tree |"});
#line 25
    testRunner.Then("the Markdown output has the lines in the following order", ((string)(null)), table13, "Then ");
#line hidden
            }
            this.ScenarioCleanup();
        }

        [NUnit.Framework.TestAttribute()]
        [NUnit.Framework.DescriptionAttribute("Output has table step scenario outline")]
        public virtual void OutputHasTableStepScenarioOutline()
        {
            string[] tagsOfScenario = ((string[])(null));
            System.Collections.Specialized.OrderedDictionary argumentsOfScenario = new System.Collections.Specialized.OrderedDictionary();
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Output has table step scenario outline", null, tagsOfScenario, argumentsOfScenario, this._featureTags);
#line 41
this.ScenarioInitialize(scenarioInfo);
#line hidden
            bool isScenarioIgnored = default(bool);
            bool isFeatureIgnored = default(bool);
            if ((tagsOfScenario != null))
            {
                isScenarioIgnored = tagsOfScenario.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any();
            }
            if ((this._featureTags != null))
            {
                isFeatureIgnored = this._featureTags.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any();
            }
            if ((isScenarioIgnored || isFeatureIgnored))
            {
                testRunner.SkipScenario();
            }
            else
            {
                this.ScenarioStart();
#line 43
    testRunner.Given("I have a feature called \'My Scenario Outline Feature\'", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given ");
#line hidden
#line 45
    testRunner.And("I have a scenario outline called \'Scenario Outline with table step\'", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line hidden
                TechTalk.SpecFlow.Table table14 = new TechTalk.SpecFlow.Table(new string[] {
                            "TableColA",
                            "TableColb"});
                table14.AddRow(new string[] {
                            "<data_one>",
                            "TDB1"});
                table14.AddRow(new string[] {
                            "TDA2",
                            "<data_two>"});
#line 47
    testRunner.And("I have the scenario step with table \'Given I have a table\'", ((string)(null)), table14, "And ");
#line hidden
                TechTalk.SpecFlow.Table table15 = new TechTalk.SpecFlow.Table(new string[] {
                            "Scenario",
                            "data_one",
                            "data_two"});
                table15.AddRow(new string[] {
                            "First",
                            "one",
                            "wun"});
                table15.AddRow(new string[] {
                            "Second",
                            "two",
                            "too"});
                table15.AddRow(new string[] {
                            "Third",
                            "three",
                            "tree"});
#line 52
    testRunner.And("I have an examples table", ((string)(null)), table15, "And ");
#line hidden
#line 58
    testRunner.When("I generate Markdown output", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line hidden
                TechTalk.SpecFlow.Table table16 = new TechTalk.SpecFlow.Table(new string[] {
                            "Content"});
                table16.AddRow(new string[] {
                            "#### Scenario Outline: Scenario Outline with table step"});
                table16.AddRow(new string[] {
                            ">"});
                table16.AddRow(new string[] {
                            "> **Given** I have a table"});
                table16.AddRow(new string[] {
                            ">"});
                table16.AddRow(new string[] {
                            "> | TableColA | TableColb |"});
                table16.AddRow(new string[] {
                            "> | --- | --- |"});
                table16.AddRow(new string[] {
                            "> | \\<data_one\\> | TDB1 |"});
                table16.AddRow(new string[] {
                            "> | TDA2 | \\<data_two\\> |"});
                table16.AddRow(new string[] {
                            ">"});
                table16.AddRow(new string[] {
                            "> Examples:"});
                table16.AddRow(new string[] {
                            ">"});
                table16.AddRow(new string[] {
                            "> | Scenario | data_one | data_two |"});
                table16.AddRow(new string[] {
                            "> | --- | --- | --- |"});
                table16.AddRow(new string[] {
                            "> | First | one | wun |"});
                table16.AddRow(new string[] {
                            "> | Second | two | too |"});
                table16.AddRow(new string[] {
                            "> | Third | three | tree |"});
#line 60
    testRunner.Then("the Markdown output has the lines in the following order", ((string)(null)), table16, "Then ");
#line hidden
            }
            this.ScenarioCleanup();
        }
    }
}
#pragma warning restore
#endregion


text:
/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
/*
 * Copyright (c) 1982, 1986, 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)uio.h	8.5 (Berkeley) 2/22/94
 */

#ifndef _SYS_UIO_H_
#define _SYS_UIO_H_

#include <sys/cdefs.h>
#include <sys/_types.h>

/*
 * [XSI] The ssize_t and size_t types shall be defined as described
 * in <sys/types.h>.
 */
#include <sys/_types/_size_t.h>
#include <sys/_types/_ssize_t.h>

/*
 * [XSI] Structure whose address is passed as the second parameter to the
 * readv() and writev() functions.
 */
#include <sys/_types/_iovec_t.h>

#if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE)
/*
 * IO direction for uio_t.
 *	UIO_READ - data moves into iovec(s) associated with uio_t
 *	UIO_WRITE - data moves out of iovec(s) associated with uio_t
 */
enum uio_rw { UIO_READ, UIO_WRITE };
#endif

__BEGIN_DECLS
ssize_t readv(int, const struct iovec *, int) __DARWIN_ALIAS_C(readv);
ssize_t writev(int, const struct iovec *, int) __DARWIN_ALIAS_C(writev);
__END_DECLS

#endif /* !_SYS_UIO_H_ */


text:
layout: post
title: 'Emotional Roller Coaster'
date: 2006-12-26 03:13
comments: true
categories : []
---

So yesterday was an emotional roller coaster. I got engaged yesterday morning and also found out later that afternoon that a good friend of mine from the VA Linux Systems days also got engaged. Then I hear that another ex-VA'er lost his grandmother and another ex-VA Engineer lost his battle with cancer.

I'm not really sure what else I can say.


text:
namespace PhoneXamlDirect3DApp1Comp
{

public enum class OCVFilterType
{
    ePreview,
    eGray,
    eCanny,
    eSepia,
    eNumOCVFilterTypes
};

public delegate void RequestAdditionalFrameHandler();
public delegate void RecreateSynchronizedTextureHandler();

[Windows::Foundation::Metadata::WebHostHidden]
public ref class Direct3DInterop sealed : public Windows::Phone::Input::Interop::IDrawingSurfaceManipulationHandler
{
public:
    Direct3DInterop();

    Windows::Phone::Graphics::Interop::IDrawingSurfaceContentProvider^ CreateContentProvider();

    // IDrawingSurfaceManipulationHandler
    virtual void SetManipulationHost(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ manipulationHost);

    event RequestAdditionalFrameHandler^ RequestAdditionalFrame;
    event RecreateSynchronizedTextureHandler^ RecreateSynchronizedTexture;

    property Windows::Foundation::Size WindowBounds;
    property Windows::Foundation::Size NativeResolution;
    property Windows::Foundation::Size RenderResolution
    {
        Windows::Foundation::Size get(){ return m_renderResolution; }
        void set(Windows::Foundation::Size renderResolution);
    }
    void CreateTexture(const Platform::Array<int>^ buffer, int with, int height, OCVFilterType filter);

protected:
    // Event Handlers
    void OnPointerPressed(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args);
    void OnPointerMoved(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args);
    void OnPointerReleased(Windows::Phone::Input::Interop::DrawingSurfaceManipulationHost^ sender, Windows::UI::Core::PointerEventArgs^ args);

internal:
    HRESULT STDMETHODCALLTYPE Connect(_In_ IDrawingSurfaceRuntimeHostNative* host);
    void STDMETHODCALLTYPE Disconnect();
    HRESULT STDMETHODCALLTYPE PrepareResources(_In_ const LARGE_INTEGER* presentTargetTime, _Out_ BOOL* contentDirty);
    HRESULT STDMETHODCALLTYPE GetTexture(_In_ const DrawingSurfaceSizeF* size, _Out_ IDrawingSurfaceSynchronizedTextureNative** synchronizedTexture, _Out_ DrawingSurfaceRectF* textureSubRectangle);
    ID3D11Texture2D* GetTexture();

private:
    CubeRenderer^ m_renderer;
    BasicTimer^ m_timer;
    Windows::Foundation::Size m_renderResolution;

    void ApplyGrayFilter(const cv::Mat& image);
    void ApplyCannyFilter(const cv::Mat& image);
    void ApplySepiaFilter(const cv::Mat& image);

    void UpdateImage(const cv::Mat& image);

    cv::Mat Lena;
    unsigned int frameWidth, frameHeight;
};

}


text:
from django.test import TestCase
from teams.models import Team,TeamManager
from django.core.exceptions import ValidationError, ObjectDoesNotExist

class TestTeamManager(TestCase):
    def setUp(self):
        self.team = Team()
        self.team.name = "firstTeam"

        self.valid_team_name = "TeamTeam-_0"
        self.valid_second_team_name = "SecondTeam"
        self.invalid_long_length_name = "a" * 65
        self.invalid_long_length_contact_number = "a" * 21
        self.invalid_long_length_team_url = "a" * 201

        self.team = Team.objects.create_team(
            name = self.valid_team_name
        )

        self.second_team = Team.objects.create_team(
            name = self.valid_second_team_name
        )

    def test_create_team_must_contain_name(self):
        self.assertraises(
            ValidationError,
            team = team.objects.create_team,
        )

    def test_create_team_must_contain_name(self):
        self.assertRaises(
            ValidationError,
            Team.objects.create_team,
            name = "",
        )
# Validation
    def test_team_name_is_restricted_to_64_characters(self):
        try:
            team = Team.objects.create_team(
                name = self.invalid_long_length_name
            )
        except ValidationError:
            pass

    def test_get_all_teams(self):
        teams = Team.objects.all()
        self.assertEqual(teams[0].name, self.team.name)
        self.assertEqual(teams[1].name, self.second_team.name)

    def test_more_than_64_letters_team_name_must_raise_validation_error(self):
        try:
            team = Team.objects.create_team(
                   name = self.invalid_long_length_name
                )
        except ValidationError:
            pass
        else:
            self.fail("More than 64 letters name should raise ValidationError")

    def test_more_than_20_digits_team_contact_number_must_raise_validation_error(self):
        try:
            team = Team.objects.create_team(
                name = self.valid_team_name,
                contact_number = self.invalid_long_length_contact_number
            )
        except ValidationError:
            pass
        else:
            self.fail("More than 20 digits phonenumber should raise ValidationError")

    def test_more_than_200_letters_team_website_url_must_raise_validation_error(self):
        try:
            team = Team.objects.create_team(
                name = self.valid_team_name,
                team_url = self.invalid_long_length_team_url
            )
        except ValidationError:
            pass
        else:
            self.fail("More than 200 letters website_url should raise ValidationError")

    # ObjectDoesNotExist
    def test_team_manager_could_delete_team(self):
        self.team.delete()
        try:
            Team.objects.get_team(id = self.team.id),
        except ObjectDoesNotExist:
            pass

    def test_get_team(self):
        self.assertIsNotNone(
            Team.objects.get_team(self.team.id),
        )

    def test_get_team_equal_to_team_targetted(self):
        get_team = Team.objects.get_team(self.team.id)
        self.assertEqual(
                self.team,
                get_team,
                "get_team  should be equal to target team",
        )


text:
import os
from setuptools import setup, find_packages

def read_file(path):
    with open(os.path.join(os.path.dirname(__file__), path), "r") as fobj:
        return fobj.read()

setup(
    name="starman",
    version="1.0.0",
    packages=find_packages(),

    install_requires=["future", "numpy"],

    author="Rich Wareham",
    author_email="rich.starman@richwareham.com",
    url="https://github.com/rjw57/starman",
    description="A library which implements algorithms of use when "
                "trying to track the true state of one or more systems over "
                "time in the presence of noisy observations.",
    long_description=read_file("README.rst"),
    classifiers=[
        "Development Status :: 4 - Beta",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Operating System :: POSIX",
        "Topic :: Scientific/Engineering",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
    ],
    license="MIT",
)


text:
#ifndef ALEXA_CLIENT_SDK_LIBIPCSERVERSAMPLEAPP_INCLUDE_IPCSERVERSAMPLEAPP_DOWNLOADMONITOR_H_
#define ALEXA_CLIENT_SDK_LIBIPCSERVERSAMPLEAPP_INCLUDE_IPCSERVERSAMPLEAPP_DOWNLOADMONITOR_H_

#include <APLClient/Telemetry/DownloadMetricsEmitter.h>

#include "IPCServerSampleApp/CachingDownloadManager.h"

namespace alexaClientSDK {
namespace sampleApplications {
namespace ipcServerSampleApp {

/**
 * Emits APL telemetry in response to download manager events.
 */
class DownloadMonitor : public CachingDownloadManager::Observer {
public:
    explicit DownloadMonitor(APLClient::Telemetry::DownloadMetricsEmitterPtr metricsEmitter);

    ~DownloadMonitor() override = default;

    void onDownloadStarted() override;

    void onDownloadComplete() override;

    void onDownloadFailed() override;

    void onCacheHit() override;

    void onBytesRead(uint64_t numberOfBytes) override;

private:
    APLClient::Telemetry::DownloadMetricsEmitterPtr m_metricsEmitter;
};

}  // namespace ipcServerSampleApp
}  // namespace sampleApplications
}  // namespace alexaClientSDK

#endif  // ALEXA_CLIENT_SDK_LIBIPCSERVERSAMPLEAPP_INCLUDE_IPCSERVERSAMPLEAPP_DOWNLOADMONITOR_H_


text:
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from django import http

from subhub import models

def _get_verify(verifies):
    for v in verifies:
        if v in ('sync', 'async'):
            return v
    raise KeyError('hub.verify is missing or not recognized')

@csrf_exempt
@require_POST
def hub(request):
    try:
        callback = request.POST['hub.callback']
        topic = request.POST['hub.topic']
        mode = request.POST['hub.mode']
        verify = _get_verify(request.POST.getlist('hub.verify'))
    except KeyError, e:
        return http.HttpResponseBadRequest(str(e))
    if mode not in dict(models.MODES):
        return http.HttpResponseBadRequest('Unknown hub.mode: %s' % mode)

    defaults = {
        'lease_seconds': (request.POST.get('hub.lease-seconds'), int),
        'secret': (request.POST.get('hub.secret'), str),
    }
    try:
        defaults = dict((k, c(v)) for k, (v, c) in defaults.items() if v is not None)
    except ValueError, e:
        return http.HttpResponseBadRequest(str(e))
    task, created = models.SubscriptionTask.objects.get_or_create(
        callback = callback,
        topic = topic,
        verify_token = request.POST.get('hub.verify_token', ''),
        mode = mode,
        defaults = defaults,
    )
    if verify == 'sync':
        result, description = task.verify()
        if result and description == 'verified':
            return http.HttpResponse('', status=204)
        else:
            return http.HttpResponseBadRequest('Verification failed: %s' % description)
    else:
        return http.HttpResponse('Subscription queued', status=202)


text:
require_relative 'abundance'

module BELParser
  module Language
    module Version1_0
      module ValueEncodings
        # ComplexAbundance value encoding.
        class ComplexAbundance < Abundance
          # Return the {Symbol} value.
          #
          # @note This method should be overridden in subclasses.
          def self.to_sym
            raise_not_implemented(__method__) if self != ComplexAbundance
            :C
          end
        end
      end
    end
  end
end


text:
import logging
import time
import sys

from os.path import join, dirname, realpath

l = logging.getLogger("angr.tests.test_dfg")
l.setLevel(logging.DEBUG)

import nose
import angr
import pyvex

test_location = str(join(dirname(realpath(__file__)), "../../binaries/tests"))

def perform_one(binary_path):
    proj = angr.Project(join(test_location, binary_path),
                        load_options={'auto_load_libs': False},
                        )
    start = time.time()
    cfg = proj.analyses.CFGAccurate(context_sensitivity_level=2)
    end = time.time()
    duration = end - start
    l.info("CFG generated in %f seconds.", duration)

    dfg = proj.analyses.DFG(cfg=cfg)
    nose.tools.assert_true(len(dfg.dfgs) <= len(cfg.nodes()))
    for addr, d in dfg.dfgs.items():
        nose.tools.assert_true(cfg.get_any_node(addr) is not None)
        # We check there is not node that we ignored
        for n in d.nodes():
            nose.tools.assert_not_equal(n.tag, 'Ist_IMark')
            nose.tools.assert_not_equal(n.tag, 'Ist_AbiHint')
            nose.tools.assert_not_equal(n.tag, 'Ist_Exit')
            if n.tag == 'Ist_Put':
                nose.tools.assert_not_equal(n.offset, proj.arch.ip_offset)

        for (a, b) in d.edges():
            if isinstance(a, pyvex.IRExpr.IRExpr):
                # We check that there is no edge between two expressions/const
                nose.tools.assert_false(isinstance(b, pyvex.IRExpr.IRExpr))

                # If there is an edge coming from an expr/const it should be in
                # the dependencies of the other node
                # FIXME
                # Impossible to check because of the Unop optimization in the
                # DFG...
                # nose.tools.assert_true(a in b.expressions)
            elif hasattr(a, 'tmp'):
                # If there is an edge between a tmp and another node
                # be sure that this tmp is in the dependencies of this node
                tmps = [ ]
                for e in b.expressions:
                    if hasattr(e, 'tmp'):
                        tmps.append(e.tmp)

                nose.tools.assert_true(a.tmp in tmps)

def test_dfg_isalnum():
    perform_one("i386/isalnum")

def test_dfg_counter():
    perform_one("i386/counter")

def test_dfg_cfg_0():
    perform_one("x86_64/cfg_0")

def test_dfg_fauxware():
    perform_one("mips/fauxware")

def run_all():
    functions = globals()
    all_functions = dict(filter((lambda (k, v): k.startswith('test_') and hasattr(v, '__call__')), functions.items()))
    for f in sorted(all_functions.keys()):
        all_functions[f]()

if __name__ == "__main__":
    logging.getLogger("angr.analyses.dfg").setLevel(logging.DEBUG)

    if len(sys.argv) > 1:
        globals()['test_' + sys.argv[1]]()
    else:
        run_all()


text:
package com.obsidian.compiler.ControlFlowGraph;

import com.obsidian.compiler.AbstractSyntaxTree.AsExpressionAstNode;
import com.obsidian.compiler.AbstractSyntaxTree.TypeAstNode;
import com.obsidian.compiler.Lava.LvEvalResult;
import com.obsidian.compiler.Lava.LvValue;
import com.obsidian.compiler.LvEvalEnvironment;
import com.obsidian.compiler.StaticCodeAnalyzer.StaticCodeAnalyzer;
import com.obsidian.compiler.StaticCodeAnalyzer.TypeChecker;
import com.obsidian.compiler.Types.Type;

import javax.json.stream.JsonGenerator;

/**
 * The "as" operation to cast types/objects.
 * Should objects be allowed to declare custom casting operations? I'm thinking no? But not dead set on that.
 * Could ultimately be made more efficient by allowing a destructive casting to take place.
 */

public class AsCfgNode extends ExpressionCfgNode {

	public ExpressionCfgNode operand;
	public TypeAstNode typeAstNode;
	public Type type;

	public AsCfgNode(StaticCodeAnalyzer sca, AsExpressionAstNode ast) {
		super();
		this.source = ast.getSource();
		this.operand = ExpressionCfgNode.fromAst(sca, ast.operand);
		this.typeAstNode = ast.type;
	}

	public AsCfgNode(ExpressionCfgNode operand, Type type) {
		super();
		this.operand = operand;
		this.type = type;
	}

	@Override
	public void writeJson(JsonGenerator generator) {

	}

	@Override
	public LvValue generateDeducedValue(LvEvalEnvironment lv) {
		if (this.type == null) {	// Type will be null if coming from user-code, non-null if the type was manually declared for internal-use
			this.type = Type.fromAst(lv, this.typeAstNode);
		}
		assert this.type != null;
		// TODO: Derive value if possible
		return LvValue.forType(this.type);
	}

	@Override
	public void analyze(LvEvalEnvironment lv) {
		// TODO: Is casting <value> to <type> even possible? If not throw a message
		super.analyze(lv);
	}

	@Override
	public IsPureCheckResult isPure(LvEvalEnvironment lv) {
		return new IsPureCheckResult();
	}

	@Override
	public boolean canAffectFlow() {
		return false;
	}

	@Override
	public LvEvalResult eval(LvEvalEnvironment lv) {
		LvEvalResult result = this.operand.eval(lv);
		if (result.unrollAction != null) {
			return result;
		}
		return new LvEvalResult(TypeChecker.cast(result.value, this.type));
	}

}


text:
<?php
/**
 * @Author: binghe
 * @Date:   2017-06-07 10:36:14
 * @Last Modified by:   binghe
 * @Last Modified time: 2017-06-17 11:35:29
 */
namespace Binghe\Wechat\Server;
use Binghe\Wechat\Core\Exceptions\FaultException;
use Binghe\Wechat\Core\Exceptions\InvalidArgumentException;
use Binghe\Wechat\Core\Exceptions\RuntimeException;
use Binghe\Wechat\Core\Exceptions\BadRequestException;
use Binghe\Wechat\Encryption\Encryptor;
use Binghe\Wechat\Support\Collection;
use Binghe\Wechat\Support\Log;
use Binghe\Wechat\Support\XML;
use Binghe\Wechat\Message\AbstractMessage;
use Binghe\Wechat\Message\Raw as RawMessage;
use Binghe\Wechat\Message\Text;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
*  Base server
*/
class BaseServer
{
    const SUCCESS_EMPTY_RESPONSE='success';
    /**
     * @var bool
     */
    protected $debug = false;
    /**
     * @var Request
     */
    protected $request;
    /**
     * @var string
     */
    protected $token;
    /**
     * @var Encryptor
     */
    protected $encryptor;

    /**
     * Constructor.
     *
     * @param string  $token
     * @param Request $request
     */
    public function __construct($token, Request $request = null)
    {
        $this->token = $token;
        $this->request = $request ?: Request::createFromGlobals();
    }
    public function debug($debug = true)
    {
        $this->debug = $debug;
    }
     /**
     * Validation request params.
     *
     * @param string $token
     *
     * @throws FaultException
     */
    public function validate($token)
    {
        $params = [
            $token,
            $this->request->get('timestamp'),
            $this->request->get('nonce'),
        ];

        if (!$this->debug && $this->request->get('signature') !== $this->signature($params)) {
            throw new FaultException('Invalid request signature.', 400);
        }
    }
    /**
     * Request getter.
     *
     * @return Request
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * Request setter.
     *
     * @param Request $request
     *
     * @return $this
     */
    public function setRequest(Request $request)
    {
        $this->request = $request;

        return $this;
    }
    /**
     * Set Encryptor.
     *
     * @param Encryptor $encryptor
     *
     * @return BaseServer
     */
    public function setEncryptor(Encryptor $encryptor)
    {
        $this->encryptor = $encryptor;

        return $this;
    }

    /**
     * Return the encryptor instance.
     *
     * @return Encryptor
     */
    public function getEncryptor()
    {
        return $this->encryptor;
    }
    /**
     * Build response.
     *
     * @param $to
     * @param $from
     * @param mixed $message
     *
     * @return string
     *
     * @throws \Binghe\Wechat\Core\Exceptions\InvalidArgumentException
     */
    protected function buildResponse($to, $from, $message)
    {
        if (empty($message) || $message === self::SUCCESS_EMPTY_RESPONSE) {
            return self::SUCCESS_EMPTY_RESPONSE;
        }

        if ($message instanceof RawMessage) {
            return $message->get('content', self::SUCCESS_EMPTY_RESPONSE);
        }

        if (is_string($message) || is_numeric($message)) {
            $message = new Text(['content' => $message]);
        }

        if (!$this->isMessage($message)) {
            $messageType = gettype($message);
            throw new InvalidArgumentException("Invalid Message type .'{$messageType}'");
        }

        $response = $this->buildReply($to, $from, $message);
        Log::debug($response);
        if ($this->isSafeMode()) {
            Log::debug('Message safe mode is enable.');
            $response = $this->encryptor->encryptMsg(
                $response,
                $this->request->get('nonce'),
                $this->request->get('timestamp')
            );
        }

        return $response;
    }
     /**
     * Whether response is message.
     *
     * @param mixed $message
     *
     * @return bool
     */
    protected function isMessage($message)
    {
        if (is_array($message)) {
            foreach ($message as $element) {
                if (!is_subclass_of($element, AbstractMessage::class)) {
                    return false;
                }
            }

            return true;
        }

        return is_subclass_of($message, AbstractMessage::class);
    }
    /**
     * Get request message.
     *
     * @return array
     *
     * @throws BadRequestException
     */
    public function getMessage()
    {
        $message = $this->parseMessageFromRequest($this->request->getContent(false));

        if (!is_array($message) || empty($message)) {
            throw new BadRequestException('Invalid request.');
        }

        return $message;
    }

    /**
     * Build reply XML.
     *
     * @param string          $to
     * @param string          $from
     * @param AbstractMessage $message
     *
     * @return string
     */
    protected function buildReply($to, $from, $message)
    {
        $base = [
            'ToUserName' => $to,
            'FromUserName' => $from,
            'CreateTime' => time(),
            'MsgType' => is_array($message) ? current($message)->getType() : $message->getType(),
        ];

        $transformer = new Transformer();

        return XML::build(array_merge($base, $transformer->transform($message)));
    }

    /**
     * Get signature.
     *
     * @param array $request
     *
     * @return string
     */
    protected function signature($request)
    {
        sort($request, SORT_STRING);

        return sha1(implode($request));
    }

    /**
     * Parse message array from raw php input.
     *
     * @param string|resource $content
     *
     * @throws \Binghe\Wechat\Core\Exceptions\RuntimeException
     * @throws \Binghe\Wechat\Encryption\EncryptionException
     *
     * @return array
     */
    protected function parseMessageFromRequest($content)
    {
        $content = strval($content);

        $arrayable = json_decode($content, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return $arrayable;
        }

        if ($this->isSafeMode()) {
            if (!$this->encryptor) {
                throw new RuntimeException('Safe mode Encryptor is necessary, please use BaseServer::setEncryptor(Encryptor $encryptor) set the encryptor instance.');
            }

            $message = $this->encryptor->decryptMsg(
                $this->request->get('msg_signature'),
                $this->request->get('nonce'),
                $this->request->get('timestamp'),
                $content
            );
        } else {
            $message = XML::parse($content);
        }

        return $message;
    }

    /**
     * Check the request message safe mode.
     *
     * @return bool
     */
    private function isSafeMode()
    {
        return $this->request->get('encrypt_type') && $this->request->get('encrypt_type') === 'aes';
    }

}


text:
<?php

function bodyClass() {
    $body_classes = array();
    $class = "";
    foreach ( \Request::segments() as $segment )
    {
        if ( is_numeric( $segment ) || empty( $segment ) ) {
            continue;
        }
        $class .= ! empty( $class ) ? "-" . $segment : $segment;
        array_push( $body_classes, $class );
    }
    return ! empty( $body_classes ) ? implode( ' ', $body_classes ) : NULL;
}


text:
using System;
using Azure.Core;

namespace Azure.Communication.Chat
{
    [CodeGenModel("ChatMessage")]
    public partial class ChatMessage
    {
        internal ChatMessage(string id, string type, ChatMessagePriority? priority, string version, string content, string senderDisplayName, DateTimeOffset? createdOn, string senderId, DateTimeOffset? deletedOn, DateTimeOffset? editedOn)
        {
            Id = id;
            Type = type;
            Priority = priority;
            Version = version;
            Content = content;
            SenderDisplayName = senderDisplayName;
            CreatedOn = createdOn;
            SenderId = senderId;
            DeletedOn = deletedOn;
            EditedOn = editedOn;
            Sender = new CommunicationUser(senderId);
        }

        /// <summary>
        /// The <see cref="CommunicationUser" /> for the message.
        /// </summary>
        public CommunicationUser Sender { get; }
        internal string SenderId { get; }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 56: 41 (1995)

#### Original name
Lambertella torquata W.Y. Zhuang

### Remarks
null


text:
date: 2015-11-20T01:46:33-06:00
description: "Arrested DevOps is a podcast focusing on trends in the DevOps space"
license: "apache2"
licenseLink: "https://github.com/arresteddevops/ado-hugo/blob/master/LICENSE.md"
sitelink: https://www.arresteddevops.com/
sourceLink: https://github.com/arresteddevops/ado-hugo
tags:
- podcast
- bootstrap
thumbnail: /img/arresteddevops-tn.png
title: arresteddevops
---


text:
import sys

def main():
	sum_integers = 0
	file = open(sys.argv[1], 'r')
	numbers = file.read()
	numbers = numbers.split(" ")

	for number in numbers:
		number = int(number)
		sum_integers += number

	file.close()
	print(sum_integers)

if __name__ == "__main__":
	main()