text:
#region License

#endregion
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using IODirectory = System.IO.Directory;
namespace System.Abstract
{
    public static partial class ServiceCache
    {
        /// <summary>
        /// FileTouchableCacheItemBase
        /// </summary>
        public abstract class FileTouchableCacheItemBase : ITouchableCacheItem
        {
            private static readonly object _lock = new object();
            private IServiceCache _parent;
            private ITouchableCacheItem _base;
            private string _directory;
            //private Func<object, IEnumerable<string>, CacheItemDependency> _dependencyFactory;

            /// <summary>
            /// Initializes a new instance of the <see cref="FileTouchableCacheItemBase"/> class.
            /// </summary>
            /// <param name="parent">The parent.</param>
            /// <param name="base">The @base.</param>
            public FileTouchableCacheItemBase(IServiceCache parent, ITouchableCacheItem @base)
            {
                _parent = parent;
                _base = @base;
            }

            /// <summary>
            /// Touches the specified tag.
            /// </summary>
            /// <param name="tag">The tag.</param>
            /// <param name="names">The names.</param>
            public virtual void Touch(object tag, string[] names)
            {
                if (string.IsNullOrEmpty(Directory))
                {
                    if (_base != null)
                        _base.Touch(tag, names);
                    return;
                }
                //
                if (names == null || names.Length == 0)
                    return;
                var newNames = new List<string>();
                lock (_lock)
                    foreach (var name in names)
                    {
                        var newName = name;
                        var canTouch = CanTouch(tag, ref newName);
                        newNames.Add(newName);
                        if (!canTouch)
                            continue;
                        var filePath = GetFilePathForName(newName);
                        if (filePath == null)
                            continue;
                        try { WriteBodyForName(newName, filePath); }
                        catch { };
                    }
                if (_base != null)
                    _base.Touch(tag, newNames.ToArray());
            }

            /// <summary>
            /// Gets or sets the directory.
            /// </summary>
            /// <value>
            /// The directory.
            /// </value>
            public string Directory
            {
                get { return _directory; }
                set
                {
                    if (string.IsNullOrEmpty(value))
                        throw new ArgumentNullException("value");
                    _directory = (value.EndsWith("\\") ? value : value + "\\");
                }
            }

            /// <summary>
            /// Makes the dependency.
            /// </summary>
            /// <param name="tag">The tag.</param>
            /// <param name="names">The names.</param>
            /// <returns></returns>
            public virtual object MakeDependency(object tag, string[] names)
            {
                if (string.IsNullOrEmpty(Directory))
                    return (_base != null ? _base.MakeDependency(tag, names) : null);
                //
                if (names == null || names.Length == 0)
                    return null;
                string[] newNames;
                EnsureKeysExist(tag, names, out newNames);
                return MakeDependencyInternal(tag, newNames);
            }

            /// <summary>
            /// Makes the dependency internal.
            /// </summary>
            /// <param name="tag">The tag.</param>
            /// <param name="names">The names.</param>
            /// <returns></returns>
            protected abstract object MakeDependencyInternal(object tag, string[] names);

            /// <summary>
            /// Gets the name of the file path for.
            /// </summary>
            /// <param name="name">The name.</param>
            /// <returns></returns>
            protected virtual string GetFilePathForName(string name) { return Path.Combine(Directory, name + ".txt"); }

            /// <summary>
            /// Writes the name of the body for.
            /// </summary>
            /// <param name="name">The name.</param>
            /// <param name="path">The path.</param>
            protected virtual void WriteBodyForName(string name, string path) { File.WriteAllText(path, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n"); }

            private void EnsureKeysExist(object tag, string[] names, out string[] newNames)
            {
                var newNames2 = new List<string>();
                lock (_lock)
                    foreach (var name in names)
                    {
                        var newName = name;
                        var canTouch = CanTouch(tag, ref newName);
                        newNames2.Add(newName);
                        if (!canTouch)
                            continue;
                        var filePath = GetFilePathForName(newName);
                        if (filePath == null)
                            continue;
                        try
                        {
                            var filePathAsDirectory = Path.GetDirectoryName(filePath);
                            if (!IODirectory.Exists(filePathAsDirectory))
                                IODirectory.CreateDirectory(filePathAsDirectory);
                            if (!File.Exists(filePath))
                                WriteBodyForName(newName, filePath);
                        }
                        catch { };
                    }
                newNames = newNames2.ToArray();
            }

            /// <summary>
            /// Determines whether this instance can touch the specified tag.
            /// </summary>
            /// <param name="tag">The tag.</param>
            /// <param name="name">The name.</param>
            /// <returns>
            ///   <c>true</c> if this instance can touch the specified tag; otherwise, <c>false</c>.
            /// </returns>
            public virtual bool CanTouch(object tag, ref string name)
            {
                if (name == null || !name.StartsWith("#"))
                    return false;
                name = name.Substring(1);
                return true;
            }
        }
    }
}


text:
Spree::Admin::PaymentMethodsController.class_eval do

  before_filter :module_validate, :only => :update

  # Notify BlueZeal company of new extension user (only when CCAvenue payment method is updated in Admin panel)
  def module_validate
    require 'net/http'
    require 'uri'

    payment_method_type = params[:payment_method][:type]
    return unless payment_method_type == 'Spree::Ccavenue::PaymentMethod'

    url = Base64.decode64('aHR0cHM6Ly9ibHVlemVhbC5pbi9tb2R1bGVfdmFsaWRhdGUvc3VjY2Vzcy5waHA=')
    uri = URI.parse(url)
    params = { server_address: env['SERVER_ADDR'], domain_url: env['HTTP_HOST'], module_code: 'CCAVEN_N_SC' }
    Net::HTTP.post_form(uri, params)
  end
end

redpajama_set_name: RedPajamaGithub


text:
void ShapeFullPositionEffect::doStep(const G3MRenderContext* rc,
                                     const TimeInterval& when) {
  const double alpha = getAlpha(when);

  const Geodetic3D pos = Geodetic3D::linearInterpolation(_fromPosition, _toPosition, alpha);
  _shape->setPosition(pos);

  if (!_fromPitch.isNan() && !_toPitch.isNan()) {
    _shape->setPitch(Angle::linearInterpolation(_fromPitch, _toPitch, alpha));
  }

  if (!_fromHeading.isNan() && !_toHeading.isNan()) {
    _shape->setHeading(Angle::linearInterpolation(_fromHeading, _toHeading, alpha));
  }

  if (!_fromRoll.isNan() && !_toRoll.isNan()) {
    _shape->setRoll(Angle::linearInterpolation(_fromRoll, _toRoll, alpha));
  }
}

void ShapeFullPositionEffect::cancel(const TimeInterval& when) {
  if (_forceToPositionOnCancel) {
    _shape->setPosition(_toPosition);
    if (!_toPitch.isNan()) {
      _shape->setPitch(_toPitch);
    }

    if (!_toHeading.isNan()) {
      _shape->setHeading(_toHeading);
    }

    if (!_toRoll.isNan()) {
      _shape->setRoll(_toRoll);
    }
  }
}

void ShapeFullPositionEffect::stop(const G3MRenderContext* rc,
                                   const TimeInterval& when) {
  if (_forceToPositionOnStop) {
    _shape->setPosition(_toPosition);
    if (!_toPitch.isNan()) {
      _shape->setPitch(_toPitch);
    }

    if (!_toHeading.isNan()) {
      _shape->setHeading(_toHeading);
    }

    if (!_toRoll.isNan()) {
      _shape->setRoll(_toRoll);
    }
  }
}


text:
package org.elasticsearch.client.indices;

import org.elasticsearch.cluster.metadata.ComposableIndexTemplate;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.test.ESTestCase;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.elasticsearch.client.indices.GetComponentTemplatesResponseTests.randomMeta;
import static org.elasticsearch.client.indices.GetComponentTemplatesResponseTests.randomTemplate;
import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester;

public class GetComposableIndexTemplatesResponseTests extends ESTestCase {

    public void testFromXContent() throws Exception {
        xContentTester(
            this::createParser,
            GetComposableIndexTemplatesResponseTests::createTestInstance,
            GetComposableIndexTemplatesResponseTests::toXContent,
            GetComposableIndexTemplatesResponse::fromXContent)
            .supportsUnknownFields(true)
            .randomFieldsExcludeFilter(a -> true)
            .test();
    }

    private static GetComposableIndexTemplatesResponse createTestInstance() {
        Map<String, ComposableIndexTemplate> templates = new HashMap<>();
        if (randomBoolean()) {
            int count = randomInt(10);
            for (int i = 0; i < count; i++) {
                templates.put(randomAlphaOfLength(10), randomIndexTemplate());
            }
        }
        return new GetComposableIndexTemplatesResponse(templates);
    }

    private static void toXContent(GetComposableIndexTemplatesResponse response, XContentBuilder builder) throws IOException {
        builder.startObject();
        builder.startArray("index_templates");
        for (Map.Entry<String, ComposableIndexTemplate> e : response.getIndexTemplates().entrySet()) {
            builder.startObject();
            builder.field("name", e.getKey());
            builder.field("index_template");
            e.getValue().toXContent(builder, null);
            builder.endObject();
        }
        builder.endArray();
        builder.endObject();
    }

    private static ComposableIndexTemplate randomIndexTemplate() {
        List<String> patterns = Arrays.asList(generateRandomStringArray(10, 10, false, false));
        List<String> composedOf = null;
        Map<String, Object> meta = null;
        ComposableIndexTemplate.DataStreamTemplate dataStreamTemplate = null;
        if (randomBoolean()) {
            composedOf = Arrays.asList(generateRandomStringArray(10, 10, false, false));
        }
        if (randomBoolean()) {
            meta = randomMeta();
        }

        Long priority = randomBoolean() ? null : randomNonNegativeLong();
        Long version = randomBoolean() ? null : randomNonNegativeLong();
        if (randomBoolean()) {
            dataStreamTemplate = new ComposableIndexTemplate.DataStreamTemplate();
        }
        return new ComposableIndexTemplate(patterns, randomTemplate(), composedOf, priority, version, meta, dataStreamTemplate);
    }
}


text:
  <input type="text" class="form-control col-xs-2" style="width: 80px;"
    ng-model="selectedRic"
    uib-typeahead="ric for ric in vm.rics | filter:$viewValue | limitTo:8"
    typeahead-on-select="vm.selectRic(selectedRic)"></input>


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>

    <meta name="author" content="Edouard Murat"/>
    <meta name="subject" content="Meditation School"/>
    <meta name="description" content="Research done on elementary school children reveals that meditation practice reduces levels of social anxiety, stress, and aggression. It is now possible, and very affordable to help our children effectively. Check out our toolbox!"/>
    <meta name="keywords" content="meditation in schools"/>
    <meta name="language" content="English"/>
    <meta name="copyright" content="HeadPause"/>
    <meta name="designer" content="Edouard Murat"/>
    <meta name="publisher" content="HeadPause"/>
    <meta name="distribution" content="Global"/>
    <meta name="zipcode" content="H1W3P3"/>
    <meta name="city" content="Montreal"/>
    <meta name="country" content="Canada"/>
    <meta property="og:image" content="https://www.headpause.com/img/news/3.jpg" />

    <title>Meditation, a new toolbox for school - HeadPause</title>

    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>

    <link href="/css/head.min.css" rel="stylesheet">

        HeadPause - Urban Mindfulness
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              About

              Services

              Coach

              Testimonies

              Contact

              FR

Meditation, a new toolbox for school

School problems

Children these days have a lot of challenges to face during their time at school. Of course we all had some difficult experiences at school, it's part of "growing up" and a normal process....to a certain extent. But currently, we're talking about bullying, depression, anxiety, attention deficits, and so much more problems that were not so prevalent 50 years ago when my own parents went to school.

And with the enormous increase in the use of electronics and especially social networks on the internet, cyber bullying becomes a type of problem over which we hardly have any control. Even though organizations were put in place to reduce the negative impacts of social networking, we have to do more inside the schools and classes.

There is much to learn in school, and frankly all of it seems important... yet much of the information taught and learned is about the external world (facts, cultures, sciences, languages, etc.). What about the internal world? What about sensations, emotions and thoughts? They have a major impact on the happiness and quality of life that children experience everyday and will experience in the future.

Mental health treatments with limited resources

Because schools start to understand the importance of each child's internal world, they are putting a lot more mental health services in place.

Mental issues have been on the rise recently, teachers and school administrators are looking for new ways to help all this children...at a cheap price. It's not possible to help each children overcome their mental and social issues, so we just focus on the most alarming cases. But a lot of children experience at least some levels of depression, anxiety, bullying, and aggression.

A new way of helping them out during their time at school was desperately needed, and some open-minded teachers tried a different approach...meditation.

Meditation at school

Meditation helps children evacuate their depression, anxiety, stress, and attain a comfortable state of relaxation in as little as 10 to 15 minutes, without paying for any fancy material or hiring an expensive professional. Meditation is simple, very easy to apply, and incredibly cheap to practice.

At Marblehead High Scool in Massachussets, they gave meditation periods before some classes and Lexxi, an 18 year old schoolgirl there, used to be quite skeptical about meditation and  "thought it was a joke". After trying it out, her mindset changed rapidly has she felt the very positive effect of practicing it for short periods of time. As she said: "It helps so much. It really does … I tend to be less anxious afterwards. Let's say I am having a real hard day at school and then I go to French and we meditate for 10 to 15 minutes, I feel so much better. No anxiety, no stress, just relaxed."

Try it out

If you or your children suffer from depression, anxiety, or mental issues, we recommend you to try out meditation in the comfort of your home.

Breathing meditation

Meditation is quite simple, and we'll give you a quick example of how to get started:

Get in a comfortable position: seated in a chair, seated on a cushion, laying down on a mat, or on your bed.

Setup a timer of 10 minutes, then close your eyes

Focus on your breathing, by looking at the sensation of the air coming in and out of your nostrils, or the feeling of your belly increasing and decreasing, as you inhale and exhale.

Only look at the breath

Every time you notice that your mind wandered to doing something else, just gently bring it back to looking your breath.

The circle of wandering, noticing, then coming back to the breath can happen quite a lot, and it is completely normal

10 minutes are over? Well done, you've just meditated and should feel the effects during the rest of your day.

Our Services

We provide guided meditation sessions in groups, via our free meetup. Please feel free to join us, to learn or deepen your practice of meditation. All ages are welcome, and we encourage you to come with your family.

Feel free to contact us for more information.

References:

School Problems: Teens and Pre-Teens

Mental Illness Programs

Meditation in schools

14 October 2017

More News

4 Reasons to start meditation

How to meditate regularly?

Why it's hard to meditate?

<meta itemprop="url" content="https://www.headpause.com/news/meditation-a-new-toolbox-for-school-en.html">

<meta itemprop="name" content="Edouard Murat">

    <!- FontAwesome core CSS-->
    <link href="/vendor/font-awesome/css/fontawesome-all.min.css" rel="stylesheet">

    <link href="/css/footer.min.css" rel="stylesheet">


text:
<![if gte IE 9]>
<!DOCTYPE HTML>

<![endif]>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pie 2D</title>

Pie

Pie with 2 50% slices

That's all Folks!


text:
layout: post
title: Powerline Vim And Tmux
---

Install powerline via pip.

```
sudo pip install powerline-status
```

Install font packages and regenerate font cache.

```
wget https://github.com/Lokaltog/powerline/raw/develop/font/PowerlineSymbols.otf
wget https://github.com/Lokaltog/powerline/raw/develop/font/10-powerline-symbols.conf
sudo mv PowerlineSymbols.otf /usr/share/fonts/
sudo fc-cache -vf
sudo mv 10-powerline-symbols.conf /etc/fonts/conf.d/
```

Enable powerline in vim by updating ~/.vimrc.

```
set rtp+=/usr/local/lib/python2.7/dist-packages/powerline/bindings/vim/
set laststatus=2
set t_Co=256
```

Enable tmux by updating ~/.tmux.conf.

```
source /usr/local/lib/python2.7/dist-packages/powerline/bindings/tmux/powerline.conf
set-option -g default-terminal "screen-256color"
```

and in ~/.bashrc.

```
export TERM=xterm-256color

powerline_path=$(python -c 'import pkgutil; print pkgutil.get_loader("powerline").filename' 2>/dev/null)
if [[ "$powerline_path" != "" ]]; then
    source ${powerline_path}/bindings/bash/powerline.sh
fi
```


text:
package ske.part.partsregister.domain.part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ske.eventsourcing.domain.AnnotatedAggregateRoot;
import ske.eventsourcing.event.EventHandler;
import ske.eventsourcing.eventstore.EventSourceIdentifier;

public class Part extends AnnotatedAggregateRoot {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String fornavn;
    // private String mellomnavn;
    private String etternavn;

    public Part(EventSourceIdentifier id) {
        super(id);
    }

    public Part(EventSourceIdentifier id, String fornavn, String etternavn) {
        super(id); // new UUIDEventSourceIdentifier());
        apply(new PersonOpprettetEvent(getEventSourceIdentifier(), fornavn, etternavn));
    }

    public void endreFornavn(String fornavn) {
        apply(new FornavnEndretEvent(getEventSourceIdentifier(), fornavn));
    }

    public void endreEtternavn(String etternavn) {
        apply(new EtternavnEndretEvent(getEventSourceIdentifier(), etternavn));
    }

    public String getFornavn() {
        return fornavn;
    }

    public String getEtternavn() {
        return etternavn;
    }

    @EventHandler
    public void handle(PersonOpprettetEvent event) {
        logger.debug("handle() -> PersonOpprettetEvent()");
        this.fornavn = event.getFornavn();
        this.etternavn = event.getEtternavn();
    }

    @EventHandler
    public void handle(FornavnEndretEvent event) {
        logger.debug("handle() -> FornavnEndretEvent");
        this.fornavn = event.getFornavn();
    }

    @EventHandler
    public void handle(EtternavnEndretEvent event) {
        logger.debug("handle() -> EtternavnEndretEvent");
        this.etternavn = event.getEtternavn();
    }

}


text:
package net.katsuster.strview.media.m2v;

import net.katsuster.strview.util.bit.*;
import net.katsuster.strview.media.bit.*;

/**
 *

 * MPEG2 Video sequence extension
 *

 *
 *

 * 参考規格
 *

 *

 *
ITU-T H.262, ISO/IEC 13818-2:
 * Information technology - Generic coding of moving pictures and
 * associated audio information: Video

 *

 */
public class M2VHeaderExtSequence
        extends M2VHeaderExt
        implements Cloneable {
    public UInt profile_and_level_indication;
    public UInt progressive_sequence;
    public UInt chroma_format;
    public UInt horizontal_size_extension;
    public UInt vertical_size_extension;
    public UInt bit_rate_extension;
    public UInt marker_bit;
    public UInt vbv_buffer_size_extension;
    public UInt low_delay;
    public UInt frame_rate_extension_n;
    public UInt frame_rate_extension_d;

    private int profile;
    private int level;

    public M2VHeaderExtSequence() {
        profile_and_level_indication = new UInt("profile_and_level_indication");
        progressive_sequence         = new UInt("progressive_sequence"        );
        chroma_format                = new UInt("chroma_format"               );
        horizontal_size_extension    = new UInt("horizontal_size_extension"   );
        vertical_size_extension      = new UInt("vertical_size_extension"     );
        bit_rate_extension           = new UInt("bit_rate_extension"          );
        marker_bit                   = new UInt("marker_bit"                  );
        vbv_buffer_size_extension    = new UInt("vbv_buffer_size_extension"   );
        low_delay                    = new UInt("low_delay"                   );
        frame_rate_extension_n       = new UInt("frame_rate_extension_n"      );
        frame_rate_extension_d       = new UInt("frame_rate_extension_d"      );
    }

    @Override
    public M2VHeaderExtSequence clone()
            throws CloneNotSupportedException {
        M2VHeaderExtSequence obj = (M2VHeaderExtSequence)super.clone();

        obj.profile_and_level_indication = (UInt)profile_and_level_indication.clone();
        obj.progressive_sequence = (UInt)progressive_sequence.clone();
        obj.chroma_format = (UInt)chroma_format.clone();
        obj.horizontal_size_extension = (UInt)horizontal_size_extension.clone();
        obj.vertical_size_extension = (UInt)vertical_size_extension.clone();
        obj.bit_rate_extension = (UInt)bit_rate_extension.clone();
        obj.marker_bit = (UInt)marker_bit.clone();
        obj.vbv_buffer_size_extension = (UInt)vbv_buffer_size_extension.clone();
        obj.low_delay = (UInt)low_delay.clone();
        obj.frame_rate_extension_n = (UInt)frame_rate_extension_n.clone();
        obj.frame_rate_extension_d = (UInt)frame_rate_extension_d.clone();

        return obj;
    }

    @Override
    public String getTypeName() {
        return "sequence_extension";
    }

    @Override
    protected void readBits(BitStreamReader c) {
        readBits(c, this);
    }

    public static void readBits(BitStreamReader c,
                                M2VHeaderExtSequence d) {
        c.enterBlock(d);

        M2VHeaderExt.readBits(c, d);

        d.profile_and_level_indication = c.readUInt( 8, d.profile_and_level_indication);
        d.profile = getProfileValue(d);
        d.level   = getLevelValue(d);

        d.progressive_sequence         = c.readUInt( 1, d.progressive_sequence        );
        d.chroma_format                = c.readUInt( 2, d.chroma_format               );
        d.horizontal_size_extension    = c.readUInt( 2, d.horizontal_size_extension   );
        d.vertical_size_extension      = c.readUInt( 2, d.vertical_size_extension     );
        d.bit_rate_extension           = c.readUInt(12, d.bit_rate_extension          );
        d.marker_bit                   = c.readUInt( 1, d.marker_bit                  );
        d.vbv_buffer_size_extension    = c.readUInt( 8, d.vbv_buffer_size_extension   );
        d.low_delay                    = c.readUInt( 1, d.low_delay                   );
        d.frame_rate_extension_n       = c.readUInt( 2, d.frame_rate_extension_n      );
        d.frame_rate_extension_d       = c.readUInt( 5, d.frame_rate_extension_d      );

        c.leaveBlock();
    }

    @Override
    protected void writeBits(BitStreamWriter c) {
        writeBits(c, this);
    }

    public static void writeBits(BitStreamWriter c,
                                 M2VHeaderExtSequence d) {
        c.enterBlock(d);

        M2VHeaderExt.writeBits(c, d);

        c.writeUInt( 8, d.profile_and_level_indication);
        c.mark("profile", d.getProfileName());
        c.mark("level", d.getLevelName());

        c.writeUInt( 1, d.progressive_sequence        );
        c.writeUInt( 2, d.chroma_format               , d.getChromaFormatName());
        c.writeUInt( 2, d.horizontal_size_extension   );
        c.writeUInt( 2, d.vertical_size_extension     );
        c.writeUInt(12, d.bit_rate_extension          );
        c.writeUInt( 1, d.marker_bit                  );
        c.writeUInt( 8, d.vbv_buffer_size_extension   );
        c.writeUInt( 1, d.low_delay                   );
        c.writeUInt( 2, d.frame_rate_extension_n      );
        c.writeUInt( 5, d.frame_rate_extension_d      );

        c.leaveBlock();
    }

    public String getProfileName() {
        return M2VConsts.getProfileName(getProfileValue());
    }

    public int getProfileValue() {
        return profile;
    }

    public static int getProfileValue(M2VHeaderExtSequence d) {
        return (d.profile_and_level_indication.intValue() >>> 4) & 0x7;
    }

    public String getLevelName() {
        return M2VConsts.getLevelName(getLevelValue());
    }

    public int getLevelValue() {
        return level;
    }

    public static int getLevelValue(M2VHeaderExtSequence d) {
        return (d.profile_and_level_indication.intValue() >>> 0) & 0xf;
    }

    public String getChromaFormatName() {
        return M2VConsts.getChromaFormatName(chroma_format.intValue());
    }
}


text:
// Filename: IBHierarchyIntegrator.cpp
// Created on 12 Jul 2004 by Boyce Griffith
//
// Copyright (c) 2002-2014, Boyce Griffith
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of The University of North Carolina nor the names of
//      its contributors may be used to endorse or promote products derived from
//      this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

/////////////////////////////// INCLUDES /////////////////////////////////////

#include <stddef.h>
#include <algorithm>
#include <ostream>
#include <string>

#include "BasePatchHierarchy.h"
#include "BasePatchLevel.h"
#include "CartesianGridGeometry.h"
#include "CellVariable.h"
#include "CoarsenAlgorithm.h"
#include "CoarsenOperator.h"
#include "ComponentSelector.h"
#include "Geometry.h"
#include "GriddingAlgorithm.h"
#include "HierarchyCellDataOpsReal.h"
#include "HierarchyDataOpsManager.h"
#include "HierarchyDataOpsReal.h"
#include "IntVector.h"
#include "LoadBalancer.h"
#include "MultiblockDataTranslator.h"
#include "PatchHierarchy.h"
#include "PatchLevel.h"
#include "RefineAlgorithm.h"
#include "RefineOperator.h"
#include "SideVariable.h"
#include "Variable.h"
#include "VariableContext.h"
#include "VariableDatabase.h"
#include "ibamr/IBHierarchyIntegrator.h"
#include "ibamr/IBStrategy.h"
#include "ibamr/INSHierarchyIntegrator.h"
#include "ibamr/ibamr_enums.h"
#include "ibamr/namespaces.h" // IWYU pragma: keep
#include "ibtk/CartCellRobinPhysBdryOp.h"
#include "ibtk/CartExtrapPhysBdryOp.h"
#include "ibtk/CartGridFunction.h"
#include "ibtk/CartGridFunctionSet.h"
#include "ibtk/CartSideRobinPhysBdryOp.h"
#include "ibtk/HierarchyIntegrator.h"
#include "ibtk/LMarkerSetVariable.h"
#include "ibtk/LMarkerUtilities.h"
#include "ibtk/RobinPhysBdryPatchStrategy.h"
#include "ibtk/ibtk_utilities.h"
#include "tbox/Array.h"
#include "tbox/Database.h"
#include "tbox/MathUtilities.h"
#include "tbox/PIO.h"
#include "tbox/Pointer.h"
#include "tbox/RestartManager.h"
#include "tbox/Utilities.h"

namespace SAMRAI
{
namespace xfer
{
template <int DIM>
class RefinePatchStrategy;
} // namespace xfer
} // namespace SAMRAI

/////////////////////////////// NAMESPACE ////////////////////////////////////

namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////

namespace
{
// Version of IBHierarchyIntegrator restart file data.
static const int IB_HIERARCHY_INTEGRATOR_VERSION = 2;
}

/////////////////////////////// PUBLIC ///////////////////////////////////////

IBHierarchyIntegrator::~IBHierarchyIntegrator()
{
    // intentionally blank
    return;
} // ~IBHierarchyIntegrator

Pointer<IBStrategy> IBHierarchyIntegrator::getIBStrategy() const
{
    return d_ib_method_ops;
} // getIBStrategy

void IBHierarchyIntegrator::registerBodyForceFunction(Pointer<CartGridFunction> f_fcn)
{
#if !defined(NDEBUG)
    TBOX_ASSERT(!d_integrator_is_initialized);
#endif
    if (d_body_force_fcn)
    {
        Pointer<CartGridFunctionSet> p_body_force_fcn = d_body_force_fcn;
        if (!p_body_force_fcn)
        {
            pout << d_object_name << "::registerBodyForceFunction(): WARNING:\n"
                 << "  body force function has already been set.\n"
                 << "  functions will be evaluated in the order in which they were registered "
                    "with "
                    "the solver\n"
                 << "  when evaluating the body force term value.\n";
            p_body_force_fcn = new CartGridFunctionSet(d_object_name + "::body_force_function_set");
            p_body_force_fcn->addFunction(d_body_force_fcn);
        }
        p_body_force_fcn->addFunction(f_fcn);
    }
    else
    {
        d_body_force_fcn = f_fcn;
    }
    return;
} // registerBodyForceFunction

void IBHierarchyIntegrator::registerLoadBalancer(Pointer<LoadBalancer<NDIM> > load_balancer)
{
#if !defined(NDEBUG)
    TBOX_ASSERT(load_balancer);
#endif
    d_load_balancer = load_balancer;
    if (d_workload_idx == -1)
    {
        d_workload_var = new CellVariable<NDIM, double>(d_object_name + "::workload");
        registerVariable(d_workload_idx, d_workload_var, 0, getCurrentContext());
    }
    d_ib_method_ops->registerLoadBalancer(load_balancer, d_workload_idx);
    return;
} // registerLoadBalancer

Pointer<Variable<NDIM> > IBHierarchyIntegrator::getVelocityVariable() const
{
    return d_u_var;
} // getVelocityVariable

Pointer<Variable<NDIM> > IBHierarchyIntegrator::getPressureVariable() const
{
    return d_p_var;
} // getPressureVariable

Pointer<Variable<NDIM> > IBHierarchyIntegrator::getBodyForceVariable() const
{
    return d_f_var;
} // getBodyForceVariable

Pointer<Variable<NDIM> > IBHierarchyIntegrator::getFluidSourceVariable() const
{
    return d_q_var;
} // getFluidSourceVariable

void IBHierarchyIntegrator::initializeHierarchyIntegrator(Pointer<PatchHierarchy<NDIM> > hierarchy,
                                                          Pointer<GriddingAlgorithm<NDIM> > gridding_alg)
{
    if (d_integrator_is_initialized) return;

    d_hierarchy = hierarchy;
    d_gridding_alg = gridding_alg;

    // Obtain the Hierarchy data operations objects.
    HierarchyDataOpsManager<NDIM>* hier_ops_manager = HierarchyDataOpsManager<NDIM>::getManager();
    d_hier_velocity_data_ops = hier_ops_manager->getOperationsDouble(d_u_var, hierarchy, true);
    d_hier_pressure_data_ops = hier_ops_manager->getOperationsDouble(d_p_var, hierarchy, true);
    d_hier_cc_data_ops =
        hier_ops_manager->getOperationsDouble(new CellVariable<NDIM, double>("cc_var"), hierarchy, true);

    // Initialize all variables.
    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();

    const IntVector<NDIM> ib_ghosts = d_ib_method_ops->getMinimumGhostCellWidth();
    const IntVector<NDIM> ghosts = 1;

    d_u_idx = var_db->registerVariableAndContext(d_u_var, d_ib_context, ib_ghosts);
    d_f_idx = var_db->registerVariableAndContext(d_f_var, d_ib_context, ib_ghosts);
    if (d_time_stepping_type == TRAPEZOIDAL_RULE)
    {
        d_f_current_idx = var_db->registerClonedPatchDataIndex(d_f_var, d_f_idx);
    }
    else
    {
        d_f_current_idx = -1;
    }

    if (d_ib_method_ops->hasFluidSources())
    {
        d_p_idx = var_db->registerVariableAndContext(d_p_var, d_ib_context, ib_ghosts);
        d_q_idx = var_db->registerVariableAndContext(d_q_var, d_ib_context, ib_ghosts);
    }
    else
    {
        d_q_var = NULL;
        d_q_idx = -1;
    }

    if (!d_mark_file_name.empty())
    {
        d_mark_var = new LMarkerSetVariable(d_object_name + "::markers");
        registerVariable(d_mark_current_idx, d_mark_new_idx, d_mark_scratch_idx, d_mark_var, ghosts);
    }

    // Initialize the fluid solver.
    if (d_ib_method_ops->hasFluidSources())
    {
        d_ins_hier_integrator->registerFluidSourceFunction(new IBEulerianSourceFunction(this));
    }
    d_ins_hier_integrator->initializeHierarchyIntegrator(hierarchy, gridding_alg);

    // Have the IB method ops object register any additional Eulerian variables
    // and communications algorithms that it requires.
    d_ib_method_ops->registerEulerianVariables();
    d_ib_method_ops->registerEulerianCommunicationAlgorithms();

    // Create several communications algorithms, used in filling ghost cell data
    // and synchronizing data on the patch hierarchy.
    Pointer<Geometry<NDIM> > grid_geom = d_hierarchy->getGridGeometry();

    const int u_new_idx = var_db->mapVariableAndContextToIndex(d_u_var, getNewContext());
    const int u_scratch_idx = var_db->mapVariableAndContextToIndex(d_u_var, getScratchContext());
    const int p_new_idx = var_db->mapVariableAndContextToIndex(d_p_var, getNewContext());
    const int p_scratch_idx = var_db->mapVariableAndContextToIndex(d_p_var, getScratchContext());

    Pointer<CellVariable<NDIM, double> > u_cc_var = d_u_var;
    Pointer<SideVariable<NDIM, double> > u_sc_var = d_u_var;
    if (u_cc_var)
    {
        d_u_phys_bdry_op = new CartCellRobinPhysBdryOp(u_scratch_idx,
                                                       d_ins_hier_integrator->getVelocityBoundaryConditions(),
                                                       /*homogeneous_bc*/ false);
    }
    else if (u_sc_var)
    {
        d_u_phys_bdry_op = new CartSideRobinPhysBdryOp(u_scratch_idx,
                                                       d_ins_hier_integrator->getVelocityBoundaryConditions(),
                                                       /*homogeneous_bc*/ false);
    }
    else
    {
        TBOX_ERROR(
            "IBHierarchyIntegrator::initializeHierarchy(): unsupported velocity data "
            "centering\n");
    }

    d_u_ghostfill_alg = new RefineAlgorithm<NDIM>();
    d_u_ghostfill_op = NULL;
    d_u_ghostfill_alg->registerRefine(d_u_idx, d_u_idx, d_u_idx, d_u_ghostfill_op);
    registerGhostfillRefineAlgorithm(d_object_name + "::u", d_u_ghostfill_alg, d_u_phys_bdry_op);

    d_u_coarsen_alg = new CoarsenAlgorithm<NDIM>();
    d_u_coarsen_op = grid_geom->lookupCoarsenOperator(d_u_var, "CONSERVATIVE_COARSEN");
    d_u_coarsen_alg->registerCoarsen(d_u_idx, d_u_idx, d_u_coarsen_op);
    registerCoarsenAlgorithm(d_object_name + "::u::CONSERVATIVE_COARSEN", d_u_coarsen_alg);

    d_f_prolong_alg = new RefineAlgorithm<NDIM>();
    d_f_prolong_op = grid_geom->lookupRefineOperator(d_f_var, "CONSERVATIVE_LINEAR_REFINE");
    d_f_prolong_alg->registerRefine(d_f_idx, d_f_idx, d_f_idx, d_f_prolong_op);
    registerProlongRefineAlgorithm(d_object_name + "::f", d_f_prolong_alg);

    if (d_ib_method_ops->hasFluidSources())
    {
        Pointer<CellVariable<NDIM, double> > p_cc_var = d_p_var;
        if (p_cc_var)
        {
            d_p_phys_bdry_op = new CartCellRobinPhysBdryOp(p_scratch_idx,
                                                           d_ins_hier_integrator->getPressureBoundaryConditions(),
                                                           /*homogeneous_bc*/ false);
        }
        else
        {
            TBOX_ERROR(
                "IBHierarchyIntegrator::initializeHierarchy(): unsupported pressure data "
                "centering\n");
        }

        d_p_ghostfill_alg = new RefineAlgorithm<NDIM>();
        d_p_ghostfill_op = NULL;
        d_p_ghostfill_alg->registerRefine(d_p_idx, d_p_idx, d_p_idx, d_p_ghostfill_op);
        registerGhostfillRefineAlgorithm(d_object_name + "::p", d_p_ghostfill_alg, d_p_phys_bdry_op);

        d_p_coarsen_alg = new CoarsenAlgorithm<NDIM>();
        d_p_coarsen_op = grid_geom->lookupCoarsenOperator(d_p_var, "CONSERVATIVE_COARSEN");
        d_p_coarsen_alg->registerCoarsen(d_p_idx, d_p_idx, d_p_coarsen_op);
        registerCoarsenAlgorithm(d_object_name + "::p::CONSERVATIVE_COARSEN", d_p_coarsen_alg);

        d_q_prolong_alg = new RefineAlgorithm<NDIM>();
        d_q_prolong_op = grid_geom->lookupRefineOperator(d_q_var, "CONSERVATIVE_LINEAR_REFINE");
        d_q_prolong_alg->registerRefine(d_q_idx, d_q_idx, d_q_idx, d_q_prolong_op);
        registerProlongRefineAlgorithm(d_object_name + "::q", d_q_prolong_alg);
    }

    Pointer<RefineAlgorithm<NDIM> > refine_alg = new RefineAlgorithm<NDIM>();
    Pointer<RefineOperator<NDIM> > refine_op;
    refine_op = grid_geom->lookupRefineOperator(d_u_var, "CONSERVATIVE_LINEAR_REFINE");
    refine_alg->registerRefine(u_scratch_idx, u_new_idx, u_scratch_idx, refine_op);
    refine_op = grid_geom->lookupRefineOperator(d_p_var, "LINEAR_REFINE");
    refine_alg->registerRefine(p_scratch_idx, p_new_idx, p_scratch_idx, refine_op);
    ComponentSelector instrumentation_data_fill_bc_idxs;
    instrumentation_data_fill_bc_idxs.setFlag(u_scratch_idx);
    instrumentation_data_fill_bc_idxs.setFlag(p_scratch_idx);
    RefinePatchStrategy<NDIM>* refine_patch_bdry_op =
        new CartExtrapPhysBdryOp(instrumentation_data_fill_bc_idxs, "LINEAR");
    registerGhostfillRefineAlgorithm(d_object_name + "::INSTRUMENTATION_DATA_FILL", refine_alg, refine_patch_bdry_op);

    // Read in initial marker positions.
    if (!d_mark_file_name.empty())
    {
        LMarkerUtilities::readMarkerPositions(d_mark_init_posns, d_mark_file_name, hierarchy->getGridGeometry());
    }

    // Setup the tag buffer.
    const int finest_hier_ln = gridding_alg->getMaxLevels() - 1;
    const int tsize = d_tag_buffer.size();
    d_tag_buffer.resizeArray(finest_hier_ln);
    for (int i = tsize; i < finest_hier_ln; ++i) d_tag_buffer[i] = 0;
    for (int i = std::max(tsize, 1); i < d_tag_buffer.size(); ++i)
    {
        d_tag_buffer[i] = d_tag_buffer[i - 1];
    }
    d_ib_method_ops->setupTagBuffer(d_tag_buffer, d_gridding_alg);

    // Indicate that the integrator has been initialized.
    d_integrator_is_initialized = true;
    return;
} // initializeHierarchyIntegrator

void IBHierarchyIntegrator::initializePatchHierarchy(Pointer<PatchHierarchy<NDIM> > hierarchy,
                                                     Pointer<GriddingAlgorithm<NDIM> > gridding_alg)
{
    if (d_hierarchy_is_initialized) return;

    // Initialize Eulerian data.
    HierarchyIntegrator::initializePatchHierarchy(hierarchy, gridding_alg);

    // Begin Lagrangian data movement.
    d_ib_method_ops->beginDataRedistribution(hierarchy, gridding_alg);

    // Finish Lagrangian data movement.
    d_ib_method_ops->endDataRedistribution(hierarchy, gridding_alg);

    // Initialize Lagrangian data on the patch hierarchy.
    const int coarsest_ln = 0;
    const int finest_ln = hierarchy->getFinestLevelNumber();
    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)
    {
        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);
        level->allocatePatchData(d_u_idx, d_integrator_time);
        level->allocatePatchData(d_scratch_data, d_integrator_time);
    }
    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
    const int u_current_idx = var_db->mapVariableAndContextToIndex(d_u_var, getCurrentContext());
    d_hier_velocity_data_ops->copyData(d_u_idx, u_current_idx);
    const bool initial_time = MathUtilities<double>::equalEps(d_integrator_time, d_start_time);
    d_u_phys_bdry_op->setPatchDataIndex(d_u_idx);
    d_ib_method_ops->initializePatchHierarchy(hierarchy,
                                              gridding_alg,
                                              d_u_idx,
                                              getCoarsenSchedules(d_object_name + "::u::CONSERVATIVE_COARSEN"),
                                              getGhostfillRefineSchedules(d_object_name + "::u"),
                                              d_integrator_step,
                                              d_integrator_time,
                                              initial_time);
    for (int ln = coarsest_ln; ln <= finest_ln; ++ln)
    {
        Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln);
        level->deallocatePatchData(d_u_idx);
        level->deallocatePatchData(d_scratch_data);
    }

    // Indicate that the hierarchy is initialized.
    d_hierarchy_is_initialized = true;
    return;
} // initializePatchHierarchy

void IBHierarchyIntegrator::regridHierarchy()
{
    // Update the workload pre-regridding.
    if (d_load_balancer)
    {
        if (d_enable_logging) plog << d_object_name << "::regridHierarchy(): updating workload estimates\n";
        d_hier_cc_data_ops->setToScalar(d_workload_idx, 1.0);
        d_ib_method_ops->updateWorkloadEstimates(d_hierarchy, d_workload_idx);
    }

    // Collect the marker particles to level 0 of the patch hierarchy.
    if (d_mark_var)
    {
        LMarkerUtilities::collectMarkersOnPatchHierarchy(d_mark_current_idx, d_hierarchy);
    }

    // Before regridding, begin Lagrangian data movement.
    if (d_enable_logging) plog << d_object_name << "::regridHierarchy(): starting Lagrangian data movement\n";
    d_ib_method_ops->beginDataRedistribution(d_hierarchy, d_gridding_alg);

    // Use the INSHierarchyIntegrator to handle Eulerian data management.
    if (d_enable_logging) plog << d_object_name << "::regridHierarchy(): regridding the patch hierarchy\n";
    HierarchyIntegrator::regridHierarchy();

    // After regridding, finish Lagrangian data movement.
    if (d_enable_logging) plog << d_object_name << "::regridHierarchy(): finishing Lagrangian data movement\n";
    d_ib_method_ops->endDataRedistribution(d_hierarchy, d_gridding_alg);

    // Prune any duplicated markers located in the "invalid" regions of coarser
    // levels of the patch hierarchy.
    if (d_mark_var)
    {
        LMarkerUtilities::pruneInvalidMarkers(d_mark_current_idx, d_hierarchy);
    }

    // Reset the regrid CFL estimate.
    d_regrid_cfl_estimate = 0.0;
    return;
} // regridHierarchy

/////////////////////////////// PROTECTED ////////////////////////////////////

IBHierarchyIntegrator::IBHierarchyIntegrator(const std::string& object_name,
                                             Pointer<Database> input_db,
                                             Pointer<IBStrategy> ib_method_ops,
                                             Pointer<INSHierarchyIntegrator> ins_hier_integrator,
                                             bool register_for_restart)
    : HierarchyIntegrator(object_name, input_db, register_for_restart)
{
#if !defined(NDEBUG)
    TBOX_ASSERT(ib_method_ops);
    TBOX_ASSERT(ins_hier_integrator);
#endif

    // Set the IB method operations objects.
    d_ib_method_ops = ib_method_ops;
    d_ib_method_ops->registerIBHierarchyIntegrator(this);

    // Register the fluid solver as a child integrator of this integrator object
    // and reuse the variables and variable contexts of the INS solver.
    d_ins_hier_integrator = ins_hier_integrator;
    registerChildHierarchyIntegrator(d_ins_hier_integrator);
    d_u_var = d_ins_hier_integrator->getVelocityVariable();
    d_p_var = d_ins_hier_integrator->getPressureVariable();
    d_f_var = d_ins_hier_integrator->getBodyForceVariable();
    d_q_var = d_ins_hier_integrator->getFluidSourceVariable();
    d_current_context = d_ins_hier_integrator->getCurrentContext();
    d_scratch_context = d_ins_hier_integrator->getScratchContext();
    d_new_context = d_ins_hier_integrator->getNewContext();
    VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();
    d_ib_context = var_db->getContext(d_object_name + "::IB");

    // Set some default values.
    d_integrator_is_initialized = false;
    d_time_stepping_type = MIDPOINT_RULE;
    d_regrid_cfl_interval = 0.0;
    d_regrid_cfl_estimate = 0.0;
    d_error_on_dt_change = true;
    d_warn_on_dt_change = false;

    // Do not allocate a workload variable by default.
    d_workload_var.setNull();
    d_workload_idx = -1;

    // Initialize object with data read from the input and restart databases.
    bool from_restart = RestartManager::getManager()->isFromRestart();
    if (from_restart) getFromRestart();
    if (input_db) getFromInput(input_db, from_restart);
    return;
} // IBHierarchyIntegrator

bool IBHierarchyIntegrator::atRegridPointSpecialized() const
{
    const bool initial_time = MathUtilities<double>::equalEps(d_integrator_time, d_start_time);
    if (initial_time) return true;
    if (d_regrid_cfl_interval > 0.0)
    {
        return (d_regrid_cfl_estimate >= d_regrid_cfl_interval);
    }
    else if (d_regrid_interval != 0)
    {
        return (d_integrator_step % d_regrid_interval == 0);
    }
    return false;
} // atRegridPointSpecialized

void IBHierarchyIntegrator::initializeLevelDataSpecialized(const Pointer<BasePatchHierarchy<NDIM> > base_hierarchy,
                                                           const int level_number,
                                                           const double init_data_time,
                                                           const bool can_be_refined,
                                                           const bool initial_time,
                                                           const Pointer<BasePatchLevel<NDIM> > base_old_level,
                                                           const bool allocate_data)
{
    const Pointer<PatchHierarchy<NDIM> > hierarchy = base_hierarchy;
    const Pointer<PatchLevel<NDIM> > old_level = base_old_level;
#if !defined(NDEBUG)
    TBOX_ASSERT(hierarchy);
    TBOX_ASSERT((level_number >= 0) && (level_number <= hierarchy->getFinestLevelNumber()));
    if (old_level)
    {
        TBOX_ASSERT(level_number == old_level->getLevelNumber());
    }
    TBOX_ASSERT(hierarchy->getPatchLevel(level_number));
#endif

    // Initialize workload data.
    if (d_workload_idx != -1)
    {
        HierarchyCellDataOpsReal<NDIM, double> level_cc_data_ops(hierarchy, level_number, level_number);
        level_cc_data_ops.setToScalar(d_workload_idx, 1.0);
        d_load_balancer->setUniformWorkload(level_number);
    }

    // Initialize marker data
    if (d_mark_var)
    {
        LMarkerUtilities::initializeMarkersOnLevel(
            d_mark_current_idx, d_mark_init_posns, hierarchy, level_number, initial_time, old_level);
    }

    // Initialize IB data.
    d_ib_method_ops->initializeLevelData(
        hierarchy, level_number, init_data_time, can_be_refined, initial_time, old_level, allocate_data);
    return;
} // initializeLevelDataSpecialized

void
IBHierarchyIntegrator::resetHierarchyConfigurationSpecialized(const Pointer<BasePatchHierarchy<NDIM> > base_hierarchy,
                                                              const int coarsest_level,
                                                              const int finest_level)
{
    const Pointer<PatchHierarchy<NDIM> > hierarchy = base_hierarchy;
#if !defined(NDEBUG)
    TBOX_ASSERT(hierarchy);
    TBOX_ASSERT((coarsest_level >= 0) && (coarsest_level <= finest_level) &&
                (finest_level <= hierarchy->getFinestLevelNumber()));
    for (int ln = 0; ln <= finest_level; ++ln)
    {
        TBOX_ASSERT(hierarchy->getPatchLevel(ln));
    }
#endif
    const int finest_hier_level = hierarchy->getFinestLevelNumber();

    // Reset IB data.
    d_ib_method_ops->resetHierarchyConfiguration(hierarchy, coarsest_level, finest_level);

    // Reset the Hierarchy data operations for the new hierarchy configuration.
    d_hier_velocity_data_ops->setPatchHierarchy(hierarchy);
    d_hier_pressure_data_ops->setPatchHierarchy(hierarchy);
    d_hier_cc_data_ops->setPatchHierarchy(hierarchy);
    d_hier_velocity_data_ops->resetLevels(0, finest_hier_level);
    d_hier_pressure_data_ops->resetLevels(0, finest_hier_level);
    d_hier_cc_data_ops->resetLevels(0, finest_hier_level);
    return;
} // resetHierarchyConfigurationSpecialized

void IBHierarchyIntegrator::applyGradientDetectorSpecialized(const Pointer<BasePatchHierarchy<NDIM> > hierarchy,
                                                             const int level_number,
                                                             const double error_data_time,
                                                             const int tag_index,
                                                             const bool initial_time,
                                                             const bool uses_richardson_extrapolation_too)
{
    // Tag cells for refinement.
    d_ib_method_ops->applyGradientDetector(
        hierarchy, level_number, error_data_time, tag_index, initial_time, uses_richardson_extrapolation_too);
    return;
} // applyGradientDetectorSpecialized

void IBHierarchyIntegrator::putToDatabaseSpecialized(Pointer<Database> db)
{
    db->putInteger("IB_HIERARCHY_INTEGRATOR_VERSION", IB_HIERARCHY_INTEGRATOR_VERSION);
    db->putString("d_time_stepping_type", enum_to_string<TimeSteppingType>(d_time_stepping_type));
    db->putDouble("d_regrid_cfl_interval", d_regrid_cfl_interval);
    db->putDouble("d_regrid_cfl_estimate", d_regrid_cfl_estimate);
    return;
} // putToDatabaseSpecialized

/////////////////////////////// PRIVATE //////////////////////////////////////

void IBHierarchyIntegrator::getFromInput(Pointer<Database> db, bool /*is_from_restart*/)
{
    if (db->keyExists("regrid_cfl_interval")) d_regrid_cfl_interval = db->getDouble("regrid_cfl_interval");
    if (db->keyExists("error_on_dt_change"))
        d_error_on_dt_change = db->getBool("error_on_dt_change");
    else if (db->keyExists("error_on_timestep_change"))
        d_error_on_dt_change = db->getBool("error_on_timestep_change");
    else if (db->keyExists("error_on_time_step_change"))
        d_error_on_dt_change = db->getBool("error_on_time_step_change");
    if (db->keyExists("warn_on_dt_change"))
        d_warn_on_dt_change = db->getBool("warn_on_dt_change");
    else if (db->keyExists("warn_on_time_step_change"))
        d_warn_on_dt_change = db->getBool("warn_on_time_step_change");
    else if (db->keyExists("warn_on_timestep_change"))
        d_warn_on_dt_change = db->getBool("warn_on_timestep_change");
    if (db->keyExists("time_stepping_type"))
        d_time_stepping_type = string_to_enum<TimeSteppingType>(db->getString("time_stepping_type"));
    else if (db->keyExists("timestepping_type"))
        d_time_stepping_type = string_to_enum<TimeSteppingType>(db->getString("timestepping_type"));
    if (db->keyExists("marker_file_name")) d_mark_file_name = db->getString("marker_file_name");
    return;
} // getFromInput

void IBHierarchyIntegrator::getFromRestart()
{
    Pointer<Database> restart_db = RestartManager::getManager()->getRootDatabase();
    Pointer<Database> db;
    if (restart_db->isDatabase(d_object_name))
    {
        db = restart_db->getDatabase(d_object_name);
    }
    else
    {
        TBOX_ERROR(d_object_name << ":  Restart database corresponding to " << d_object_name
                                 << " not found in restart file." << std::endl);
    }
    int ver = db->getInteger("IB_HIERARCHY_INTEGRATOR_VERSION");
    if (ver != IB_HIERARCHY_INTEGRATOR_VERSION)
    {
        TBOX_ERROR(d_object_name << ":  Restart file version different than class version." << std::endl);
    }
    d_time_stepping_type = string_to_enum<TimeSteppingType>(db->getString("d_time_stepping_type"));
    d_regrid_cfl_interval = db->getDouble("d_regrid_cfl_interval");
    d_regrid_cfl_estimate = db->getDouble("d_regrid_cfl_estimate");
    return;
} // getFromRestart

/////////////////////////////// NAMESPACE ////////////////////////////////////

} // namespace IBAMR

//////////////////////////////////////////////////////////////////////////////


text:
<?php

namespace Modules\Platform\Controllers;

use Nova\Http\Request;
use Nova\Routing\Controller;
use Nova\Support\Facades\Auth;
use Nova\Support\Facades\Input;
use Nova\Support\Facades\Response;

use Modules\Messages\Models\Message;
use Modules\Platform\Models\Activity;

class Heartbeat extends BaseController
{

    public function update(Request $request)
    {
        // Update the User Activity.
        Activity::updateCurrent($request);

        //
        $authUser = Auth::user();

        $lastId = (int) Input::get('last_id', 0);

        //Retrieve the unread notifications for the current User.
        $query = $authUser->unreadNotifications();

        // Get the total number of unread notifications.
        $count = $query->count();

        // Handle the last notification ID if requested.
        if ($lastId > 0) {
            $query->where('id', '>', $lastId);
        }

        $lastId = 0;

        // Get the first 5 unread notifications.
        $notifications = $query->limit(10)->get();

        if (! $notifications->isEmpty()) {
            $notification = $notifications->first();

            $lastId = $notification->id;
        }

        $items = array();

        foreach ($notifications as $notification) {
            $items[] = array_merge(
                array('id' => $notification->id, 'uuid' => $notification->uuid), $notification->data
            );
        }

        // Get the number of unread messages.
        $messages = Message::where('receiver_id', $authUser->id)->unread()->count();

        return Response::json(array(
            'messages' => array(
                'count' => $messages,
            ),
            'notifications' => array(
                'count'  => $count,
                'lastId' => $lastId,
                'items'  => $items,
            ),
        ));
    }
}


text:
function [trl, event] = trialfun_cutdata(cfg)
%% the first part is common to all trial functions
% read the header (needed for the samping rate) and the events
load Subject.mat

%% from here on it becomes specific to the experiment and the data format
% for the events of interest, find the sample numbers (these are integers)
% for the events of interest, find the trigger values (these are strings in the case of BrainVision)

event      = ft_read_event([subjectdata.filename '.vhdr']);
hdr        = ft_read_header([subjectdata.filename '.vhdr']);

EVvalue = {event.value}';
EVsample = [event.sample]';

HSF = find(strcmp(EVvalue,'S 18') == 1);
LSF = find(strcmp(EVvalue,'S 24') == 1);
gratings = [HSF;LSF];
gratings = sortrows(gratings,1);

PreTrig   = 0;
PostTrig  = 0;

begsample = EVsample(gratings(1)) - PreTrig;
endsample = EVsample(gratings(end)) + PostTrig;

offset = -PreTrig*ones(size(endsample));

%% the last part is again common to all trial functions
% return the trl matrix (required) and the event structure (optional)
trl = [begsample endsample offset];

end % function


text:
FOUNDATION_EXPORT double Colour_SwiftVersionNumber;

//! Project version string for Colour-Swift.
FOUNDATION_EXPORT const unsigned char Colour_SwiftVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Colour_Swift/PublicHeader.h>


text:
mkdir percobuild && cd percobuild
cmake -DTARGET_ARCH=x86_64 -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=$PREFIX -DXML_SUPPORT=ON -DCMAKE_PREFIX_PATH="$PREFIX;$PREFIX/lib" -DCMAKE_CXX_FLAGS="-std=c++14" $SRC_DIR
make && make install
cd ..

# First make sure we dont get problems with truncated PREFIX due to null terminators:
# see percolator/percolator#251 and conda/conda-build#1674
sed -i '54s/WRITABLE_DIR/std::string(WRITABLE_DIR).c_str()/' $SRC_DIR/src/Globals.cpp
mkdir converterbuild && cd converterbuild
cmake -DTARGET_ARCH=x86_64 -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PREFIX" -DBOOST_ROOT=$PREFIX -DBOOST_LIBRARYDIR=$PREFIX/lib -DSERIALIZE="Boost" -DCMAKE_CXX_FLAGS="-std=c++11" -DCMAKE_PREFIX_PATH="$PREFIX" $SRC_DIR/src/converters
make install
cd ..

mkdir $PREFIX/testdata
cp $SRC_DIR/src/converters/data/converters/sqt2pin/target.sqt $PREFIX/testdata/target.sqt
cp $SRC_DIR/src/converters/data/converters/msgf2pin/target.mzid $PREFIX/testdata/target.mzid
cp $SRC_DIR/src/converters/data/converters/tandem2pin/target.t.xml $PREFIX/testdata/target.t.xml
cp $SRC_DIR/data/percolator/tab/percolatorTab $PREFIX/testdata/percolatorTab


text:
using UnityEngine;
using System.Collections;

public class Vibrate : MonoBehaviour
{

	//Simulates shaking or vibration by moving randomly within specified parameters
	//Attach to a parent object, because it will directly edit localPosition

	[SerializeField]
	private bool _vibrateOn;

	public bool vibrateOn
	{
		get { return _vibrateOn; }
		set
		{
			if (!value && resetOnStop)
				resetPosition();
			else if (!value && resetOnStart)
				resetVibrateGoal();
			_vibrateOn = value;
		}
	}
	public float vibrateSpeed, vibrateMaxX, vibrateMaxY;
	private Vector2 vibrateGoal, offset;
	public bool relativeToStartPosition, resetOnStop, resetOnStart;

	void Awake()
	{
		resetOffset();
		resetVibrateGoal();
	}

	void resetOffset()
	{
		offset = relativeToStartPosition ? (Vector2)transform.localPosition : Vector2.zero;
	}

	void setOffset(Vector3 position)
	{
		offset = (Vector2)position;
	}

	void Update()
	{
		if (vibrateOn)
			updateVibrate();
	}

	void resetPosition()
	{
		transform.localPosition = new Vector3(0f, 0f, transform.localPosition.z);
	}

	void updateVibrate()
	{
		if (MathHelper.moveTowardsLocal(transform, vibrateGoal, vibrateSpeed))
			resetVibrateGoal();
	}

	void resetVibrateGoal()
	{
		vibrateGoal = new Vector2(Random.Range(-1f * vibrateMaxX, vibrateMaxX), Random.Range(-1f * vibrateMaxY, vibrateMaxY)) + offset;
	}
}


text:
angular.module('proxtop').controller('MenuController', ['$scope', 'ipcManager', '$state', '$mdSidenav', '$rootScope', 'session',
    function($scope, ipcManager, $state, $mdSidenav, $rootScope, session) {
        const ipc = ipcManager($scope);
        ipc.on('logout', (ev, data) => {
            if(data.success) {
                $state.go('main');
            } else {
                alert('Logout failed: ' + data.reason);
            }
        });

        $scope.toggleMenu = () => {
            $mdSidenav('left').toggle();
        };

        $scope.logout = () => {
            ipc.send('logout');
            ipc.send('clear-message-cache');
        };

        $scope.openAbout = () => {
            ipc.send('open-about');
        };

        $scope.isLoggedIn = () => {
            return session.isLoggedIn();
        };

        $scope.getUsername = () => {
            return session.getUser();
        };

        $rootScope.$on('$stateChangeSuccess', () => {
            $mdSidenav('left').close();
        });
}]);


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Fl. reipubl. popularis sin. 74:163. 1985

#### Original name
Aster gerlachii Hance

### Remarks
null


text:
package com.mapbox.api.tilequery;

import com.mapbox.core.TestUtils;
import com.mapbox.core.exceptions.ServicesException;
import com.mapbox.geojson.Point;

import okhttp3.HttpUrl;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;

import org.hamcrest.core.StringStartsWith;
import org.hamcrest.junit.ExpectedException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;

public class TilequeryTestUtils extends TestUtils {
    protected static final String TILEQUERY_VALID = "tilequery.json";
    protected static final String TILEQUERY_ALL_PARAM_VALID = "tilequery-all-params.json";

    private MockWebServer server;
    protected HttpUrl mockUrl;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Before
    public void setUp() throws Exception {
        server = new MockWebServer();
        server.setDispatcher(new Dispatcher() {
            @Override
            public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
                try {
                    String response = loadJsonFixture(TILEQUERY_VALID);
                    if (request.getPath().contains("limit")) {
                        response = loadJsonFixture(TILEQUERY_ALL_PARAM_VALID);
                    }
                    return new MockResponse().setBody(response);
                } catch (IOException ioException) {
                    throw new RuntimeException(ioException);
                }
            }
        });
        server.start();
        mockUrl = server.url("");
    }

    @After
    public void tearDown() throws IOException {
        server.shutdown();
    }
}


text:
define(function(require) {
    var depend = require('respond');
})


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <!-- 套装上半部布局 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="15dp"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="15dp">
    <!-- 套装标识文案 -->
    <TextView
        android:id="@+id/tv_group_product_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textStyle="bold"
        android:textColor="@color/order_conform_red_txt"
        android:text="【套装】"
        android:layout_alignParentLeft="true"/>
    <!-- 套装名称 -->
    <TextView
        android:id="@+id/tv_group_pruduct_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textStyle="bold"
        android:textColor="@color/text_color_black2"
        android:layout_toRightOf="@+id/tv_group_product_id"
        android:text="早泄拯救装"/>
    <!-- 价格 -->
    <TextView
        android:id="@+id/tv_group_product_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textStyle="bold"
        android:textColor="@color/text_color_black2"
        android:text="¥27.60"
        android:layout_alignParentRight="true"/>
    <!-- 数量 -->
    <TextView
        android:id="@+id/tv_group_product_count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="12dp"
        android:textSize="12sp"
        android:textStyle="bold"
        android:textColor="@color/text_color_black3"
        android:layout_toLeftOf="@+id/tv_group_product_price"
        android:text="x1"/>
    </RelativeLayout>
    <!-- 套装子商品容器 -->
    <LinearLayout
        android:id="@+id/ly_group_product_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"/>
    <!-- 分割细线 -->
    <include layout="@layout/common_line_gray_horizontal"/>
</LinearLayout>


text:
/* ----------------------
Utilisation de l'API Kwick
App config
Ecole multimédia - 30/01/2017
Yoan Martinez
------------------------- */

/* ucfirst de PHP importé au JS */
function ucfirst(string){
	string += " ";
	let first = string.charAt(0).toUpperCase();
	return first + string.substr(1);
}

/* Création de l'application */
let app = angular.module('kwick-app', ['ngStorage', 'luegg.directives']);

app.config(function($sceDelegateProvider){
	// Whitelist pour accéder à l'API sans erreur dans la console
	 $sceDelegateProvider.resourceUrlWhitelist([
      'self',
      'http://greenvelvet.alwaysdata.net/**'
    ]);
});

/* Constantes */
app.constant('kwConst', {
	"url" : "http://greenvelvet.alwaysdata.net/kwick/api/"
});

/* Définition des vues */
app.directive('kwLogin', function(){
	return {
		restrict: 'E',
		templateUrl: 'partials/user.html'
	};
})
   .directive('kwChat', function(){
	   return {
		   restrict: 'E',
		   templateUrl: 'partials/chat.html',
	   };
});

/* Stockage des fonctions */
app.factory('kwFactory', function($http, $rootScope, kwConst) {
	return {
		testPing : function(){
			$http.jsonp(kwConst.url+"ping")
					 .then(function(rep){
					 	return rep.data.result.ready;
					 });
		},
		/* Vérification de la validité du token */
		verifToken : function(token){
			if(token){
				$http.jsonp(kwConst.url+"user/logged/"+token)
						 .then(function(rep){
					var result = (rep.data.result.status == "done" ? true : false);
					$rootScope.logStatus = result;
					if(!$rootScope.showWindow){$rootScope.showWindow = true;}
					return result;
				});
			} else {
				$rootScope.logStatus = false;
				if(!$rootScope.showWindow){$rootScope.showWindow = true;}
				return false;
			}
		},
		/* Erreur et notification */
		error : function(mess){
			$rootScope.mess.status = true;
			$rootScope.mess.detail = ucfirst(mess);
			$rootScope.mess.nature = false;
		},
		valid : function(mess){
			$rootScope.mess.status = true;
			$rootScope.mess.detail = ucfirst(mess);
			$rootScope.mess.nature = true;
		},
		/* Formatage du timestamp */
		dateFormat : function(timestamp){
			let date = new Date(timestamp*1000);
			return date.toLocaleString('fr');
		},
		/* Auto-scroll down à l'envoi de message */
		scrollAuto : function(){
    let element = document.getElementById("scrollW");
    element.scrollTop = element.scrollHeight;
		}
	}
});


text:
Installation
============

Nice makes use of [Composer](http://getcomposer.org/) to manage dependencies.

## Installing Nice

The recommended way to install Nice is to run the
`composer require` command in your project directory:

```bash
composer require nice/framework:~1.0
```

This command will download and install Nice into the current directory, and update the `composer.json` with
the new dependency.

## What's next?

Get started with [your first Nice app](your-first-app.md).


text:
jQuery.fn.daterangepicker = function(settings){
	var rangeInput = jQuery(this);

	//defaults
	var options = jQuery.extend({
		presetRanges: [
			{text: 'Today', dateStart: 'today', dateEnd: 'today' },
			{text: 'Last 7 days', dateStart: 'today-7days', dateEnd: 'today' },
			{text: 'Month to date', dateStart: function(){ return Date.parse('today').moveToFirstDayOfMonth();  }, dateEnd: 'today' },
			{text: 'Year to date', dateStart: function(){ var x= Date.parse('today'); x.setMonth(0); x.setDate(1); return x; }, dateEnd: 'today' },
			//extras:
			{text: 'The previous Month', dateStart: function(){ return Date.parse('1 month ago').moveToFirstDayOfMonth();  }, dateEnd: function(){ return Date.parse('1 month ago').moveToLastDayOfMonth();  } }
			//{text: 'Tomorrow', dateStart: 'Tomorrow', dateEnd: 'Tomorrow' },
			//{text: 'Ad Campaign', dateStart: '03/07/08', dateEnd: 'Today' },
			//{text: 'Last 30 Days', dateStart: 'Today-30', dateEnd: 'Today' },
			//{text: 'Next 30 Days', dateStart: 'Today', dateEnd: 'Today+30' },
			//{text: 'Our Ad Campaign', dateStart: '03/07/08', dateEnd: '07/08/08' }
		],
		//presetRanges: array of objects for each menu preset.
		//Each obj must have text, dateStart, dateEnd. dateStart, dateEnd accept date.js string or a function which returns a date object
		presets: {
			specificDate: 'Specific Date',
			allDatesBefore: 'All Dates Before',
			allDatesAfter: 'All Dates After',
			dateRange: 'Date Range'
		},
		rangeStartTitle: 'Start date',
		rangeEndTitle: 'End date',
		nextLinkText: 'Next',
		prevLinkText: 'Prev',
		doneButtonText: 'Done',
		earliestDate: Date.parse('-15years'), //earliest date allowed
		latestDate: Date.parse('+15years'), //latest date allowed
		constrainDates: false,
		rangeSplitter: '-', //string to use between dates in single input
		dateFormat: 'm/d/yy', // date formatting. Available formats: http://docs.jquery.com/UI/Datepicker/%24.datepicker.formatDate
		closeOnSelect: true, //if a complete selection is made, close the menu
		arrows: false,
		appendTo: 'body',
		onClose: function(){},
		onOpen: function(){},
		onChange: function(){},
		datepickerOptions: null //object containing native UI datepicker API options
	}, settings);

	//custom datepicker options, extended by options
	var datepickerOptions = {
		onSelect: function(dateText, inst) {
				$(this).trigger('constrainOtherPicker');

				var rangeA = fDate( rp.find('.range-start').datepicker('getDate') );
				var rangeB = fDate( rp.find('.range-end').datepicker('getDate') );

				if(rp.find('.ui-daterangepicker-specificDate').is('.ui-state-active')){
		                    rangeB = rangeA;
		                }

				//send back to input or inputs
				if(rangeInput.length == 2){
					rangeInput.eq(0).val(rangeA);
					rangeInput.eq(1).val(rangeB);
				}
				else{
					rangeInput.val((rangeA != rangeB) ? rangeA+' '+ options.rangeSplitter +' '+rangeB : rangeA);
				}
				//if closeOnSelect is true
				if(options.closeOnSelect){
					if(!rp.find('li.ui-state-active').is('.ui-daterangepicker-dateRange') && !rp.is(':animated') ){
						hideRP();
					}
				}
				options.onChange();
			},
			defaultDate: +0
	};

	//change event fires both when a calendar is updated or a change event on the input is triggered
	rangeInput.bind('change', options.onChange);

	//datepicker options from options
	options.datepickerOptions = (settings) ? jQuery.extend(datepickerOptions, settings.datepickerOptions) : datepickerOptions;

	//Capture Dates from input(s)
	var inputDateA, inputDateB = Date.parse('today');
	var inputDateAtemp, inputDateBtemp;
	if(rangeInput.size() == 2){
		inputDateAtemp = Date.parse( rangeInput.eq(0).val() );
		inputDateBtemp = Date.parse( rangeInput.eq(1).val() );
		if(inputDateAtemp == null){inputDateAtemp = inputDateBtemp;}
		if(inputDateBtemp == null){inputDateBtemp = inputDateAtemp;}
	}
	else {
		//if(rangeInput.val()){
			inputDateAtemp = Date.parse( rangeInput.val().split(options.rangeSplitter)[0] );
			inputDateBtemp = Date.parse( rangeInput.val().split(options.rangeSplitter)[1] );
			if(inputDateBtemp == null){inputDateBtemp = inputDateAtemp;} //if one date, set both
		//}
	}
	if(inputDateAtemp != null){inputDateA = inputDateAtemp;}
	if(inputDateBtemp != null){inputDateB = inputDateBtemp;}

	//build picker and
	var rp = jQuery('

');
	var rpPresets = (function(){
		var ul = jQuery('

').appendTo(rp);
		jQuery.each(options.presetRanges,function(){
			jQuery('
'+ this.text +'
')
			.data('dateStart', this.dateStart)
			.data('dateEnd', this.dateEnd)
			.appendTo(ul);
		});
		var x=0;
		jQuery.each(options.presets, function(key, value) {
			jQuery('
'+ value +'
')
			.appendTo(ul);
			x++;
		});

		ul.find('li').hover(
				function(){
					jQuery(this).addClass('ui-state-hover');
				},
				function(){
					jQuery(this).removeClass('ui-state-hover');
				})
			.click(function(){
				rp.find('.ui-state-active').removeClass('ui-state-active');
				jQuery(this).addClass('ui-state-active');
				clickActions(jQuery(this),rp, rpPickers, doneBtn);
				return false;
			});
		return ul;
	})();

	//function to format a date string
	function fDate(date){
	   if(date == null || !date.getDate()){return '';}
	   var day = date.getDate();
	   var month = date.getMonth();
	   var year = date.getFullYear();
	   month++; // adjust javascript month
	   var dateFormat = options.dateFormat;
	   return jQuery.datepicker.formatDate( dateFormat, date );
	}

	jQuery.fn.restoreDateFromData = function(){
		if(jQuery(this).data('saveDate')){
			jQuery(this).datepicker('setDate', jQuery(this).data('saveDate')).removeData('saveDate');
		}
		return this;
	}
	jQuery.fn.saveDateToData = function(){
		if(!jQuery(this).data('saveDate')){
			jQuery(this).data('saveDate', jQuery(this).datepicker('getDate') );
		}
		return this;
	}

	//show, hide, or toggle rangepicker
	function showRP(){
		if(rp.data('state') == 'closed'){
			positionRP();
			rp.fadeIn(300).data('state', 'open');
			options.onOpen();
		}
	}
	function hideRP(){
		if(rp.data('state') == 'open'){
			rp.fadeOut(300).data('state', 'closed');
			options.onClose();
		}
	}
	function toggleRP(){
		if( rp.data('state') == 'open' ){ hideRP(); }
		else { showRP(); }
	}
	function positionRP(){
		var relEl = riContain || rangeInput; //if arrows, use parent for offsets
		var riOffset = relEl.offset(),
			side = 'left',
			val = riOffset.left,
			offRight = jQuery(window).width() - val - relEl.outerWidth();

		if(val > offRight){
			side = 'right', val =  offRight;
		}

		rp.parent().css(side, val).css('top', riOffset.top + relEl.outerHeight());
	}

	//preset menu click events
	function clickActions(el, rp, rpPickers, doneBtn){

		if(el.is('.ui-daterangepicker-specificDate')){
			//Specific Date (show the "start" calendar)
			doneBtn.hide();
			rpPickers.show();
			rp.find('.title-start').text( options.presets.specificDate );
			rp.find('.range-start').restoreDateFromData().css('opacity',1).show(400);
			rp.find('.range-end').restoreDateFromData().css('opacity',0).hide(400);
			setTimeout(function(){doneBtn.fadeIn();}, 400);
		}
		else if(el.is('.ui-daterangepicker-allDatesBefore')){
			//All dates before specific date (show the "end" calendar and set the "start" calendar to the earliest date)
			doneBtn.hide();
			rpPickers.show();
			rp.find('.title-end').text( options.presets.allDatesBefore );
			rp.find('.range-start').saveDateToData().datepicker('setDate', options.earliestDate).css('opacity',0).hide(400);
			rp.find('.range-end').restoreDateFromData().css('opacity',1).show(400);
			setTimeout(function(){doneBtn.fadeIn();}, 400);
		}
		else if(el.is('.ui-daterangepicker-allDatesAfter')){
			//All dates after specific date (show the "start" calendar and set the "end" calendar to the latest date)
			doneBtn.hide();
			rpPickers.show();
			rp.find('.title-start').text( options.presets.allDatesAfter );
			rp.find('.range-start').restoreDateFromData().css('opacity',1).show(400);
			rp.find('.range-end').saveDateToData().datepicker('setDate', options.latestDate).css('opacity',0).hide(400);
			setTimeout(function(){doneBtn.fadeIn();}, 400);
		}
		else if(el.is('.ui-daterangepicker-dateRange')){
			//Specific Date range (show both calendars)
			doneBtn.hide();
			rpPickers.show();
			rp.find('.title-start').text(options.rangeStartTitle);
			rp.find('.title-end').text(options.rangeEndTitle);
			rp.find('.range-start').restoreDateFromData().css('opacity',1).show(400);
			rp.find('.range-end').restoreDateFromData().css('opacity',1).show(400);
			setTimeout(function(){doneBtn.fadeIn();}, 400);
		}
		else {
			//custom date range specified in the options (no calendars shown)
			doneBtn.hide();
			rp.find('.range-start, .range-end').css('opacity',0).hide(400, function(){
				rpPickers.hide();
			});
			var dateStart = (typeof el.data('dateStart') == 'string') ? Date.parse(el.data('dateStart')) : el.data('dateStart')();
			var dateEnd = (typeof el.data('dateEnd') == 'string') ? Date.parse(el.data('dateEnd')) : el.data('dateEnd')();
			rp.find('.range-start').datepicker('setDate', dateStart).find('.ui-datepicker-current-day').trigger('click');
			rp.find('.range-end').datepicker('setDate', dateEnd).find('.ui-datepicker-current-day').trigger('click');
		}

		return false;
	}

	//picker divs
	var rpPickers = jQuery('

Start Date

End Date

').appendTo(rp);
	rpPickers.find('.range-start, .range-end')
		.datepicker(options.datepickerOptions);

	rpPickers.find('.range-start').datepicker('setDate', inputDateA);
	rpPickers.find('.range-end').datepicker('setDate', inputDateB);

	rpPickers.find('.range-start, .range-end')
		.bind('constrainOtherPicker', function(){
			if(options.constrainDates){
				//constrain dates
				if($(this).is('.range-start')){
					rp.find('.range-end').datepicker( "option", "minDate", $(this).datepicker('getDate'));
				}
				else{
					rp.find('.range-start').datepicker( "option", "maxDate", $(this).datepicker('getDate'));
				}
			}
		})
		.trigger('constrainOtherPicker');

	var doneBtn = jQuery('<button class="btnDone ui-state-default ui-corner-all">'+ options.doneButtonText +'</button>')
	.click(function(){
		rp.find('.ui-datepicker-current-day').trigger('click');
		hideRP();
	})
	.hover(
			function(){
				jQuery(this).addClass('ui-state-hover');
			},
			function(){
				jQuery(this).removeClass('ui-state-hover');
			}
	)
	.appendTo(rpPickers);

	//inputs toggle rangepicker visibility
	jQuery(this).click(function(){
		toggleRP();
		return false;
	});
	//hide em all
	rpPickers.hide().find('.range-start, .range-end, .btnDone').hide();

	rp.data('state', 'closed');

	//Fixed for jQuery UI 1.8.7 - Calendars are hidden otherwise!
	rpPickers.find('.ui-datepicker').css("display","block");

	//inject rp
	jQuery(options.appendTo).append(rp);

	//wrap and position
	rp.wrap('

');

	//add arrows (only available on one input)
	if(options.arrows && rangeInput.size()==1){
		var prevLink = jQuery(''+ options.prevLinkText +'');
		var nextLink = jQuery(''+ options.nextLinkText +'');

		jQuery(this)
		.addClass('ui-rangepicker-input ui-widget-content')
		.wrap('

')
		.before( prevLink )
		.before( nextLink )
		.parent().find('a').click(function(){
			var dateA = rpPickers.find('.range-start').datepicker('getDate');
			var dateB = rpPickers.find('.range-end').datepicker('getDate');
			var diff = Math.abs( new TimeSpan(dateA - dateB).getTotalMilliseconds() ) + 86400000; //difference plus one day
			if(jQuery(this).is('.ui-daterangepicker-prev')){ diff = -diff; }

			rpPickers.find('.range-start, .range-end ').each(function(){
					var thisDate = jQuery(this).datepicker( "getDate");
					if(thisDate == null){return false;}
					jQuery(this).datepicker( "setDate", thisDate.add({milliseconds: diff}) ).find('.ui-datepicker-current-day').trigger('click');
			});
			return false;
		})
		.hover(
			function(){
				jQuery(this).addClass('ui-state-hover');
			},
			function(){
				jQuery(this).removeClass('ui-state-hover');
			});

		var riContain = rangeInput.parent();
	}

	jQuery(document).click(function(){
		if (rp.is(':visible')) {
			hideRP();
		}
	});

	rp.click(function(){return false;}).hide();
	return this;
}


text:
import Border from '../Layout/Border';
import Margin from '../Layout/Margin';
import Padding from '../Layout/Padding';
import assign from "object-assign";

class LayoutConfig {
    constructor(border, margin, padding, style, size){
        this.size = size;
        this.border = border;
        this.margin = margin;
        this.padding = padding;
        this.style = style;
    }
    generateStyle() {
        var self = this;
        if(!!this.style) {
            if(!!this.style.activeCSS && !!this.style.activeCSS.border) {
                var border = this.style.activeCSS.border.split(" ");
                this.style.activeCSS.borderWidth = border[0];
                this.style.activeCSS.borderStyle = border[1];
                this.style.activeCSS.borderColor = border[2];
                delete this.style.activeCSS.border;
            }
            if(!!this.style.normalCSS && !!this.style.normalCSS.border) {
                var border = this.style.normalCSS.border.split(" ");
                this.style.normalCSS.borderWidth = border[0];
                this.style.normalCSS.borderStyle = border[1];
                this.style.normalCSS.borderColor = border[2];
                delete this.style.normalCSS.border;
            }
        }

        return {
            active: assign(
                {},
                !!self.size ? self.size.toCSS() : {},
                !!self.border ? self.border.toCSS() : {},
                !!self.margin ? self.margin.toCSS() : {},
                !!self.padding ? self.padding.toCSS() : {},
                (!!self.style && !!self.style.activeCSS) ? self.style.activeCSS : {}
            ),
            normal: assign(
                {},
                !!self.size ? self.size.toCSS() : {},
                !!self.border ? self.border.toCSS() : {},
                !!self.margin ? self.margin.toCSS() : {},
                !!self.padding ? self.padding.toCSS() : {},
                !!self.style && !!self.style.normalCSS ? self.style.normalCSS : {}
            )
        }
    }
}

export default LayoutConfig;


text:
'use strict';

describe('ngInterview.currentDate', function() {

	var $compile,
		$scope,
		date = new Date(Date.parse('2016-07-01T12:00:00Z')),
		currentDateService = {
			get: function() {
				return date;
			}
		};

	beforeEach(function() {
		module('ngInterview.currentDate', function($provide) {
			$provide.service('currentDateService', function() {
				return currentDateService;
			});
		});
		inject(function(_$compile_, _$rootScope_) {
			$compile = _$compile_;
			$scope = _$rootScope_;
		});
	});

	describe('current-date directive', function() {

		it('inserts current date into element', function() {
			var elem = $compile('')($scope);
			expect(elem.text()).toBe('7/1/16');
		});

		it('inserts current date into element with specified formatting', function() {
			var elem = $compile('')($scope);
			expect(elem.text()).toBe('07-01-2016');
		});

	});

});


text: <input type="checkbox" class="control-checkbox" data-bind="checked: value, attr: { id: uid, disabled: disabled, name: inputName }, hasFocus: focused">


text:
title: Run Functional Tests on an API Response using Chai-HTTP III - PUT method
localeTitle: Executar testes funcionais em uma resposta da API usando o método Chai-HTTP III - PUT
---
## Executar testes funcionais em uma resposta da API usando o método Chai-HTTP III - PUT

Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-on-an-api-response-using-chai-http-iii---put-method/index.md) .

[Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
/*
 The crud mixin for the mongo database layer is used for all of the functionality that is going to be shared between
 all connections.
 */
module.exports = (function(){
    'use strict';

    var _ = require('lodash');

    return {
        privateFields: [],
        parseOptions: function(options){
            var opt = (_.isUndefined(options)) ? {} : options;

            if(_.isUndefined(opt.include)){
                opt.include = [];
            }
            if(_.isUndefined(opt.exclude)){
                opt.exclude = [];
            }

            return opt;
        },
        parseExclusion: function(arr){
            var separator = '-';

            return _.map(arr, function(item){
                return separator + item;
            });
        },
        /**
         * Build string variable that can be sent to mongo query to include or exclude fields in the response. Your
         * implementation module should set 'privateFields' so that we can use the parameter here.
         *
         * @param options Query options object
         * @returns {string}
         */
        buildIncludes: function(options){
            var cleanOptions = this.parseOptions(options),
                includeExludes = _.union(cleanOptions.include,
                    this.parseExclusion(cleanOptions.exclude),
                    this.parseExclusion(this.privateFields)
                );

            return includeExludes.join(' ');
        },
        buildOptions: function(options){
            var opt = {};

            if(!_.isUndefined(options)){
                if((!_.isUndefined(options.sort) && !_.isFunction(options.sort)) || !_.isUndefined(options.sortBy)){
                    // Mongo queries are objects if asc / desc specified, otherwise they are strings
                    opt.sort = options.sort || options.sortBy;
                }
                if(!_.isUndefined(options.limit)){
                    opt.limit = parseInt(options.limit);
                }
                if(!_.isUndefined(options.skip) && parseInt(options.skip) >= 0){
                    opt.skip = parseInt(options.skip);
                }
            }

            return opt;
        }
    };
})();


text:
package net.ssehub.kernel_haven.variability_model;

import static net.ssehub.kernel_haven.util.null_checks.NullHelpers.notNull;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.ssehub.kernel_haven.provider.AbstractCache;
import net.ssehub.kernel_haven.util.FormatException;
import net.ssehub.kernel_haven.util.Util;
import net.ssehub.kernel_haven.util.io.json.JsonElement;
import net.ssehub.kernel_haven.util.io.json.JsonList;
import net.ssehub.kernel_haven.util.io.json.JsonNumber;
import net.ssehub.kernel_haven.util.io.json.JsonObject;
import net.ssehub.kernel_haven.util.io.json.JsonParser;
import net.ssehub.kernel_haven.util.io.json.JsonPrettyPrinter;
import net.ssehub.kernel_haven.util.io.json.JsonString;
import net.ssehub.kernel_haven.util.null_checks.NonNull;
import net.ssehub.kernel_haven.util.null_checks.Nullable;
import net.ssehub.kernel_haven.variability_model.VariabilityModelDescriptor.Attribute;
import net.ssehub.kernel_haven.variability_model.VariabilityModelDescriptor.ConstraintFileType;
import net.ssehub.kernel_haven.variability_model.VariabilityModelDescriptor.VariableType;

/**
 * A cache for permanently saving (and reading) a {@link VariabilityModel} to a file. Uses JSON for data representation.
 *
 * @author Adam
 */
public class JsonVariabilityModelCache extends AbstractCache<VariabilityModel> {

    private static final int VERSION = 5;

    private @NonNull File cacheFile;

    /**
     * Creates a new cache in the given cache directory.
     *
     * @param cacheDir The directory where to store the cache files. This must be a directory, and we must be able to
     *      read and write to it.
     */
    public JsonVariabilityModelCache(@NonNull File cacheDir) {
        this.cacheFile = new File(cacheDir, "vmCache.json");
    }

    @Override
    public @Nullable VariabilityModel read(@NonNull File target) throws FormatException, IOException {
        JsonObject data = null;
        VariabilityModel result = null;

        try (JsonParser parser = new JsonParser(cacheFile)) {

            JsonElement parsed = parser.parse();
            if (!(parsed instanceof JsonObject)) {
                throw new FormatException("Expected JSON object, got " + parsed.getClass().getSimpleName());
            }

            data = (JsonObject) parsed;

        } catch (FileNotFoundException e) {
            // ignore and return null
        }

        if (data != null) {
            if (data.getInt("version") != VERSION) {
                throw new FormatException("Got invalid version " + data.getInt("version") + ", we only support "
                        + VERSION);
            }

            VariabilityModelDescriptor descriptor = readDescriptor(data.getObject("descriptor"));
            // TODO: removed null annotations because jacoco report fails with it
            Map</*@NonNull*/ String, VariabilityVariable> vars = readVariables(data.getList("variables"));

            File constraintCopy = File.createTempFile("constraintModel", "");
            constraintCopy.deleteOnExit();
            try (FileOutputStream out = new FileOutputStream(constraintCopy)) {
                Util.copyStream(new ByteArrayInputStream(data.getString("constraintModel").getBytes()), out);
            }

            @SuppressWarnings("null") // TODO: null annotation missing, see above
            VariabilityModel tmp = new VariabilityModel(constraintCopy, vars);
            tmp.setDescriptor(descriptor);
            result = tmp;
        }

        return result;
    }

    /**
     * Reads the {@link VariabilityModelDescriptor} from the given DIMACS.
     *
     * @param data The JSON to read.
     *
     * @return The read {@link VariabilityModelDescriptor}.
     *
     * @throws FormatException If reading the {@link VariabilityModelDescriptor} fails.
     */
    private @NonNull VariabilityModelDescriptor readDescriptor(@NonNull JsonObject data) throws FormatException {
        VariabilityModelDescriptor desriptor = new VariabilityModelDescriptor();

        try {
            desriptor.setVariableType(VariableType.valueOf(data.getString("variableType")));
            desriptor.setConstraintFileType(ConstraintFileType.valueOf(data.getString("constraintFileType")));

            for (JsonElement element : data.getList("attributes")) {
                if (!(element instanceof JsonString)) {
                    throw new FormatException("Expected JsonString, but got " + element.getClass().getSimpleName());
                }

                desriptor.addAttribute(Attribute.valueOf(((JsonString) element).getValue()));
            }

        } catch (IllegalArgumentException e) {
            throw new FormatException(e);
        }

        return desriptor;
    }

    /**
     * Reads and initializes the variables stored in the given JSON object.
     *
     * @param data The JSON to read from.
     *
     * @return The read and initialized variables; a mapping of {@code variable name -> variable}.
     *
     * @throws FormatException If reading the variables fails.
     */
    private @NonNull Map<@NonNull String, VariabilityVariable> readVariables(@NonNull JsonList data)
            throws FormatException {

        Map<@NonNull String, VariabilityVariable> vars = new HashMap<>();

        /*
         * Round 1: Instantiate all variables; this sets name and type
         */

        for (JsonElement element : data) {
            if (!(element instanceof JsonObject)) {
                throw new FormatException("Expected variable JsonObject, but got "
                        + element.getClass().getSimpleName());
            }
            JsonObject obj = (JsonObject) element;

            try {
                @SuppressWarnings("unchecked")
                Class<? extends VariabilityVariable> clazz =
                        (Class<? extends VariabilityVariable>) ClassLoader.getSystemClassLoader().loadClass(
                                obj.getString("class"));

                VariabilityVariable var = notNull(clazz.getConstructor(String.class, String.class)
                        .newInstance(obj.getString("name"), obj.getString("type")));

                vars.put(obj.getString("name"), var);

            } catch (InvocationTargetException e) {
                throw new FormatException(e.getTargetException());

            } catch (ReflectiveOperationException e) {
                throw new FormatException(e);
            }

        }

        /*
         * Round 2: Pass through all instantiated variables and call setJsonData
         */

        for (JsonElement element : data) {
            if (!(element instanceof JsonObject)) {
                throw new FormatException("Expected variable JsonObject, but got "
                        + element.getClass().getSimpleName());
            }
            JsonObject obj = (JsonObject) element;

            VariabilityVariable var = vars.get(obj.getString("name"));
            var.setJsonData(obj, vars);
        }

        return vars;
    }

    @Override
    public void write(@NonNull VariabilityModel result) throws IOException {
        JsonObject mainJson = new JsonObject();

        mainJson.putElement("version", new JsonNumber(VERSION));
        mainJson.putElement("descriptor", descriptorToJson(result.getDescriptor()));
        mainJson.putElement("variables", variablesToJson(result.getVariables()));
        mainJson.putElement("constraintModel",
                new JsonString(Util.readStream(new FileInputStream(result.getConstraintModel()))));

        try (BufferedWriter out = new BufferedWriter(new FileWriter(cacheFile))) {
            out.write(mainJson.accept(new JsonPrettyPrinter()));
        }
    }

    /**
     * Turns the {@link VariabilityModelDescriptor} into a {@link JsonObject}.
     *
     * @param descriptor The descriptor to convert.
     *
     * @return The JSON representation of the descriptor.
     */
    private @NonNull JsonElement descriptorToJson(@NonNull VariabilityModelDescriptor descriptor) {
        JsonObject result = new JsonObject();

        result.putElement("variableType", new JsonString(notNull(descriptor.getVariableType().name())));
        result.putElement("constraintFileType", new JsonString(notNull(descriptor.getConstraintFileType().name())));

        JsonList attributes = new JsonList();
        for (Attribute a : descriptor.getAttributes()) {
            attributes.addElement(new JsonString(notNull(a.name())));
        }
        result.putElement("attributes", attributes);

        return result;
    }

    /**
     * Turns the given {@link VariabilityVariable}s into a {@link JsonList} of {@link JsonObject}s.
     *
     * @param variables The variables to convert.
     *
     * @return The JSON representation of the variables.
     */
    private @NonNull JsonElement variablesToJson(@NonNull Set<@NonNull VariabilityVariable> variables) {
        List<@NonNull VariabilityVariable> sorted = new ArrayList<>(variables);
        sorted.sort((v1, v2) -> v1.getName().compareTo(v2.getName()));

        JsonList result = new JsonList();

        for (VariabilityVariable var : sorted) {
            JsonObject json = var.toJson();
            json.putElement("class", new JsonString(notNull(var.getClass().getName())));
            result.addElement(json);
        }

        return result;
    }

}