text:
brew install caskroom/cask/brew-cask
brew tap caskroom/versions

# daily
brew cask install alfred
brew cask install dropbox
brew cask install gyazo
brew cask install nvalt
# brew cask install onepassword
# brew cask install rescuetime
brew cask install sizeup
# cask install flux

# dev
brew cask install cyberduck
# brew cask install filezilla
brew cask install iterm2
brew cask install imagealpha
brew cask install imageoptim
brew cask install mysqlworkbench
brew cask install sourcetree
brew cask install sublime-text3
# brew cask install virtualbox

# fun
# brew cask install limechat
brew cask install miro-video-converter
# brew cask install spotify

# browsers
brew cask install firefox
brew cask install google-chrome
brew cask install google-chrome-canary
# brew cask install firefox-nightly --force
# brew cask install webkit-nightly --force
# brew cask install chromium --force
# brew cask install torbrowser

# less often
brew cask install disk-inventory-x
brew cask install the-unarchiver
brew cask install ccleaner
# brew cask install transmission
brew cask install vlc


text:
<?xml version="1.0" encoding="UTF-8"?>
<SageTVPlugin>

	<Name>Name Timed Recording</Name>

  	<Identifier>NameTimedRecording</Identifier>

  	<Description>This plugin allows you to give a user friendly name to timed recordings instead of the default "Timed Record" name used by SageTV.</Description>

  	<Author>tmiranda</Author>

  	<CreationDate>2011.04.15</CreationDate>

  	<ModificationDate>2021.05.16</ModificationDate>

  	<Version beta="false">1.36.1</Version>

  	<Desktop>false</Desktop>

  	<Webpage>http://forums.sagetv.com/forums/showthread.php?p=500052#post500052</Webpage>

  	<Dependency>

		<STV>SageTV7</STV>

      	<MinVersion>7.1</MinVersion>

  	</Dependency>

      <Dependency>

        <Plugin>NameTimedRecordingGeneral</Plugin>

        <MinVersion>1.30</MinVersion>

      </Dependency>

  	<PluginType>STVI</PluginType>

  	<Package>

      <PackageType>STVI</PackageType>

      <Location>https://github.com/OpenSageTV/sagetv-plugin-repo/releases/download/1/NameTimedRecording-1.30.zip</Location>

      <MD5>9F2ADF10DFD973EBF13ABB071DE160ED</MD5>

  	</Package>

  	<STVImport>NameTimedRecording.stvi</STVImport>

  	<ReleaseNotes>
- Move to V9 repository

Version 1.36:

- Moved hosting to BinTray. No change in functionality.

Version 1.30:

- NOTE: If you are upgrading from a previous version all of the names for existing timed recordings will be lost.

- Fixed bug that would occur if two timed recordings with the same recurrence happened on the same channel.

- Added ability to edit the names of existing timed recordings and manual recordings.

- Improved dialog that displays suggested names.

- Added logging.

- Known Issue: Will not work properly for languages other than English.

Version 1.25: (forum release)

- Fixed bug that would cause naming error if two Timed Recordings were scheduled for the same time.

- Added check to make sure plugin is installed on Sage server as well as SageClient.

Version 1.20:

- Fix bug that caused all but the first occurance of a recurring recording to default back to "Timed Record".

- Add ability to choose a name from airings in the guide.

- Change status to beta.

Version 1.10:

- Add option to change the name.

- Add General Plugin to automatically add name to MediaFile metadata when the recording ends.

- Store the default Timed Record name in a property so it can be altered for languages other than English.

- Add small delay after Manual Recording is created to make sure the Airing is available.

- Fix bug that occured with recurring timed recordings.

Version 1.00:

- First release.

  </ReleaseNotes>

</SageTVPlugin>

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "3rd_party/yaml-cpp/yaml.h"
#include "common/io_item.h"

#include <string>
#include <vector>

// interface for handling model files in marian, both *.npz files and
// *.bin files have the same way of accessing them and are identified
// by suffixes (*.npz or *.bin).

// Files with the *.bin suffix are supposed to be memory-mappable for
// CPU decoding.

namespace marian {
namespace io {

bool isNpz(const std::string& fileName);
bool isBin(const std::string& fileName);

void getYamlFromModel(YAML::Node& yaml, const std::string& varName, const std::string& fileName);
void getYamlFromModel(YAML::Node& yaml, const std::string& varName, const void* ptr);

void addMetaToItems(const std::string& meta,
                    const std::string& varName,
                    std::vector<io::Item>& items);

std::vector<Item> loadItems(const std::string& fileName);
std::vector<Item> loadItems(const void* ptr);

std::vector<Item> mmapItems(const void* ptr);

void saveItems(const std::string& fileName, const std::vector<Item>& items);

/**
 * Creates a flat io::Item from a given std::vector so that it can be saved in a npz file
 * or Marian's native binary format with the given name.
 */
template <typename T>
Item fromVector(const std::vector<T>& vec, const std::string& name) {
  Item item;
  item.name = std::move(name);
  item.shape = Shape({1, (int)vec.size()}); // @TODO: review if this should be {1, size} or rather just {size}
  item.type = typeId<T>();
  item.bytes.resize(vec.size() * sizeOf(item.type));
  std::copy((char*)vec.data(), (char*)(vec.data() + vec.size()), item.bytes.begin());
  return item;
}

}  // namespace io
}  // namespace marian


text:
require 'rodakase/container'

module Main
  class Container < Rodakase::Container
    configure do |config|
      config.root = Pathname(__FILE__).join('../..').realpath.dirname.freeze
      config.auto_register = 'lib'
    end

    require root.join('../../shared/persistence').to_s

    import Persistence::Container

    load_paths!('lib')
  end
end


text:
//
//  GTLBigqueryProjectList.h
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   BigQuery API (bigquery/v2)
// Description:
//   A data platform for customers to create, manage, share and query data.
// Documentation:
//   https://cloud.google.com/bigquery/
// Classes:
//   GTLBigqueryProjectList (0 custom class methods, 5 custom properties)
//   GTLBigqueryProjectListProjectsItem (0 custom class methods, 5 custom properties)

#if GTL_BUILT_AS_FRAMEWORK
  #import "GTL/GTLObject.h"
#else
  #import "GTLObject.h"
#endif

@class GTLBigqueryProjectListProjectsItem;
@class GTLBigqueryProjectReference;

// ----------------------------------------------------------------------------
//
//   GTLBigqueryProjectList
//

@interface GTLBigqueryProjectList : GTLObject

// A hash of the page of results
@property (nonatomic, copy) NSString *ETag;

// The type of list.
@property (nonatomic, copy) NSString *kind;

// A token to request the next page of results.
@property (nonatomic, copy) NSString *nextPageToken;

// Projects to which you have at least READ access.
@property (nonatomic, retain) NSArray *projects;  // of GTLBigqueryProjectListProjectsItem

// The total number of projects in the list.
@property (nonatomic, retain) NSNumber *totalItems;  // intValue

@end

// ----------------------------------------------------------------------------
//
//   GTLBigqueryProjectListProjectsItem
//

@interface GTLBigqueryProjectListProjectsItem : GTLObject

// A descriptive name for this project.
@property (nonatomic, copy) NSString *friendlyName;

// An opaque ID of this project.
// identifier property maps to 'id' in JSON (to avoid Objective C's 'id').
@property (nonatomic, copy) NSString *identifier;

// The resource type.
@property (nonatomic, copy) NSString *kind;

// The numeric ID of this project.
@property (nonatomic, retain) NSNumber *numericId;  // unsignedLongLongValue

// A unique reference to this project.
@property (nonatomic, retain) GTLBigqueryProjectReference *projectReference;

@end


text:
module ServerEngine

  IS_WINDOWS = /mswin|mingw/ === RUBY_PLATFORM
  private_constant :IS_WINDOWS

  def self.windows?
    IS_WINDOWS
  end

  module ClassMethods
    def dump_uncaught_error(e)
      STDERR.write "Unexpected error #{e}\n"
      e.backtrace.each {|bt|
        STDERR.write "  #{bt}\n"
      }
      nil
    end

    def format_signal_name(n)
      Signal.list.each_pair {|k,v|
        return "SIG#{k}" if n == v
      }
      return n
    end

    def format_join_status(code)
      case code
      when Process::Status
        if code.signaled?
          "signal #{format_signal_name(code.termsig)}"
        else
          "status #{code.exitstatus}"
        end
      when Exception
        "exception #{code}"
      when nil
        "unknown reason"
      end
    end

  end

  extend ClassMethods

end


text:
import django
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from .models import ThreadedComment
from .compat import CommentForm

class ThreadedCommentForm(CommentForm):
    title = forms.CharField(label=_('Title'), required=False, max_length=getattr(settings, 'COMMENTS_TITLE_MAX_LENGTH', 255))
    parent = forms.IntegerField(required=False, widget=forms.HiddenInput)

    def __init__(self, target_object, parent=None, data=None, initial=None):
        if django.VERSION >= (1,7):
            # Using collections.OrderedDict from Python 2.7+
            # This class does not have an insert method, have to replace it.
            from collections import OrderedDict
            keys = list(self.base_fields.keys())
            keys.remove('title')
            keys.insert(keys.index('comment'), 'title')

            self.base_fields = OrderedDict((k, self.base_fields[k]) for k in keys)
        else:
            self.base_fields.insert(
                self.base_fields.keyOrder.index('comment'), 'title',
                self.base_fields.pop('title')
            )
        self.parent = parent
        if initial is None:
            initial = {}
        initial.update({'parent': self.parent})
        super(ThreadedCommentForm, self).__init__(target_object, data=data, initial=initial)

    def get_comment_model(self):
        return ThreadedComment

    def get_comment_create_data(self):
        d = super(ThreadedCommentForm, self).get_comment_create_data()
        d['parent_id'] = self.cleaned_data['parent']
        d['title'] = self.cleaned_data['title']
        return d


text:
package org.ihtsdo.buildcloud.config;

import org.ihtsdo.buildcloud.TestConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestConfig.class)
public class DailyBuildResourceConfigTest {

	@Autowired
	private DailyBuildResourceConfig dailyBuildResourceConfig;

	@Test
	public void testUseCloud() {
		assertNotNull(dailyBuildResourceConfig);
		assertFalse(dailyBuildResourceConfig.isUseCloud());
	}

	@Test
	public void testGetCloud() {
		assertNotNull(dailyBuildResourceConfig);
		assertTrue(dailyBuildResourceConfig.getCloud().getBucketName().isEmpty());
	}
	@Test
	public void testGetLocalPath() {
		assertNotNull(dailyBuildResourceConfig);
		assertEquals("store/local/", dailyBuildResourceConfig.getLocal().getPath());
	}
}


text:
#login-header-bar {
  -webkit-padding-start: 15px;
  border-bottom: 3px solid black;
  bottom: 0;
  left: 0;
  padding-bottom: 7px;
  position: absolute;
  right: 0;
}

#login-header-bar {
  /* Using copy of Ash launcher background with 0.8 opacity applied to it.
     Otherwise if opacity: 0.8 is set here it will affect button text as well.
     Have to position background differently so that opacity is not applied
     to child elements. */
  background-image: url(chrome://theme/IDR_LAUNCHER_BACKGROUND);
  padding-top: 7px;
}

html[screen=lock] .login-header-bar-hidden,
html[screen=oobe] .login-header-bar-hidden {
  opacity: 0;
}

html[screen=lock] .login-header-bar-animate-fast,
html[screen=oobe] .login-header-bar-animate-fast {
  -webkit-transition: opacity 200ms ease-out;
}

html[screen=lock] .login-header-bar-animate-slow,
html[screen=oobe] .login-header-bar-animate-slow {
  -webkit-transition: opacity 2s ease-out;
}

#login-header-bar button,
#login-header-bar button:active,
#login-header-bar button:focus,
#login-header-bar button:hover {
  background: transparent none;
  box-shadow: none;
  cursor: pointer;
  height: 34px;
  margin: 0;
  min-width: 0;
  opacity: 0.6;
  padding: 5px 8px;
  vertical-align: middle;
}

#login-header-bar button:not(.button-restricted),
#login-header-bar button:active:not(.button-restricted),
#login-header-bar button:focus:not(.button-restricted),
#login-header-bar button:hover:not(.button-restricted) {
  color: white !important;
  opacity: 1 !important;
}

.header-bar-item {
  display: inline-block;
  height: 34px;
}

.add-supervised-user-menu {
  display: none;
}

#more-settings-header-bar-item.active button.add-supervised-user-menu {
  background-color: white;
  border: 1px solid lightgray;
  border-radius: 2px;
  bottom: 15px;
  color: black !important;
  display: block;
  font-size: 13px;
  height: auto;
  left: 15px;
  margin: 0 0 -10px -10px;
  min-height: 34px;
  position: absolute;
  text-align: center;
  width: 180px;
}

html[dir=rtl] #more-settings-header-bar-item.active
                button.add-supervised-user-menu {
  right: 0;
}

html[dir=rtl] .header-bar-item {
  background-position: right center;
}

#login-header-bar #shutdown-button,
#login-header-bar #restart-button,
#login-header-bar #add-user-button,
#login-header-bar #guest-user-button,
#login-header-bar #more-settings-button,
#login-header-bar #cancel-multiple-sign-in-button {
  -webkit-padding-start: 24px;
  background-position: left center;
  background-repeat: no-repeat;
  background-size: 24px;
}

html[dir=rtl] #login-header-bar #shutdown-button,
html[dir=rtl] #login-header-bar #restart-button,
html[dir=rtl] #login-header-bar #add-user-button,
html[dir=rtl] #login-header-bar #more-settings-button,
html[dir=rtl] #login-header-bar #guest-user-button,
html[dir=rtl] #login-header-bar #cancel-multiple-sign-in-button {
  background-position: right center;
}

#login-header-bar #more-settings-header-bar-item {
  position: relative;
}

#login-header-bar #shutdown-button {
  background-image: url(chrome://theme/IDR_ICON_POWER_WHITE);
}

#login-header-bar #restart-button {
  background-image: url(chrome://theme/IDR_ICON_POWER_WHITE);
}

#login-header-bar #add-user-button {
  background-image: url(chrome://theme/IDR_ICON_ADD_USER_WHITE);
}

#login-header-bar #more-settings-button {
  background-image: url(chrome://theme/IDR_ICON_MORE_VERT_WHITE);
}

#login-header-bar #guest-user-button {
  background-image: url(chrome://theme/IDR_ICON_GUEST_WHITE);
}

#login-header-bar #cancel-multiple-sign-in-button {
  /* TODO(dzhioev): replace with appropriate image when possible. */
  background-image: url(chrome://theme/IDR_PANEL_CLOSE);
}

.button-restricted {
  border: 1px solid transparent;
  color: white !important;
  opacity: 0.4 !important;
}


text:
//******************************************************************************************************
//  SortedPointBuffer`2.cs - Gbtc
//
//  Copyright © 2014, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
//  not use this file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  02/05/2014 - Steven E. Chisholm
//       Generated original version of source code.
//  11/27/2014 - J. Ritchie Carroll
//       Added duplicated key handling for derived classes.
//
//******************************************************************************************************

using System;
using GSF.Snap.Tree;

namespace GSF.Snap.Collection
{
    /// <summary>
    /// A temporary point buffer that is designed to write unsorted data to it,
    /// then read the data back out sorted.
    /// </summary>
    /// <typeparam name="TKey">The key type to use</typeparam>
    /// <typeparam name="TValue">The value type to use</typeparam>
    /// <remarks>
    /// This class is not thread safe.
    /// </remarks>
    public class SortedPointBuffer<TKey, TValue>
        : TreeStream<TKey, TValue>
        where TKey : SnapTypeBase<TKey>, new()
        where TValue : SnapTypeBase<TValue>, new()
    {
        private readonly KeyValueMethods<TKey, TValue> m_methods;

        /// <summary>
        /// Contains indexes of sorted data.
        /// </summary>
        private int[] m_sortingBlocks1;
        /// <summary>
        /// Contains indexes of sorted data.
        /// </summary>
        /// <remarks>
        /// Two blocks are needed to do a merge sort since
        /// this class uses indexes instead of actually moving
        /// the raw values.
        /// </remarks>
        private int[] m_sortingBlocks2;

        /// <summary>
        /// A block of data for storing the keys.
        /// </summary>
        private TKey[] m_keyData;
        /// <summary>
        /// A block of data for storing the values.
        /// </summary>
        private TValue[] m_valueData;

        /// <summary>
        /// The maximum number of items that can be stored in this buffer.
        /// </summary>
        private int m_capacity;
        /// <summary>
        /// The index of the next point to dequeue.
        /// </summary>
        private int m_dequeueIndex;
        /// <summary>
        /// The index of the next point to write.
        /// </summary>
        private int m_enqueueIndex;
        /// <summary>
        /// Gets if the stream is currently reading.
        /// The stream was not designed to be read from and written to at the same time. So the mode must be changed.
        /// </summary>
        private bool m_isReadingMode;

        private readonly bool m_removeDuplicates;

        private readonly Action<TKey, TKey> m_duplicateHandler;

        /// <summary>
        /// Creates a <see cref="SortedPointBuffer{TKey,TValue}"/> that can hold only exactly the specified <see cref="capacity"/>.
        /// </summary>
        /// <param name="capacity">The maximum number of items that can be stored in this class</param>
        /// <param name="removeDuplicates">specifies if the point buffer should remove duplicate key values upon reading.</param>
        public SortedPointBuffer(int capacity, bool removeDuplicates)
        {
            m_methods = Library.GetKeyValueMethods<TKey, TValue>();
            m_removeDuplicates = removeDuplicates;
            SetCapacity(capacity);
            m_isReadingMode = false;
        }

        /// <summary>
        /// Creates a <see cref="SortedPointBuffer{TKey,TValue}"/> that can hold only exactly the specified <see cref="capacity"/>
        /// using the specified duplicate handler.
        /// </summary>
        /// <param name="capacity">The maximum number of items that can be stored in this class</param>
        /// <param name="duplicateHandler">Function that will handle encountered duplicates.</param>
        protected SortedPointBuffer(int capacity, Action<TKey, TKey> duplicateHandler)
            : this(capacity, duplicateHandler is null)
        {
            m_duplicateHandler = duplicateHandler;
        }

        /// <summary>
        /// Gets if the stream will never return duplicate keys. Do not return true unless it is Guaranteed that
        /// the data read from this stream will never contain duplicates.
        /// </summary>
        public override bool NeverContainsDuplicates => m_removeDuplicates || (object)m_duplicateHandler != null;

        /// <summary>
        /// Gets if the stream is always in sequential order. Do not return true unless it is Guaranteed that
        /// the data read from this stream is sequential.
        /// </summary>
        public override bool IsAlwaysSequential => true;

        /// <summary>
        /// Gets the current number of items in the buffer
        /// </summary>
        public int Count => m_enqueueIndex - m_dequeueIndex;

        /// <summary>
        /// Gets if this buffer is empty
        /// </summary>
        public bool IsEmpty => m_dequeueIndex == m_enqueueIndex;

        /// <summary>
        /// Gets if no more items can be added to this list.
        /// List must be cleared before any more items can be added.
        /// </summary>
        public bool IsFull => m_capacity == m_enqueueIndex;

        /// <summary>
        /// Gets/Sets the current mode of the point buffer.
        /// </summary>
        /// <remarks>
        /// This class is not designed to be read from and written to at the same time.
        /// This is because sorting must occur right before reading from this stream.
        /// </remarks>
        public bool IsReadingMode
        {
            get => m_isReadingMode;
            set
            {
                if (m_isReadingMode != value)
                {
                    m_isReadingMode = value;
                    if (m_isReadingMode)
                    {
                        Sort();
                        if (m_removeDuplicates)
                            RemoveDuplicates();
                        else
                            HandleDuplicates();
                    }
                    else
                    {
                        Clear();
                    }
                }
            }
        }

        private void SetCapacity(int capacity)
        {
            if (capacity <= 0)
                throw new ArgumentOutOfRangeException("capacity", "must be greater than 0");

            m_capacity = capacity;
            m_sortingBlocks1 = new int[capacity];
            m_sortingBlocks2 = new int[capacity];
            m_keyData = new TKey[capacity];
            for (int x = 0; x < capacity; x++)
            {
                m_keyData[x] = new TKey();
            }

            m_valueData = new TValue[capacity];
            for (int x = 0; x < capacity; x++)
            {
                m_valueData[x] = new TValue();
            }
        }

        /// <summary>
        /// Clears all of the items in this list.
        /// </summary>
        private void Clear()
        {
            m_dequeueIndex = 0;
            m_enqueueIndex = 0;
            SetEos(false);
        }

        /// <summary>
        /// Attempts to enqueue the provided item to the list.
        /// </summary>
        /// <param name="key">the key to add</param>
        /// <param name="value">the value to add</param>
        /// <returns>true if the item was successfully enqueued. False if the queue is full.</returns>
        /// <exception cref="InvalidOperationException">Occurs if <see cref="IsReadingMode"/> is set to true</exception>
        public bool TryEnqueue(TKey key, TValue value)
        {
            if (m_isReadingMode)
                throw new InvalidOperationException("Cannot enqueue to a list that is in ReadMode");
            if (IsFull)
                return false;
            m_methods.Copy(key, value, m_keyData[m_enqueueIndex], m_valueData[m_enqueueIndex]);
            m_enqueueIndex++;
            return true;
        }

        /// <summary>
        /// Advances the stream to the next value.
        /// If before the beginning of the stream, advances to the first value
        /// </summary>
        /// <returns>True if the advance was successful. False if the end of the stream was reached.</returns>
        /// <exception cref="InvalidOperationException">Occurs if <see cref="IsReadingMode"/> is set to false</exception>
        protected override bool ReadNext(TKey key, TValue value)
        {
            if (!m_isReadingMode)
                throw new InvalidOperationException("Cannot read from a list that is not in ReadMode");
            if (IsEmpty)
                return false;

            //Since this class is fixed in size. Bounds checks are not necessary as they will always be valid.
            int index = m_sortingBlocks1[m_dequeueIndex];
            m_methods.Copy(m_keyData[index], m_valueData[index], key, value);

            m_dequeueIndex++;
            return true;
        }

        /// <summary>
        /// Overrides the default behavior that disposes the stream when the end of the stream has been encountered.
        /// </summary>
        protected override void EndOfStreamReached()
        {
            SetEos(true);
        }

        /// <summary>
        /// Reads the specified item from the sorted list.
        /// </summary>
        /// <param name="index">the index of the item to read. Note: Bounds checking is not done.</param>
        /// <param name="key">the key to write to</param>
        /// <param name="value">the value to write to</param>
        internal void ReadSorted(int index, TKey key, TValue value)
        {
            if (!m_isReadingMode)
                throw new InvalidOperationException("Cannot read from a list that is not in ReadMode");
            //Since this class is fixed in size. Bounds checks are not necessary as they will always be valid.
            m_keyData[m_sortingBlocks1[index]].CopyTo(key);
            m_valueData[m_sortingBlocks1[index]].CopyTo(value);
        }

        /// <summary>
        /// Does a sort of the data. using a merge sort like algorithm.
        /// </summary>
        private unsafe void Sort()
        {
            //InitialSort
            int count = Count;

            for (int x = 0; x < count; x += 2)
            {
                //Can't sort the last entry if not
                if (x + 1 == count)
                {
                    m_sortingBlocks1[x] = x;
                }
                else if (m_keyData[x].IsLessThanOrEqualTo(m_keyData[x + 1]))
                {
                    m_sortingBlocks1[x] = x;
                    m_sortingBlocks1[x + 1] = x + 1;
                }
                else
                {
                    m_sortingBlocks1[x] = x + 1;
                    m_sortingBlocks1[x + 1] = x;
                }
            }

            bool shouldSwap = false;

            fixed (int* block1 = m_sortingBlocks1, block2 = m_sortingBlocks2)
            {
                int stride = 2;
                while (true)
                {
                    if (stride >= count)
                        break;

                    shouldSwap = true;
                    SortLevel(block1, block2, m_keyData, count, stride);
                    stride *= 2;

                    if (stride >= count)
                        break;

                    shouldSwap = false;
                    SortLevel(block2, block1, m_keyData, count, stride);
                    stride *= 2;
                }
            }

            if (shouldSwap)
            {
                int[] b1 = m_sortingBlocks1;
                m_sortingBlocks1 = m_sortingBlocks2;
                m_sortingBlocks2 = b1;
            }
        }

        /// <summary>
        /// Does a merge sort on the provided level.
        /// </summary>
        /// <param name="srcIndex">where the current indexes exist</param>
        /// <param name="dstIndex">where the final indexes should go</param>
        /// <param name="ptr">the data</param>
        /// <param name="count">the number of entries at this level</param>
        /// <param name="stride">the number of compares per level</param>
        private unsafe void SortLevel(int* srcIndex, int* dstIndex, TKey[] ptr, int count, int stride)
        {
            for (int xStart = 0; xStart < count; xStart += stride + stride)
            {
                int d = xStart;
                int dEnd = Math.Min(xStart + stride + stride, count);
                int i1 = xStart;
                int i1End = Math.Min(xStart + stride, count);
                int i2 = Math.Min(xStart + stride, count);
                int i2End = Math.Min(xStart + stride + stride, count);

                if (d != dEnd && i1 != i1End && i2 != i2End)
                {
                    //Check to see if already in order, then I can shortcut
                    if (ptr[srcIndex[i1End - 1]].IsLessThanOrEqualTo(ptr[srcIndex[i2]]))
                    {
                        for (int i = d; i < dEnd; i++)
                        {
                            dstIndex[i] = srcIndex[i];
                        }
                        continue;
                    }
                }

                while (d < dEnd)
                {
                    if (i1 == i1End)
                    {
                        dstIndex[d] = srcIndex[i2];
                        d++;
                        i2++;
                    }
                    else if (i2 == i2End)
                    {
                        dstIndex[d] = srcIndex[i1];
                        d++;
                        i1++;
                    }
                    else if (ptr[srcIndex[i1]].IsLessThanOrEqualTo(ptr[srcIndex[i2]]))
                    {
                        dstIndex[d] = srcIndex[i1];
                        d++;
                        i1++;
                    }
                    else
                    {
                        dstIndex[d] = srcIndex[i2];
                        d++;
                        i2++;
                    }
                }
            }
        }

        private void RemoveDuplicates()
        {
            int skipCount = 0;
            for (int x = 0; x < m_enqueueIndex - 1; x++)
            {
                if (skipCount > 0)
                    m_sortingBlocks1[x - skipCount] = m_sortingBlocks1[x];

                if (m_keyData[m_sortingBlocks1[x - skipCount]].IsEqualTo(m_keyData[m_sortingBlocks1[x + 1]]))
                {
                    skipCount++;
                }
            }

            m_enqueueIndex -= skipCount;
        }

        private void HandleDuplicates()
        {
            if (m_duplicateHandler is null)
                return;

            TKey left, right;
            bool keysManipulated = false;

            // Handle any encountered duplicates using derived class handler
            for (int x = 0; x < m_enqueueIndex - 1; x++)
            {
                left = m_keyData[m_sortingBlocks1[x]];
                right = m_keyData[m_sortingBlocks1[x + 1]];

                if (left.IsEqualTo(right))
                {
                    m_duplicateHandler(left, right);
                    keysManipulated = true;
                }
            }

            // Validate that duplicates were properly handled
            if (keysManipulated)
            {
                // Since derived class function manipulated keys to manage duplicates we have
                // to re-sort for safety - if keys were managed properly the tree should still
                // be sorted so this second sort will be fast
                Sort();

                // We cannot corrupt the tree so we remove any unhandled duplicates - if derived
                // class duplicate handler did its job, nothing will be removed
                RemoveDuplicates();
            }
        }
    }
}


text:
import expect from 'expect.js'
import use, {format, extend} from '../src/index'

describe('index.js', function(){
    describe('#use', function () {
        it('should be a function', function(){
            expect(use).to.be.a('function')
        })

        let mixinCalled = false
        const riot = {
            mixin(){
                mixinCalled = true
            }
        }

        it('should mixin after called', function(){
            use(riot)
            expect(mixinCalled).to.ok()
        })

        for(let method of ['define', 'extend', 'format']){
            it(`should has method ${method}`, function(){
                expect(use[method]).to.be.a('function')
            })
        }
    })

    it('#format() should be a function', function () {
        expect(format).to.be.a('function')
    })

    it('#extend() should be a function', function () {
        expect(extend).to.be.a('function')
    })
})


text:
package in.vesely.eclub.yodaqa.view;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.DrawableRes;

import in.vesely.eclub.yodaqa.R;
import in.vesely.eclub.yodaqa.adapters.BindableLinearLayout;
import in.vesely.eclub.yodaqa.restclient.YodaSource;

/**
 * Created by vesely on 6/16/15.
 */
@EViewGroup(R.layout.source_item)
public class SourceItem extends BindableLinearLayout<YodaSource> {

    @ViewById(R.id.text)
    protected TextView text;

    @DrawableRes(R.drawable.ic_wikipedia_logo)
    protected Drawable wikiLogoDrawable;

    @DrawableRes(R.drawable.ic_bing_logo)
    protected Drawable bingLogoDrawable;

    @DrawableRes(R.drawable.ic_freebase_logo)
    protected Drawable freebaseLogoDrawable;

    @DrawableRes(R.drawable.ic_dbpedia_logo)
    protected Drawable dbpediaLogoDrawable;

    public SourceItem(Context context) {
        super(context);
    }

    @Override
    public void bind(YodaSource data, int position) {
        String url = data.getURL();
        text.setText(Html.fromHtml(String.format("%s (%s)", url, data.getTitle(), data.getOrigin())));
        text.setMovementMethod(LinkMovementMethod.getInstance());
        setIcon(data.getType());
    }

    private void setIcon(String sourceType){
        switch (sourceType){
            case "enwiki":
                text.setCompoundDrawablesWithIntrinsicBounds(wikiLogoDrawable, null, null, null);
                break;
            case "bing":
                text.setCompoundDrawablesWithIntrinsicBounds(bingLogoDrawable, null, null, null);
                break;
            case "freebase":
                text.setCompoundDrawablesWithIntrinsicBounds(freebaseLogoDrawable, null, null, null);
                break;
            case "dbpedia":
                text.setCompoundDrawablesWithIntrinsicBounds(dbpediaLogoDrawable, null, null, null);
                break;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
  <title>qlibc: containers/qvector.c File Reference</title>
  <link href="tabs.css" rel="stylesheet" type="text/css"/>
  <link href="doxygen.css" rel="stylesheet" type="text/css"/>

qLibc API Reference

Main Page

Files

File List

Globals

Functions

containers/qvector.c File Reference

Detailed Description

Vector implementation.

qvector container is a vector implementation. It implements a growable array of objects and it extends qlist container that allow a linked-list to be treated as a vector.

  [Code sample - Object]
  qvector_t *vector = qvector();

  // add elements
  vector->addstr(vector, "AB");      // no need to supply size
  vector->addstrf(vector, "%d", 12); // for formatted string
  vector->addstr(vector, "CD");

  // get the chunk as a string
  char *final = vector->tostring(vector);

  // print out
  printf("Number of elements = %zu\n", vector->size(vector));
  printf("Final string = %s\n", final);

  // release
  free(final);
  vector->free(vector);

  [Result]
  Number of elements = 3
  Final string = AB12CD

  [Code sample - Object]
  // sample object
  struct sampleobj {
    int num;
    char str[10];
  };

  // get new vector
  qvector_t *vector = qvector();

  // add objects
  int i;
  struct sampleobj obj;
  for(i = 0; i < 3; i++) {
    // filling object with sample data
    obj.num  = i;
    sprintf(obj.str, "hello%d", i);

    // stack
    vector->add(vector, (void *)&obj, sizeof(struct sampleobj));
  }

  // final
  struct sampleobj *final;
  final = (struct sampleobj *)vector->toarray(vector, NULL);

  // print out
  printf("Number of Objects = %zu\n", vector->size(vector));
  for(i = 0; i < vector->size(vector); i++) {
    printf("Object%d %d, %s\n", i+1, final[i].num, final[i].str);
  }

  // release
  free(final);
  vector->free(vector);

  [Result]
  Number of Objects = 3
  Object1 0, hello0
  Object2 1, hello1
  Object3 2, hello2

Note:

Use "--enable-threadsafe" configure script option to use under multi-threaded environments.

Functions

qvector_t * 	qvector (void)

 	Initialize vector.

static bool 	add (qvector_t *vector, const void *data, size_t size)

 	qvector->add(): Stack object

static bool 	addstr (qvector_t *vector, const char *str)

 	qvector->addstr(): Stack string

static bool 	addstrf (qvector_t *vector, const char *format,...)

 	qvector->addstrf(): Stack formatted string

static void * 	toarray (qvector_t *vector, size_t *size)

 	qvector->toarray(): Returns the serialized chunk containing all the elements in this vector.

static char * 	tostring (qvector_t *vector)

 	qvector->tostring(): Returns a string representation of this vector, containing string representation of each element.

static size_t 	size (qvector_t *vector)

 	qvector->size(): Returns the number of elements in this vector.

static size_t 	datasize (qvector_t *vector)

 	qvector->datasize(): Returns the sum of total element size in this vector.

static void 	clear (qvector_t *vector)

 	qvector->clear(): Removes all of the elements from this vector.

static bool 	debug (qvector_t *vector, FILE *out)

 	qvector->debug(): Print out stored elements for debugging purpose.

static void 	free_ (qvector_t *vector)

 	qvector->free(): De-allocate vector

Function Documentation

          qvector_t* qvector
          (
          void

           )

Initialize vector.

Returns:

qvector_t container pointer.

Return values:

	errno 	will be set in error condition.

ENOMEM : Memory allocation failure.

  // allocate memory
  qvector_t *vector = qvector();
  vector->free(vector);

          static bool add
          (
          qvector_t *
           vector,

          const void *
           data,

          size_t
           size

          )
          		 [static]

qvector->add(): Stack object

Parameters:

	vector 	qvector_t container pointer.

	object 	a pointer of object data

	size 	size of object

Returns:

true if successful, otherwise returns false

Return values:

	errno 	will be set in error condition.

EINVAL : Invalid argument.

ENOMEM : Memory allocation failure.

          static bool addstr
          (
          qvector_t *
           vector,

          const char *
           str

          )
          		 [static]

qvector->addstr(): Stack string

Parameters:

	vector 	qvector_t container pointer.

	str 	a pointer of string

Returns:

true if successful, otherwise returns false

Return values:

	errno 	will be set in error condition.

EINVAL : Invalid argument.

ENOMEM : Memory allocation failure.

          static bool addstrf
          (
          qvector_t *
           vector,

          const char *
           format,

           ...

          )
          		 [static]

qvector->addstrf(): Stack formatted string

Parameters:

	vector 	qvector_t container pointer.

	format 	string format

Returns:

true if successful, otherwise returns false

Return values:

	errno 	will be set in error condition.

EINVAL : Invalid argument.

ENOMEM : Memory allocation failure.

          static void* toarray
          (
          qvector_t *
           vector,

          size_t *
           size

          )
          		 [static]

qvector->toarray(): Returns the serialized chunk containing all the elements in this vector.

Parameters:

	vector 	qvector_t container pointer.

	size 	if size is not NULL, merged object size will be stored.

Returns:

a pointer of finally merged elements(malloced), otherwise returns NULL

Return values:

	errno 	will be set in error condition.

ENOENT : Vector is empty.

ENOMEM : Memory allocation failure.

          static char* tostring
          (
          qvector_t *
           vector
           )
           [static]

qvector->tostring(): Returns a string representation of this vector, containing string representation of each element.

Parameters:

	vector 	qvector_t container pointer.

Returns:

a pointer of finally merged strings(malloced), otherwise returns NULL

Return values:

	errno 	will be set in error condition.

ENOENT : Vector is empty.

ENOMEM : Memory allocation failure.

Note:

Return string is always terminated by ''.

          static size_t size
          (
          qvector_t *
           vector
           )
           [static]

qvector->size(): Returns the number of elements in this vector.

Parameters:

	vector 	qvector_t container pointer.

Returns:

the number of elements in this vector.

          static size_t datasize
          (
          qvector_t *
           vector
           )
           [static]

qvector->datasize(): Returns the sum of total element size in this vector.

Parameters:

	vector 	qvector_t container pointer.

Returns:

the sum of total element size in this vector.

          static void clear
          (
          qvector_t *
           vector
           )
           [static]

qvector->clear(): Removes all of the elements from this vector.

Parameters:

	vector 	qvector_t container pointer.

          static bool debug
          (
          qvector_t *
           vector,

          FILE *
           out

          )
          		 [static]

qvector->debug(): Print out stored elements for debugging purpose.

Parameters:

	vector 	qvector_t container pointer.

	out 	output stream FILE descriptor such like stdout, stderr.

Returns:

true if successful, otherwise returns false.

Return values:

	errno 	will be set in error condition.

EIO : Invalid output stream.

          static void free_
          (
          qvector_t *
           vector
           )
           [static]

qvector->free(): De-allocate vector

Parameters:

	vector 	qvector_t container pointer.

<address class="footer">
The qDecoder Project.
Tue Jun 12 2012 07:35:13
</address>


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Countdown</title>
</head>
<body>
<input type="text" id="time" style="border:3px solid blue; text-align:center; font-size:2em;" disabled="true"/>
<script>
    window.onload = function () {
        countdown(600);

        function countdown(startTime) {
            let time = startTime;
            let box = document.getElementById('time');
            let intervalID = setInterval(decrement, 1000);

            function decrement() {
                time--;
                box.value = Math.trunc(time / 60) + ':' + ('0' + (time % 60)).slice(-2);
            }
        }
    }
</script>
</body>
</html>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        android:layout_width="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_height="wrap_content"
        android:id="@+id/LeftListItem"
        android:paddingTop="10dip"
		android:paddingBottom="10dip">

		<ImageView
		    android:id="@+id/youtubeImageView"
		    android:layout_marginLeft="20px"
		    android:layout_width="100px"
		    android:layout_height="75px"
			android:layout_gravity="center_vertical"/>

		<LinearLayout
		    android:layout_marginLeft="15px"
		    android:layout_width="140px"
		    android:layout_height="75px"
		    android:orientation="vertical"
		    android:gravity="center_vertical"
			android:layout_gravity="center_vertical">

	        <TextView
	                android:layout_height="wrap_content"
	                android:layout_width="80px"
	                android:id="@+id/youtubeId"
	                android:textSize="16dip"
	                android:visibility="gone">
	        </TextView>
	        <TextView
	                android:layout_height="wrap_content"
	                android:layout_width="140px"
	                android:id="@+id/youtubeTitleLong"
	                android:textSize="16dip"
	                android:visibility="gone">
	        </TextView>
			<TextView
	                android:layout_height="wrap_content"
	                android:layout_width="140px"
	                android:id="@+id/youtubeViewCount"
	                android:textSize="16dip"
	                android:visibility="gone">
	        </TextView>
	        <TextView
	                android:layout_height="wrap_content"
	                android:layout_width="90px"
	                android:id="@+id/youtubeTitleShort"
	                android:lines="2"
	                android:textColor="@android:color/white"
	                android:textSize="16dip">
	        </TextView>
	        <TextView
	                android:layout_height="wrap_content"
	                android:layout_width="fill_parent"
	                android:id="@+id/youtubeDuration"
	                android:textSize="16dip"
	                android:textColor="@android:color/white">
	        </TextView>
		</LinearLayout>

</LinearLayout>


text:
require "akamai_api/cli/app"

module AkamaiApi::CLI
end


text:
<title>dlib C++ Library - vectorstream.h</title>

// Copyright (C) 2012  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_VECTORSTReAM__
#define DLIB_VECTORSTReAM__

#include "vectorstream/vectorstream.h"

#endif // DLIB_VECTORSTReAM__


text:
from __future__ import print_function
import logging

from plumbum import LocalPath

from loslassa.utils import *
from .conftest import *

class TestFindFile(object):
    @pytest.mark.usefixtures("work_in_example_project")
    def test_conf_file_found_in_example_project(self):
        foundFile = find_file(".", LoslassaProject.SPHINX_CONFIG)
        assert foundFile.basename == LoslassaProject.SPHINX_CONFIG

    @pytest.mark.usefixtures("work_in_empty_tmpdir")
    @pytest.mark.parametrize("path", (".", LocalPath(".")))
    def test_different_path_types_are_accepted(self, path):
        with assert_exc_contains(UtilsError, ["not found", "x"]):
            find_file(path, "x")

    def test_file_not_found_raises(self, tmpdir):
        with assert_exc_contains(UtilsError, ["not found", "x"]):
            find_file(tmpdir, "x")

    def test_too_many_files_found_raises(self, tmpdir):
        tmpdir = LocalPath(tmpdir)
        paths = create_dummy_projects(tmpdir, 3)
        with assert_exc_contains(UtilsError, ["too many"] + paths):
            find_file(tmpdir, LoslassaProject.SPHINX_CONFIG)

class TestAdjustLog(object):
    def test_bogus_level_raises(self):
        with assert_exc_contains(ValueError, "Unknown level"):
            adjust_log("bogus_level")

    def test_proper_level_adjust_level(self):
        adjust_log(logging.CRITICAL)
        log = logging.getLogger()
        assert log.getEffectiveLevel() == logging.CRITICAL


text:
// -----------------------------------------------------------------------
// <copyright file="IGetLinksByUserIdQuery.cs">
// Copyright (c) 2013-2015 Andrey Veselov. All rights reserved.
// License: Apache License 2.0
// Contacts: http://andrey.moveax.com andrey@moveax.com
// </copyright>
// -----------------------------------------------------------------------

namespace LoreKeeper.Tests.Core.Queries.Links
{
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using LoreKeeper.Tests.Core.Models;

    [ContractClass(typeof(GetLinksByUserIdQueryContract))]
    public interface IGetLinksByUserIdQuery : IQuery
    {
        IEnumerable<Link> Execute(int userId);
    }

    [ContractClassFor(typeof(IGetLinksByUserIdQuery))]
    internal abstract class GetLinksByUserIdQueryContract : IGetLinksByUserIdQuery
    {
        public IEnumerable<Link> Execute(int userId)
        {
            Contract.Requires(0 < userId);

            return default(IEnumerable<Link>);
        }
    }
}


text:
<Workflow xmlns="urn:wexflow-schema" id="160" name="Workflow_SqlToXml" description="Workflow_SqlToXml">
	<Settings>
		<Setting name="launchType" value="trigger" /> <!-- startup|trigger|periodic -->
		<Setting name="enabled" value="true" /> <!-- true|false -->
	</Settings>
	<Tasks>
		<Task id="1" name="SqlToXml" description="SQL Server" enabled="false">
			<Setting name="type" value="sqlserver" />
			<Setting name="connectionString" value="Data Source=localhost;Initial Catalog=HELLOWORLD;Integrated Security=True" />
			<Setting name="sql" value="select * from Data" />
		</Task>
		<Task id="2" name="SqlToXml" description="SQlite" enabled="true">
			<Setting name="type" value="sqlite" />
			<Setting name="connectionString" value="Data Source=C:\WexflowTesting\sqlite\HelloWorld.db;Version=3" /><!-- https://www.connectionstrings.com/sqlite/ -->
			<Setting name="sql" value="select * from Data;" />
		</Task>
		<Task id="3" name="SqlToXml" description="MySQL" enabled="false">
			<Setting name="type" value="mysql" />
			<Setting name="connectionString" value="Server=localhost;Database=helloworld;Uid=root;Pwd=password;" />
			<Setting name="sql" value="select * from `Data`" />
		</Task>
		<Task id="4" name="SqlToXml" description="PostgreSqlToXml" enabled="false">
			<Setting name="type" value="postgresql" />
			<Setting name="connectionString" value="User ID=postgres;Password=password;Host=localhost;Port=5432;Database=helloworld;" />
			<Setting name="sql" value="select * from Data" />
			<Setting name="selectFiles" value="7" />
		</Task>
		<Task id="5" name="SqlToXml" description="Oracle" enabled="false">
			<Setting name="type" value="oracle" />
			<Setting name="connectionString" value="Data Source=HelloWorld;Integrated Security=yes;" />
			<Setting name="sql" value="select * from Data" />
		</Task>
		<Task id="6" name="SqlToXml" description="Teradata" enabled="false">
			<Setting name="type" value="teradata" />
			<Setting name="connectionString" value="Data Source=HelloWorld;User ID=root;Password=password;" />
			<Setting name="sql" value="select * from Data" />
		</Task>
		<Task id="7" name="SqlToXml" description="Access" enabled="false">
			<Setting name="type" value="access" />
			<Setting name="connectionString" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\WexflowTesting\access\HelloWorld.accdb;Persist Security Info=False;" />
			<Setting name="sql" value="select * from Data" />
		</Task>
		<Task id="8" name="FilesMover" description="Moving SqlToXml files from temp folder" enabled="true">
			<Setting name="selectFiles" value="1" />
			<Setting name="selectFiles" value="2" />
			<Setting name="selectFiles" value="3" />
			<Setting name="selectFiles" value="4" />
			<Setting name="selectFiles" value="5" />
			<Setting name="selectFiles" value="6" />
			<Setting name="selectFiles" value="7" />
			<Setting name="destFolder" value="C:\WexflowTesting\SqlToXml\" />
		</Task>
	</Tasks>
</Workflow>


text:
export const prefix = "/gameData/";
export const dataPath = prefix + "data";
export const idsPath = prefix + "ids";
export const settingsPrefix = "/settings/";


text:
Run this program and see a list of latest bollywood favorite movies

## Make sure Python is installed
Open up your terminal and run:

$ python

It should return some version of Python like 2.7.

If Python is not installed at all, see the documentation here: https://www.python.org

## Run this Program
Navigate to the project folder and run:

$ python entertainment.py

A browser should open on your local machine and and render the HTML template with latest movies. Click on a movie thumbnail to view the trailer! Enjoy :)


text:
package com.mhaidarhanif.android.kargu;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.widget.TextView;

public class DisplayNumberActivity extends MainActivity {

  @SuppressLint("NewApi")

  // Display new activity
  @TargetApi(11)
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_number);

    // Get number from intent
    Intent intent = getIntent();
    String number = intent.getStringExtra(MainActivity.EXTRA_NUMBER);

    // Create text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(number);

    // Set text view as activity layout
    setContentView(textView);

    // Check minimum API level number to use ActionBar API
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      // Show Up button in ActionBar
      getActionBar().setDisplayHomeAsUpEnabled(true);
    }
  }

  // Inherit method from ActionBar
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
  }

}


text:
using Prism.Events;

namespace GiTracker.Events
{
    public class LoginEvent : PubSubEvent<string>
    {
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../" />

		<link type="text/css" rel="stylesheet" href="page.css" />

		[page:Object3D] →

[name]

			Create a non-positional ( global ) audio object.

			This uses the [link:https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API Web Audio API].

Example

			[example:webaudio_sandbox webaudio / sandbox ]

			[example:webaudio_visualizer webaudio / visualizer ]

		// create an AudioListener and add it to the camera
		var listener = new THREE.AudioListener();
		camera.add( listener );

		// create a global audio source
		var sound = new THREE.Audio( listener );

		// load a sound and set it as the Audio object's buffer
		var audioLoader = new THREE.AudioLoader();
		audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
			sound.setBuffer( buffer );
			sound.setLoop( true );
			sound.setVolume( 0.5 );
			sound.play();
		});

Constructor

[name]( [page:AudioListener listener] )

		listener — (required) [page:AudioListener AudioListener] instance.

Properties

[property:Boolean autoplay]

Whether to start playback automatically. Default is *false*.

[property:AudioContext context]

The [link:https://developer.mozilla.org/en-US/docs/Web/API/AudioContext AudioContext] of the [page:AudioListener listener] given in the constructor.

[property:Array filters]

Whether the audio is currently playing. Default is empty array.

[property:GainNode gain]

A [link:https://developer.mozilla.org/en-US/docs/Web/API/GainNode GainNode] created
		using [link:https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/createGain AudioContext.createGain]().

[property:Boolean hasPlaybackControl]

Whether playback can be controlled using the [page:Audio.play play](),
			[page:Audio.pause pause]() etc. methods. Default is *true*.

[property:Number playbackRate]

Speed of playback. Default is *1*.

[property:Boolean isPlaying]

Whether the audio is currently playing.

[property:Number startTime]

The time at which the sound should begin to play. Same as the *when* paramter of [link:https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/start AudioBufferSourceNode.start](). Default is *0*.

[property:Number offset]

An offset to the time within the audio buffer that playback should begin. Same as the *offset* paramter of [link:https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/start AudioBufferSourceNode.start](). Default is *0*.

[property:String source]

An [link:https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode AudioBufferSourceNode] created
		using [link:https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/createBufferSource AudioContext.createBufferSource]().

[property:String sourceType]

Type of the audio source. Default is string 'empty'.

[property:String type]

String denoting the type, set to 'Audio'.

Methods

[method:null connect]()

		Connect to the [page:Audio.source]. This is used internally on initialisation and when
		setting / removing filters.

[method:null disconnect]()

		Disconnect from the [page:Audio.source]. This is used internally when
		setting / removing filters.

[method:Array getFilter]()

		Returns the first element of the [page:Audio.filters filters] array.

[method:null getFilters]()

		Returns the [page:Audio.filters filters] array.

[method:Boolean getLoop]()

		Return the value of [link:https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/loop source.loop]
		 (whether playback should loop).

[method:GainNode getOutput]()

		Return the [page:Audio.gain gainNode].

[method:Number getPlaybackRate]()

		Return the value of [page:Audio.playbackRate playbackRate].

[method:Number getVolume]( value )

		Return the current volume.

[method:null play]()

		If [page:Audio.hasPlaybackControl hasPlaybackControl] is true, starts playback.

[method:null pause]()

		If [page:Audio.hasPlaybackControl hasPlaybackControl] is true, pauses playback.

[method:null onEnded]()

		Called automatically when playback finished. Sets If [page:Audio.isPlaying isPlaying] to false.

[method:Audio setBuffer]( audioBuffer )

		Setup the [page:Audio.source source] to the audioBuffer, and sets [page:Audio.sourceType sourceType] to 'buffer'.

		If [page:Audio.autoplay autoplay], also starts playback.

[method:null setFilter]( filter )

		Add the filter to the [page:Audio.filters filters] array.

[method:Audio setFilters]( [page:Array value] )

		value - arrays of filters.

		Set the [page:Audio.filters filters] array to *value*.

[method:null setLoop]( [page:Boolean value] )

		Set [link:https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/loop source.loop] to *value*
		(whether playback should loop).

[method:null setNodeSource]( audioNode )

		Setup the [page:Audio.source source] to the audioBuffer, and sets [page:Audio.sourceType sourceType] to 'audioNode'.

		Also sets [page:Audio.hasPlaybackControl hasPlaybackControl] to false.

[method:null setPlaybackRate]( [page:Number value] )

		If [page:Audio.hasPlaybackControl hasPlaybackControl] is enabled, set the [page:Audio.playbackRate playbackRate] to *value*.

[method:null setVolume]( [page:Number value] )

		Set the volume.

[method:null stop]()

		If [page:Audio.hasPlaybackControl hasPlaybackControl] is enabled, stops playback,
		resets [page:Audio.startTime startTime] to *0* and sets [page:Audio.isPlaying isPlaying] to false.

Source

		[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]


text:
from lab.base_lab import LabWorker

class DeployerDevstack(LabWorker):

    def sample_config(self):
        return {'cloud': 'arbitrary name of the cloud', 'user': 'default user name', 'tenant': 'tenant name', 'password': 'password',
                'server_config_pairs': [{'hostname': 'server name ob which to run', 'devstack_config': 'this devstack conf'}]}

    def __init__(self, config):
        import os

        super(DeployerDevstack, self).__init__(config=config)

        self.cloud = config['cloud']
        self.user = config['user']
        self.tenant = config['tenant']
        self.password = config['password']
        self.dir_for_devstack_configs = os.path.join(self.CONFIG_DIR, 'devstack')

        with open(os.path.join(self.dir_for_devstack_configs, 'common_section.conf')) as f:
            common_section = f.read()

        common_section = common_section.replace('{password}', config['password'])

        controllers = []
        others = []
        for pair in config['server_config_pairs']:
            hostname = pair['hostname']
            devstack_config = pair['devstack_config']

            config_path = devstack_config if os.path.isfile(devstack_config) else os.path.join(self.dir_for_devstack_configs, devstack_config)
            if not os.path.isfile(config_path):
                avail_configs = '\n'.join([x for x in os.listdir(self.dir_for_devstack_configs) if x != 'common_section.conf'])
                raise IOError('{0} not found. Provide full path or choose one of:\n{1}'.format(config_path, avail_configs))

            with open(os.path.join(self.dir_for_devstack_configs, devstack_config)) as f:
                conf_as_string = common_section + f.read()

            which = controllers if devstack_config.startswith('aio') or devstack_config.startswith('controller') else others
            which.append({'hostname': hostname, 'config_name': devstack_config, 'config_as_string': conf_as_string})

        if not controllers:
            raise ValueError('No aio or controller provided!')
        self.roles = controllers + others  # this is to ensure that controllers are deployed first
        self.actual_servers = []  # deployment will run on this list

    @staticmethod
    def fill_devstack_config(config_as_string, cloud_status):
        if 'controller_ip' in config_as_string:
            config_as_string = config_as_string.replace('{controller_ip}', cloud_status.get_first(role='controller', parameter='ip'))
            config_as_string = config_as_string.replace('{controller_name}', cloud_status.get_first(role='controller', parameter='hostname'))
            config_as_string = config_as_string.replace('{nova_ips}', ','.join(cloud_status.get(role='compute', parameter='ip')))
            config_as_string = config_as_string.replace('{nova_ips}', ','.join(cloud_status.get(role='compute', parameter='ip')))
        if 'ucsm_ip' in config_as_string:
            ucsm_ip = cloud_status.get_first(role='ucsm', parameter='ip')
            ucsm_user = cloud_status.get_first(role='ucsm', parameter='user')
            ucsm_password = cloud_status.get_first(role='ucsm', parameter='password')
            ucsm_host_list = cloud_status.get_first(role='ucsm', parameter='host_list')
            network_node_host = cloud_status.get_first(role='ucsm', parameter='network_node_host')
            config_as_string = config_as_string.replace('{ucsm_ip}', ucsm_ip)
            config_as_string = config_as_string.replace('{ucsm_username}', ucsm_user)
            config_as_string = config_as_string.replace('{ucsm_password}', ucsm_password)
            config_as_string = config_as_string.replace('{ucsm_host_list}', ucsm_host_list)
            config_as_string = config_as_string.replace('{network_node_host}', network_node_host)
        if '{' in config_as_string:
            raise ValueError('During populating config, values not found for some placeholders: {0}'.format(config_as_string))
        return config_as_string

    def run_devstack_on_server(self, server, config_as_string):
        repo = server.clone_repo(repo_url='https://git.openstack.org/openstack-dev/devstack.git', server=server)
        server.put(what=config_as_string, name='local.conf', in_directory=repo)
        server.exe(command='./unstack.sh', in_directory=repo, is_warn_only=True)
        server.exe(command='./clean.sh', in_directory=repo, is_warn_only=True)
        server.exe(command='sudo pkill --signal 9 -f python', is_warn_only=True)  # Kill all python processes to avoid errors: Address already in use
        server.exe(command='./stack.sh', in_directory=repo)

    def deploy_cloud(self, servers):
        from lab.cloud import Cloud

        cloud = Cloud(cloud=self.cloud, user=self.user, tenant=self.tenant, admin='admin', password=self.password)
        hostname_vs_server = {server.hostname: server for server in servers}  # {aio: server_obj, ...}
        for role in self.roles:  # [{'hostname': 'aio', 'config_name': 'aio', 'config_as_string': 'blalbl'}, ...]
            if role['hostname'] not in hostname_vs_server.keys():
                raise ValueError('Expected server "{0}" which is not provided'.format(role['hostname']))
            server = hostname_vs_server[role['hostname']]
            cloud.add_server(config_name=role['config_name'], server=server)
            server.config_as_string = role['config_as_string']
            self.actual_servers.append(server)

        for server in self.actual_servers:
            config_after_fill = self.fill_devstack_config(config_as_string=server.config_as_string, cloud_status=cloud)
            self.run_devstack_on_server(server=server, config_as_string=config_after_fill)
        return cloud

    def execute(self, servers_and_clouds):
        cloud = self.deploy_cloud(servers=servers_and_clouds['servers'])
        servers_and_clouds['clouds'].append(cloud)
        return True


text:
cask "spitfire-audio" do
  version "3.3.22,1639562400"
  sha256 "0a4b97c384b790a5ded9e426fb6b14a8401f67222af68225bebcea90e61b630b"

  url "https://d1t3zg51rvnesz.cloudfront.net/p/files/lm/#{version.csv.second}/mac/SpitfireAudio-Mac-#{version.csv.first}.dmg",
      verified: "d1t3zg51rvnesz.cloudfront.net/p/files/lm/"
  name "Spitfire Audio"
  desc "Download manager for Spitfire audio libraries"
  homepage "https://www.spitfireaudio.com/info/library-manager/"

  livecheck do
    url "https://www.spitfireaudio.com/library-manager/download/mac/"
    strategy :header_match do |headers|
      match = headers["location"].match(%r{/(\d+)/.*-(\d+(?:\.\d+)+)\.dmg}i)
      next if match.blank?

      "#{match[2]},#{match[1]}"
    end
  end

  auto_updates true

  app "Spitfire Audio.app"

  uninstall delete: [
    "/Library/LaunchDaemons/com.spitfireaudio.LibraryManagerHelper.plist",
    "/Library/Logs/Spitfire Audio",
    "/Library/PrivilegedHelperTools/com.spitfireaudio.LibraryManagerHelper",
  ]

  zap delete: [
    "~/Library/Caches/com.spitfireaudio.spitfireaudio",
    "~/Library/Preferences/com.spitfireaudio.spitfireaudio.plist",
  ]
end


text:
package de.codesourcery.javr.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;

public class MemParser
{
	private static final boolean DEBUG = false;
	private static final Pattern pat = Pattern.compile("^([_0-9]{13}) (.*?) ([0-9]+(\\.[0-9]+)) ([0-9]+) ([0-9]+)$");
	private static final Map<Date,Entry> entries = new HashMap<>();

	protected static final class Entry implements Comparable<Entry>
	{
		public final Date timestamp;
		public final Map<String,Float> percentage = new HashMap<>();
		public final Map<String,Integer> mem1 = new HashMap<>();
		public final Map<String,Integer> mem2 = new HashMap<>();

		@SuppressWarnings("deprecation")
        public Entry(Date timestamp)
		{
			this.timestamp = new Date(timestamp.getYear(),timestamp.getMonth(),timestamp.getDate());
		}

		public Set<String> processNames() {
			return mem1.keySet();
		}

		public Integer mem1(String process) {
			return mem1.get( process );
		}

		public Integer mem2(String process) {
			return mem2.get( process );
		}

		public static boolean hasGrown(String process,Entry first,Entry last)
		{
			return last.percentage(process) > first.percentage(process ) || last.mem1(process ) > first.mem1(process) || last.mem2( process ) > first.mem2( process );
		}

		public Float percentage(String process) {
			return percentage.get( process );
		}

		public String toString(String process) {
			return timestamp+" - process: "+process+" | perc: "+percentage(process)+" | mem1: "+mem1(process)+" | mem2: "+mem2(process);
		}

		@Override
		public int compareTo(Entry o) {
			return this.timestamp.compareTo( o.timestamp );
		}

		@Override
		public boolean equals(Object obj)
		{
			if ( obj instanceof Entry) {
				return this.timestamp.equals( ((Entry) obj).timestamp );
			}
			return false;
		}

		public boolean containsProcess(String name) {
			return mem1.containsKey( name );
		}

		@Override
		public int hashCode() {
			return timestamp.hashCode();
		}

		public void add(String process, float percentage, int mem1, int mem2)
		{
			Integer existing = this.mem1.get(process);
			if ( existing == null ) {
				existing = Integer.valueOf(0 );
			}
			existing += mem1;
			this.mem1.put( process , existing );

			existing = this.mem2.get(process);
			if ( existing == null ) {
				existing = Integer.valueOf(0 );
			}
			existing += mem2;
			this.mem2.put( process , existing );

			Float existingFloat = this.percentage.get(process);
			if ( existingFloat == null ) {
				existingFloat = Float.valueOf(0 );
			}
			if ( percentage > existingFloat) {
				existingFloat = percentage;
			}
			this.percentage.put( process , existingFloat );
		}
	}

	public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {

		final File file = new File("/home/tgierke/mem.log");

		// 20160115_0947
		// 20160115_0947 kuiserver 0.1 17188 274088

		final DateFormat DF = new SimpleDateFormat("yyyyMMdd_HHmm");
		int lineNo=0;
		for ( String line : IOUtils.readLines( new FileInputStream(file) ) )
		{
			lineNo++;
			Matcher m = pat.matcher( line );
			if ( m.matches() )
			{
				try {
					final Date date = DF.parse( m.group(1) );
					final String process = m.group(2);
					final float percentage = Float.parseFloat( m.group(4) );
					final int mem1 = Integer.parseInt( m.group(5) );
					final int mem2 = Integer.parseInt( m.group(6) );

					if ( percentage >= 0.1f )
					{
//						System.out.println("LINE: "+line);
//						System.out.println(date+" => "+process+" , perc="+percentage+", mem1="+mem1+" , mem2="+mem2);
						Entry existing = entries.get( date );
						if ( existing==null ) {
							existing = new Entry( date );
							entries.put(date, existing);
						}
						existing.add( process,percentage,mem1,mem2 );
					}
				} catch(Exception e) {
					System.out.println("ERROR ("+e.getMessage()+") on line "+lineNo+" : "+line);
				}
			} else {
				System.out.println("Malformed line "+lineNo+" : "+line);
			}
		}

		findGrowing();
	}

	private static Set<String> findGrowing()
	{
		final Set<String> uniqueProcessName = entries.values().stream().map( p -> p.processNames() ).flatMap( s -> s.stream() ).distinct().collect( Collectors.toSet() );

		System.out.println("Unique process names: "+uniqueProcessName.size());
		final List<Date> datesAscending = new ArrayList<>( entries.keySet() );
		Collections.sort( datesAscending );

		final List<Date> datesDescending = new ArrayList<>( entries.keySet() );
		final Comparator<Date> comp = (a,b) -> a.compareTo( b );
		Collections.sort( datesDescending , comp.reversed() );

		System.out.println( uniqueProcessName.stream().collect(Collectors.joining("\n")) );
		final Set<String> result = new HashSet<>();
		uniqueProcessName.forEach( name ->
		{
			Entry first=datesAscending.stream().map( d -> entries.get(d) ).filter( e -> e.containsProcess( name ) ).findFirst().orElse( null );
			Entry last=datesDescending.stream().map( d -> entries.get(d) ).filter( e -> e.containsProcess( name ) ).findFirst().orElse( null );

			if ( DEBUG ) {
				System.out.println( name+" first "+first.timestamp+": mem1="+first.mem1(name)+",mem2="+first.mem2(name));
				System.out.println( name+" last  "+last.timestamp+" : mem1="+last.mem1(name)+",mem2="+last.mem2(name));
			}

			if ( Entry.hasGrown( name ,first,last ) )
			{
				System.out.println("\n======\nProcess '"+name+"' grew!");
				System.out.println( first.toString( name ) );
				System.out.println( last.toString( name ) );
				result.add( name );
			} else {
				if ( DEBUG ) {
					System.out.println("NOT GROWN: Process '"+name+"' grew from "+first.percentage( name )+" => "+last.percentage(name));
				}
			}
		});
		return result;
	}
}


text:
import os
import mmap
import sys
import platform
import gc
import pickle

from joblib.test.common import with_numpy, np
from joblib.test.common import setup_autokill
from joblib.test.common import teardown_autokill
from joblib.test.common import with_multiprocessing
from joblib.test.common import with_dev_shm
from joblib.testing import raises, parametrize, skipif
from joblib.backports import make_memmap
from joblib.parallel import Parallel, delayed

from joblib.pool import MemmappingPool
from joblib.executor import _TestingMemmappingExecutor
from joblib._memmapping_reducer import has_shareable_memory
from joblib._memmapping_reducer import ArrayMemmapReducer
from joblib._memmapping_reducer import reduce_memmap
from joblib._memmapping_reducer import _strided_from_memmap
from joblib._memmapping_reducer import _get_backing_memmap
from joblib._memmapping_reducer import _get_temp_dir
from joblib._memmapping_reducer import _WeakArrayKeyMap
import joblib._memmapping_reducer as jmr

def setup_module():
    setup_autokill(__name__, timeout=300)

def teardown_module():
    teardown_autokill(__name__)

def check_array(args):
    """Dummy helper function to be executed in subprocesses

    Check that the provided array has the expected values in the provided
    range.

    """
    data, position, expected = args
    np.testing.assert_array_equal(data[position], expected)

def inplace_double(args):
    """Dummy helper function to be executed in subprocesses

    Check that the input array has the right values in the provided range
    and perform an inplace modification to double the values in the range by
    two.

    """
    data, position, expected = args
    assert data[position] == expected
    data[position] *= 2
    np.testing.assert_array_equal(data[position], 2 * expected)

@with_numpy
@with_multiprocessing
def test_memmap_based_array_reducing(tmpdir):
    """Check that it is possible to reduce a memmap backed array"""
    assert_array_equal = np.testing.assert_array_equal
    filename = tmpdir.join('test.mmap').strpath

    # Create a file larger than what will be used by a
    buffer = np.memmap(filename, dtype=np.float64, shape=500, mode='w+')

    # Fill the original buffer with negative markers to detect over of
    # underflow in case of test failures
    buffer[:] = - 1.0 * np.arange(buffer.shape[0], dtype=buffer.dtype)
    buffer.flush()

    # Memmap a 2D fortran array on a offseted subsection of the previous
    # buffer
    a = np.memmap(filename, dtype=np.float64, shape=(3, 5, 4),
                  mode='r+', order='F', offset=4)
    a[:] = np.arange(60).reshape(a.shape)

    # Build various views that share the buffer with the original memmap

    # b is an memmap sliced view on an memmap instance
    b = a[1:-1, 2:-1, 2:4]

    # c and d are array views
    c = np.asarray(b)
    d = c.T

    # Array reducer with auto dumping disabled
    reducer = ArrayMemmapReducer(None, tmpdir.strpath, 'c')

    def reconstruct_array(x):
        cons, args = reducer(x)
        return cons(*args)

    def reconstruct_memmap(x):
        cons, args = reduce_memmap(x)
        return cons(*args)

    # Reconstruct original memmap
    a_reconstructed = reconstruct_memmap(a)
    assert has_shareable_memory(a_reconstructed)
    assert isinstance(a_reconstructed, np.memmap)
    assert_array_equal(a_reconstructed, a)

    # Reconstruct strided memmap view
    b_reconstructed = reconstruct_memmap(b)
    assert has_shareable_memory(b_reconstructed)
    assert_array_equal(b_reconstructed, b)

    # Reconstruct arrays views on memmap base
    c_reconstructed = reconstruct_array(c)
    assert not isinstance(c_reconstructed, np.memmap)
    assert has_shareable_memory(c_reconstructed)
    assert_array_equal(c_reconstructed, c)

    d_reconstructed = reconstruct_array(d)
    assert not isinstance(d_reconstructed, np.memmap)
    assert has_shareable_memory(d_reconstructed)
    assert_array_equal(d_reconstructed, d)

    # Test graceful degradation on fake memmap instances with in-memory
    # buffers
    a3 = a * 3
    assert not has_shareable_memory(a3)
    a3_reconstructed = reconstruct_memmap(a3)
    assert not has_shareable_memory(a3_reconstructed)
    assert not isinstance(a3_reconstructed, np.memmap)
    assert_array_equal(a3_reconstructed, a * 3)

    # Test graceful degradation on arrays derived from fake memmap instances
    b3 = np.asarray(a3)
    assert not has_shareable_memory(b3)

    b3_reconstructed = reconstruct_array(b3)
    assert isinstance(b3_reconstructed, np.ndarray)
    assert not has_shareable_memory(b3_reconstructed)
    assert_array_equal(b3_reconstructed, b3)

@with_numpy
@with_multiprocessing
def test_high_dimension_memmap_array_reducing(tmpdir):
    assert_array_equal = np.testing.assert_array_equal

    filename = tmpdir.join('test.mmap').strpath

    # Create a high dimensional memmap
    a = np.memmap(filename, dtype=np.float64, shape=(100, 15, 15, 3),
                  mode='w+')
    a[:] = np.arange(100 * 15 * 15 * 3).reshape(a.shape)

    # Create some slices/indices at various dimensions
    b = a[0:10]
    c = a[:, 5:10]
    d = a[:, :, :, 0]
    e = a[1:3:4]

    def reconstruct_memmap(x):
        cons, args = reduce_memmap(x)
        res = cons(*args)
        return res

    a_reconstructed = reconstruct_memmap(a)
    assert has_shareable_memory(a_reconstructed)
    assert isinstance(a_reconstructed, np.memmap)
    assert_array_equal(a_reconstructed, a)

    b_reconstructed = reconstruct_memmap(b)
    assert has_shareable_memory(b_reconstructed)
    assert_array_equal(b_reconstructed, b)

    c_reconstructed = reconstruct_memmap(c)
    assert has_shareable_memory(c_reconstructed)
    assert_array_equal(c_reconstructed, c)

    d_reconstructed = reconstruct_memmap(d)
    assert has_shareable_memory(d_reconstructed)
    assert_array_equal(d_reconstructed, d)

    e_reconstructed = reconstruct_memmap(e)
    assert has_shareable_memory(e_reconstructed)
    assert_array_equal(e_reconstructed, e)

@with_numpy
def test__strided_from_memmap(tmpdir):
    fname = tmpdir.join('test.mmap').strpath
    size = 5 * mmap.ALLOCATIONGRANULARITY
    offset = mmap.ALLOCATIONGRANULARITY + 1
    # This line creates the mmap file that is reused later
    memmap_obj = np.memmap(fname, mode='w+', shape=size + offset)
    # filename, dtype, mode, offset, order, shape, strides, total_buffer_len
    memmap_obj = _strided_from_memmap(fname, dtype='uint8', mode='r',
                                      offset=offset, order='C', shape=size,
                                      strides=None, total_buffer_len=None)
    assert isinstance(memmap_obj, np.memmap)
    assert memmap_obj.offset == offset
    memmap_backed_obj = _strided_from_memmap(fname, dtype='uint8', mode='r',
                                             offset=offset, order='C',
                                             shape=(size // 2,), strides=(2,),
                                             total_buffer_len=size)
    assert _get_backing_memmap(memmap_backed_obj).offset == offset

@with_numpy
@with_multiprocessing
@parametrize("factory", [MemmappingPool, _TestingMemmappingExecutor],
             ids=["multiprocessing", "loky"])
def test_pool_with_memmap(factory, tmpdir):
    """Check that subprocess can access and update shared memory memmap"""
    assert_array_equal = np.testing.assert_array_equal

    # Fork the subprocess before allocating the objects to be passed
    pool_temp_folder = tmpdir.mkdir('pool').strpath
    p = factory(10, max_nbytes=2, temp_folder=pool_temp_folder)
    try:
        filename = tmpdir.join('test.mmap').strpath
        a = np.memmap(filename, dtype=np.float32, shape=(3, 5), mode='w+')
        a.fill(1.0)

        p.map(inplace_double, [(a, (i, j), 1.0)
                               for i in range(a.shape[0])
                               for j in range(a.shape[1])])

        assert_array_equal(a, 2 * np.ones(a.shape))

        # Open a copy-on-write view on the previous data
        b = np.memmap(filename, dtype=np.float32, shape=(5, 3), mode='c')

        p.map(inplace_double, [(b, (i, j), 2.0)
                               for i in range(b.shape[0])
                               for j in range(b.shape[1])])

        # Passing memmap instances to the pool should not trigger the creation
        # of new files on the FS
        assert os.listdir(pool_temp_folder) == []

        # the original data is untouched
        assert_array_equal(a, 2 * np.ones(a.shape))
        assert_array_equal(b, 2 * np.ones(b.shape))

        # readonly maps can be read but not updated
        c = np.memmap(filename, dtype=np.float32, shape=(10,), mode='r',
                      offset=5 * 4)

        with raises(AssertionError):
            p.map(check_array, [(c, i, 3.0) for i in range(c.shape[0])])

        # depending on the version of numpy one can either get a RuntimeError
        # or a ValueError
        with raises((RuntimeError, ValueError)):
            p.map(inplace_double, [(c, i, 2.0) for i in range(c.shape[0])])
    finally:
        # Clean all filehandlers held by the pool
        p.terminate()
        del p

@with_numpy
@with_multiprocessing
@parametrize("factory", [MemmappingPool, _TestingMemmappingExecutor],
             ids=["multiprocessing", "loky"])
def test_pool_with_memmap_array_view(factory, tmpdir):
    """Check that subprocess can access and update shared memory array"""
    assert_array_equal = np.testing.assert_array_equal

    # Fork the subprocess before allocating the objects to be passed
    pool_temp_folder = tmpdir.mkdir('pool').strpath
    p = factory(10, max_nbytes=2, temp_folder=pool_temp_folder)
    try:

        filename = tmpdir.join('test.mmap').strpath
        a = np.memmap(filename, dtype=np.float32, shape=(3, 5), mode='w+')
        a.fill(1.0)

        # Create an ndarray view on the memmap instance
        a_view = np.asarray(a)
        assert not isinstance(a_view, np.memmap)
        assert has_shareable_memory(a_view)

        p.map(inplace_double, [(a_view, (i, j), 1.0)
                               for i in range(a.shape[0])
                               for j in range(a.shape[1])])

        # Both a and the a_view have been updated
        assert_array_equal(a, 2 * np.ones(a.shape))
        assert_array_equal(a_view, 2 * np.ones(a.shape))

        # Passing memmap array view to the pool should not trigger the
        # creation of new files on the FS
        assert os.listdir(pool_temp_folder) == []

    finally:
        p.terminate()
        del p

@with_numpy
@with_multiprocessing
@parametrize("factory", [MemmappingPool, _TestingMemmappingExecutor],
             ids=["multiprocessing", "loky"])
def test_memmapping_pool_for_large_arrays(factory, tmpdir):
    """Check that large arrays are not copied in memory"""

    # Check that the tempfolder is empty
    assert os.listdir(tmpdir.strpath) == []

    # Build an array reducers that automaticaly dump large array content
    # to filesystem backed memmap instances to avoid memory explosion
    p = factory(3, max_nbytes=40, temp_folder=tmpdir.strpath, verbose=2)
    try:
        # The temporary folder for the pool is not provisioned in advance
        assert os.listdir(tmpdir.strpath) == []
        assert not os.path.exists(p._temp_folder)

        small = np.ones(5, dtype=np.float32)
        assert small.nbytes == 20
        p.map(check_array, [(small, i, 1.0) for i in range(small.shape[0])])

        # Memory has been copied, the pool filesystem folder is unused
        assert os.listdir(tmpdir.strpath) == []

        # Try with a file larger than the memmap threshold of 40 bytes
        large = np.ones(100, dtype=np.float64)
        assert large.nbytes == 800
        p.map(check_array, [(large, i, 1.0) for i in range(large.shape[0])])

        # The data has been dumped in a temp folder for subprocess to share it
        # without per-child memory copies
        assert os.path.isdir(p._temp_folder)
        dumped_filenames = os.listdir(p._temp_folder)
        assert len(dumped_filenames) == 1

        # Check that memory mapping is not triggered for arrays with
        # dtype='object'
        objects = np.array(['abc'] * 100, dtype='object')
        results = p.map(has_shareable_memory, [objects])
        assert not results[0]

    finally:
        # check FS garbage upon pool termination
        p.terminate()
        assert not os.path.exists(p._temp_folder)
        del p

@with_numpy
@with_multiprocessing
@parametrize("factory", [MemmappingPool, _TestingMemmappingExecutor],
             ids=["multiprocessing", "loky"])
def test_memmapping_pool_for_large_arrays_disabled(factory, tmpdir):
    """Check that large arrays memmapping can be disabled"""
    # Set max_nbytes to None to disable the auto memmapping feature
    p = factory(3, max_nbytes=None, temp_folder=tmpdir.strpath)
    try:

        # Check that the tempfolder is empty
        assert os.listdir(tmpdir.strpath) == []

        # Try with a file largish than the memmap threshold of 40 bytes
        large = np.ones(100, dtype=np.float64)
        assert large.nbytes == 800
        p.map(check_array, [(large, i, 1.0) for i in range(large.shape[0])])

        # Check that the tempfolder is still empty
        assert os.listdir(tmpdir.strpath) == []

    finally:
        # Cleanup open file descriptors
        p.terminate()
        del p

@with_numpy
@with_multiprocessing
@with_dev_shm
@parametrize("factory", [MemmappingPool, _TestingMemmappingExecutor],
             ids=["multiprocessing", "loky"])
def test_memmapping_on_large_enough_dev_shm(factory):
    """Check that memmapping uses /dev/shm when possible"""
    orig_size = jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE
    try:
        # Make joblib believe that it can use /dev/shm even when running on a
        # CI container where the size of the /dev/shm is not very large (that
        # is at least 32 MB instead of 2 GB by default).
        jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(32e6)
        p = factory(3, max_nbytes=10)
        try:
            # Check that the pool has correctly detected the presence of the
            # shared memory filesystem.
            pool_temp_folder = p._temp_folder
            folder_prefix = '/dev/shm/joblib_memmapping_folder_'
            assert pool_temp_folder.startswith(folder_prefix)
            assert os.path.exists(pool_temp_folder)

            # Try with a file larger than the memmap threshold of 10 bytes
            a = np.ones(100, dtype=np.float64)
            assert a.nbytes == 800
            p.map(id, [a] * 10)
            # a should have been memmapped to the pool temp folder: the joblib
            # pickling procedure generate one .pkl file:
            assert len(os.listdir(pool_temp_folder)) == 1

            # create a new array with content that is different from 'a' so
            # that it is mapped to a different file in the temporary folder of
            # the pool.
            b = np.ones(100, dtype=np.float64) * 2
            assert b.nbytes == 800
            p.map(id, [b] * 10)
            # A copy of both a and b are now stored in the shared memory folder
            assert len(os.listdir(pool_temp_folder)) == 2
        finally:
            # Cleanup open file descriptors
            p.terminate()
            del p
        # The temp folder is cleaned up upon pool termination
        assert not os.path.exists(pool_temp_folder)
    finally:
        jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = orig_size

@with_numpy
@with_multiprocessing
@with_dev_shm
@parametrize("factory", [MemmappingPool, _TestingMemmappingExecutor],
             ids=["multiprocessing", "loky"])
def test_memmapping_on_too_small_dev_shm(factory):
    orig_size = jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE
    try:
        # Make joblib believe that it cannot use /dev/shm unless there is
        # 42 exabytes of available shared memory in /dev/shm
        jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(42e18)

        p = factory(3, max_nbytes=10)
        try:
            # Check that the pool has correctly detected the presence of the
            # shared memory filesystem.
            pool_temp_folder = p._temp_folder
            assert not pool_temp_folder.startswith('/dev/shm')
        finally:
            # Cleanup open file descriptors
            p.terminate()
            del p

        # The temp folder is cleaned up upon pool termination
        assert not os.path.exists(pool_temp_folder)
    finally:
        jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = orig_size

@with_numpy
@with_multiprocessing
@parametrize("factory", [MemmappingPool, _TestingMemmappingExecutor],
             ids=["multiprocessing", "loky"])
def test_memmapping_pool_for_large_arrays_in_return(factory, tmpdir):
    """Check that large arrays are not copied in memory in return"""
    assert_array_equal = np.testing.assert_array_equal

    # Build an array reducers that automaticaly dump large array content
    # but check that the returned datastructure are regular arrays to avoid
    # passing a memmap array pointing to a pool controlled temp folder that
    # might be confusing to the user

    # The MemmappingPool user can always return numpy.memmap object explicitly
    # to avoid memory copy
    p = factory(3, max_nbytes=10, temp_folder=tmpdir.strpath)
    try:
        res = p.apply_async(np.ones, args=(1000,))
        large = res.get()
        assert not has_shareable_memory(large)
        assert_array_equal(large, np.ones(1000))
    finally:
        p.terminate()
        del p

def _worker_multiply(a, n_times):
    """Multiplication function to be executed by subprocess"""
    assert has_shareable_memory(a)
    return a * n_times

@with_numpy
@with_multiprocessing
@parametrize("factory", [MemmappingPool, _TestingMemmappingExecutor],
             ids=["multiprocessing", "loky"])
def test_workaround_against_bad_memmap_with_copied_buffers(factory, tmpdir):
    """Check that memmaps with a bad buffer are returned as regular arrays

    Unary operations and ufuncs on memmap instances return a new memmap
    instance with an in-memory buffer (probably a numpy bug).
    """
    assert_array_equal = np.testing.assert_array_equal

    p = factory(3, max_nbytes=10, temp_folder=tmpdir.strpath)
    try:
        # Send a complex, large-ish view on a array that will be converted to
        # a memmap in the worker process
        a = np.asarray(np.arange(6000).reshape((1000, 2, 3)),
                       order='F')[:, :1, :]

        # Call a non-inplace multiply operation on the worker and memmap and
        # send it back to the parent.
        b = p.apply_async(_worker_multiply, args=(a, 3)).get()
        assert not has_shareable_memory(b)
        assert_array_equal(b, 3 * a)
    finally:
        p.terminate()
        del p

def identity(arg):
    return arg

@with_numpy
@with_multiprocessing
@parametrize("factory", [MemmappingPool, _TestingMemmappingExecutor],
             ids=["multiprocessing", "loky"])
def test_pool_memmap_with_big_offset(factory, tmpdir):
    # Test that numpy memmap offset is set correctly if greater than
    # mmap.ALLOCATIONGRANULARITY, see
    # https://github.com/joblib/joblib/issues/451 and
    # https://github.com/numpy/numpy/pull/8443 for more details.
    fname = tmpdir.join('test.mmap').strpath
    size = 5 * mmap.ALLOCATIONGRANULARITY
    offset = mmap.ALLOCATIONGRANULARITY + 1
    obj = make_memmap(fname, mode='w+', shape=size, dtype='uint8',
                      offset=offset)

    p = factory(2, temp_folder=tmpdir.strpath)
    result = p.apply_async(identity, args=(obj,)).get()
    assert isinstance(result, np.memmap)
    assert result.offset == offset
    np.testing.assert_array_equal(obj, result)

def test_pool_get_temp_dir(tmpdir):
    pool_folder_name = 'test.tmpdir'
    pool_folder, shared_mem = _get_temp_dir(pool_folder_name, tmpdir.strpath)
    assert shared_mem is False
    assert pool_folder == tmpdir.join('test.tmpdir').strpath

    pool_folder, shared_mem = _get_temp_dir(pool_folder_name, temp_folder=None)
    if sys.platform.startswith('win'):
        assert shared_mem is False
    assert pool_folder.endswith(pool_folder_name)

@with_numpy
@skipif(sys.platform == 'win32', reason='This test fails with a '
        'PermissionError on Windows')
@parametrize("mmap_mode", ["r+", "w+"])
def test_numpy_arrays_use_different_memory(mmap_mode):
    def func(arr, value):
        arr[:] = value
        return arr

    arrays = [np.zeros((10, 10), dtype='float64') for i in range(10)]

    results = Parallel(mmap_mode=mmap_mode, max_nbytes=0, n_jobs=2)(
        delayed(func)(arr, i) for i, arr in enumerate(arrays))

    for i, arr in enumerate(results):
        np.testing.assert_array_equal(arr, i)

@with_numpy
def test_weak_array_key_map():

    def assert_empty_after_gc_collect(container, retries=3):
        for i in range(retries):
            if len(container) == 0:
                return
            gc.collect()
        assert len(container) == 0

    a = np.ones(42)
    m = _WeakArrayKeyMap()
    m.set(a, 'a')
    assert m.get(a) == 'a'

    b = a
    assert m.get(b) == 'a'
    m.set(b, 'b')
    assert m.get(a) == 'b'

    del a
    gc.collect()
    assert len(m._data) == 1
    assert m.get(b) == 'b'

    del b
    assert_empty_after_gc_collect(m._data)

    c = np.ones(42)
    m.set(c, 'c')
    assert len(m._data) == 1
    assert m.get(c) == 'c'

    with raises(KeyError):
        m.get(np.ones(42))

    del c
    assert_empty_after_gc_collect(m._data)

    # Check that creating and dropping numpy arrays with potentially the same
    # object id will not cause the map to get confused.
    def get_set_get_collect(m, i):
        a = np.ones(42)
        with raises(KeyError):
            m.get(a)
        m.set(a, i)
        assert m.get(a) == i
        return id(a)

    unique_ids = set([get_set_get_collect(m, i) for i in range(1000)])
    if platform.python_implementation() == 'CPython':
        # On CPython (at least) the same id is often reused many times for the
        # temporary arrays created under the local scope of the
        # get_set_get_collect function without causing any spurious lookups /
        # insertions in the map.
        assert len(unique_ids) < 100

def test_weak_array_key_map_no_pickling():
    m = _WeakArrayKeyMap()
    with raises(pickle.PicklingError):
        pickle.dumps(m)


text:
<!doctype html>

		<meta charset="utf-8">
		<title>Anisha Subberwal</title>
		<link rel="stylesheet" href="aboutme.css">

Life Enthusiast

Anisha Subberwal

 <button class="dropbtn">Menu</button>

    	About Me

    	Coding Class

    	Trend Analyzing

All About Me

		<link rel="stylesheet" href="aboutme.css">

My name is Anisha Subberwal. I'm 19 years old. I'm majoring in Communication Design. And, you're probably wondering what that entails. Its basically Digital Design, so I learn the basics and art of typography and graphic design but I also get to learn web design, User Experience and User Interface Design. Studying User Experience design is exactly what it is, desigining how the user navigates through the website/app and User Interface is just the aesthetic of it. Sorry, for boring you with some web terminology. My minor is Fashion Communication, I know... its a lot of communicating. Thats like fashion advertising, branding and merchandising. I currently intern at Jimmy Choo as a visual merchandiser, so I'm gaining a lot of work experience in my minor. I'm still trying to find a middle ground with everything I'm studying.
A little more about me and less about my academics, I'm basically a foreigner everywhere I go. I moved from India which is my birthplace halfway through 4th grade. Then I moved to Indonesia for about 2 years and I went to the American International School. After that I moved to Singapore for about 2 and a half years and I went to a British School. Two schools actually. And then, I moved to Taiwan where I stayed about 11 months and switched back to the American system. And again there was another move before sophomore year of my high school, I moved to Hong Kong where my family currently resides. We're coming on to our 5th year and that seems amazing considering our moving history.

Where are you from?
Wheres home for you?

Probably two of the hardest questions I have to answer. When I say Hong Kong, people usually say "Where are you really from? You don't look Chinese." I feel like I'm in that scene of Mean Girls. But when I moved out of India when I was really young, whenever I visit I feel like I'm in a foreign place. It just doesn't feel like home.