text:
using Ma.CustomMapper.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Ma.CustomMapper
{
  /// Mapper to map one type to another
  public interface ICustomMapper
  {
    /// Mapping configurations
    Configurations Configurations { get; }

    /// Map source object from type of source type to type of TTarget
    /// <typeparam name="TTarget">Target type to map source to</typeparam>
    /// <param name="source">Source to map</param>
    /// <param name="mapChildEntities">Also Map child entities in this source</param>
    /// <param name="additionalData">Additional data to map to model.</param>
    /// <returns>Mapped object</returns>
    TTarget Map<TTarget>(object source, bool mapChildEntities = true, object additionalData = null)
      where TTarget : class;

    /// Map source object from type of source type to type of TTarget asynchronously
    /// <typeparam name="TTarget">Target type to map source to</typeparam>
    /// <param name="source">Source to map</param>
    /// <param name="mapChildEntities">Also Map child entities in this source</param>
    /// <param name="additionalData">Additional data to map to model.</param>
    /// <returns>Task to get mapped object</returns>
    Task<TTarget> MapAsync<TTarget>(object source, bool mapChildEntities = true, object additionalData = null)
      where TTarget : class;

    /// Map source from type of TSource to type of TTarget
    /// <typeparam name="TSource">Type of source</typeparam>
    /// <typeparam name="TTarget">Type of target</typeparam>
    /// <param name="source">Source to map</param>
    /// <param name="mapChildEntities">Also Map child entities in this source</param>
    /// <param name="additionalData">Additional data to map to model.</param>
    /// <returns>Mapped object</returns>
    TTarget Map<TSource, TTarget>(TSource source, bool mapChildEntities = true, object additionalData = null)
        where TSource : class
        where TTarget : class;

    /// Map source from type of TSource to type of TTarget asynchronously
    /// <typeparam name="TSource">Type of source</typeparam>
    /// <typeparam name="TTarget">Type of target</typeparam>
    /// <param name="source">Source to map</param>
    /// <param name="mapChildEntities">Also Map child entities in this source</param>
    /// <param name="additionalData">Additional data to map to model.</param>
    /// <returns>Task to get mapped object</returns>
    Task<TTarget> MapAsync<TSource, TTarget>(TSource source, bool mapChildEntities = true, object additionalData = null)
        where TSource : class
        where TTarget : class;

    /// Map list of entities from TSource type to list of TTarget type.
    /// <typeparam name="TSource">Type of source</typeparam>
    /// <typeparam name="TTarget">Type of target</typeparam>
    /// <param name="source">Source to map</param>
    /// <param name="mapChildEntities">Also Map child entities in this source</param>
    /// <param name="additionalData">Additional data to map to model.</param>
    /// <returns>Mapped list.</returns>
    List<TTarget> Map<TSource, TTarget>(ICollection<TSource> sourceList, bool mapChildEntities = true, object additionalData = null)
        where TTarget : class
        where TSource : class;

    /// Map list of entities from TSource type to list of TTarget type asynchronously
    /// <typeparam name="TSource">Type of source</typeparam>
    /// <typeparam name="TTarget">Type of target</typeparam>
    /// <param name="source">Source to map</param>
    /// <param name="mapChildEntities">Also Map child entities in this source</param>
    /// <param name="additionalData">Additional data to map to model.</param>
    /// <returns>Task to get mapped list</returns>
    Task<List<TTarget>> MapAsync<TSource, TTarget>(ICollection<TSource> sourceList, bool mapChildEntities = true, object additionalData = null)
        where TTarget : class
        where TSource : class;
  }
}


text:
namespace cocos3d
{

C3DBaseParticleAction::C3DBaseParticleAction(C3DParticleSystem* system)
{
	_system = system;
	_name = NULL;
};

C3DBaseParticleAction::~C3DBaseParticleAction()
{
	_system = NULL;
	SAFE_DELETE_ARRAY(_name);

};

void C3DBaseParticleAction::load(C3DElementNode* psaNode)
{
	char* name = const_cast<char*>(psaNode->getElement("name"));
	size_t size = strlen(name);
	_name = new char[size+1];
    memcpy(_name,name,size);
	_name[size] = 0;
}

void C3DBaseParticleAction::save(C3DElementNode* psaNode)
{
	psaNode->setElement("name", &_name);
}

void C3DBaseParticleAction::copyFrom(const C3DBaseParticleAction* other)
{
    if (other->_name)
    {
        SAFE_DELETE_ARRAY(_name);
        _name = new char[strlen(other->_name) + 1];
        strcpy(_name, other->_name);
    }
}

C3DBaseParticleAction* C3DBaseParticleAction::clone(C3DParticleSystem* system) const
{
    C3DBaseParticleAction* action = new C3DBaseParticleAction(system);
    action->copyFrom(this);
    return action;
}

}

redpajama_set_name: RedPajamaGithub


text:
package io.sgr.telegram.bot.api.models.inline;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;

import io.sgr.telegram.bot.api.models.ParseMode;
import io.sgr.telegram.bot.api.models.markups.InlineKeyboardMarkup;
import io.sgr.telegram.bot.api.utils.JsonUtil;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Represents a link to an mp3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use
 * input_message_content to send a message with the specified content instead of the audio.
 *
 * @author SgrAlpha
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InlineQueryResultCachedAudio implements InlineQueryResult, CachedItem, ItemWithCaption {

    private static final String TYPE = "audio";

    private final String id;
    private final String fileId;
    private final String caption;
    private final ParseMode parseMode;
    private final InputMessageContent inputMessageContent;
    private final InlineKeyboardMarkup replyMarkup;

    /**
     * @param id Unique identifier for this result, 1-64 bytes.
     * @param fileId A valid URL for the audio file.
     * @param caption Optional. Caption of the audio to be sent, 0-200 characters.
     * @param parseMode Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption.
     * @param replyMarkup Optional. Inline keyboard attached to the message.
     * @param inputMessageContent Optional. Content of the message to be sent instead of the audio.
     */
    public InlineQueryResultCachedAudio(
            final String id, final String fileId,
            final String caption, final ParseMode parseMode,
            final InlineKeyboardMarkup replyMarkup, final InputMessageContent inputMessageContent) {
        checkArgument(!isNullOrEmpty(id), "Missing ID");
        this.id = id;
        checkArgument(!isNullOrEmpty(fileId), "Missing audio URL");
        this.fileId = fileId;
        checkArgument(isNullOrEmpty(caption) || caption.length() <= 200,
                String.format("Caption should be shorter than 200 characters, but it's %d", caption.length()));
        this.caption = caption;
        this.parseMode = parseMode;
        this.replyMarkup = replyMarkup;
        this.inputMessageContent = inputMessageContent;
    }

    @JsonProperty("type")
    @Override
    public String getType() {
        return TYPE;
    }

    @JsonProperty("id")
    @Override
    public String getId() {
        return this.id;
    }

    @JsonProperty("audio_file_id")
    @Override
    public String getFileId() {
        return fileId;
    }

    @JsonProperty("caption")
    @Override
    public String getCaption() {
        return this.caption;
    }

    @JsonProperty("parse_mode")
    @Override
    public ParseMode getParseMode() {
        return this.parseMode;
    }

    @JsonProperty("input_message_content")
    @Override
    public InlineKeyboardMarkup getReplyMarkup() {
        return this.replyMarkup;
    }

    @JsonProperty("reply_markup")
    @Override
    public InputMessageContent getInputMessageContent() {
        return this.inputMessageContent;
    }

    public String toJson() {
        return JsonUtil.toJson(this);
    }

    @Override
    public String toString() {
        return this.toJson();
    }

}


text:
<img src="http://omk22jt2z.bkt.clouddn.com/S0001_CRCardAnimation_20170322.gif" width=200 />

## 简介:
卡片切换动效

| demo信息    | 详情                  |
|:-----------:|:---------------------:|
| DemoName    | CRCardAnimationView   |
| CRID        | S0001                 |
| author      | [Bear](https://github.com/BearRan) |
| authorMail  | 648070256@qq.com      |
| 源gitHub     | 无                    |
| 其他说明     | 无                    |

## 使用:

### Pod
>pod 'CRAnimation/Widget/CRCardAnimationView'

```
//  delegate
<CardAnimationViewDelegate>

//  init
CRCardAnimationView *cardAnimationView = [[CRCardAnimationView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
cardAnimationView.delegate = self;
cardAnimationView.cardShowInView_Count = 3;
cardAnimationView.cardOffSetPoint = CGPointMake(0, 30);
cardAnimationView.cardScaleRatio  = 0.09;
cardAnimationView.cardCycleShow = YES;
[self.view addSubview:_cardAnimationView];
```

### 代理方法
```
#pragma mark - CardAnimationView delegate

//  和tableView中的cellForRow同理
- (CRCardViewCell *)cardViewInCardAnimationView:(CRCardAnimationView *)cardAnimationView Index:(int)index
{
CGFloat cardView_width = (1.0 * 540 / 640) * WIDTH;
CGFloat cardView_height = (1.0 * 811 / 1134) * HEIGHT;
NSString *cardViewID_Str = @"cardViewID_Str";

CRCardViewCell *cardView = (CRCardViewCell *)[cardAnimationView dequeueReusableCardViewCellWithIdentifier:cardViewID_Str];
if (!cardView) {
cardView = [[CRCardViewCell alloc] initWithFrame:CGRectMake(0, 0, cardView_width, cardView_height) reuseIdentifier:cardViewID_Str];
cardView.layer.cornerRadius = 7.0f;
}

cardView.backgroundColor = UIColorFromHEX(0xC9162C);

return cardView;
}

//  显示的card数量,和tableView中的numberOfRows同理
- (NSInteger)numberOfCardsInCardAnimationView:(CRCardAnimationView *)cardAnimationView
{
return 10;
}

//  最前面一个即将消失在屏幕中的cell
- (void)cardViewWillDisappearWithCardViewCell:(CRCardViewCell *)cardViewCell Index:(NSInteger)index
{
NSLog(@"will disappear index:%ld", (long)index);
}

//  最前面一个即将置于图层顶层的cell
- (void)cardViewWillShowInTopWithCardViewCell:(CRCardViewCell *)cardViewCell Index:(NSInteger)index
{
NSLog(@"will show index:%ld", (long)index);
}

```

## 属性列表
```
CGFloat   animationDuration_Normal;   //普通动画时间
int       cardShowInView_Count;       //可见的卡片数量
CGFloat   cardAlphaGapValue;          //相邻卡片alpha差值
CGPoint   cardOffSetPoint;            //相邻卡片偏移位置设定
CGFloat   cardScaleRatio;             //相邻卡片缩放比例

BOOL      cardCycleShow;              //卡片显示完毕后循环显示
BOOL      cardPanEnable;              //卡片是否允许拖动
BOOL      cardRotateWhenPan;          //卡片拖动时是否可旋转
CGFloat   cardRotateMaxAngle;         //卡片可旋转时:卡片可旋转的最大角度(角度制,如,90,180)
CGFloat   cardFlyMaxDistance;         //卡片不可旋转时:卡片移动超过某一值时就飞走的阈值
```


text:
package com.google.android.libraries.mobiledatadownload.lite.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import javax.inject.Qualifier;

/** An executor on which MDDLite runs control execution flow which will touch I/O. */
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Qualifier
public @interface MddLiteControlExecutor {}


text:
package netflix.ocelli;

@SuppressWarnings("rawtypes")
public class InstanceEvent<T extends Enum> extends AbstractLoadBalancerEvent<T> {

    public enum EventType implements MetricEventType {

        /* Connection specific events. */
        ExecutionSuccess(true, false, Void.class),
        ExecutionFailed(true, true, Void.class),

        ;

        private final boolean isTimed;
        private final boolean isError;
        private final Class<?> optionalDataType;

        EventType(boolean isTimed, boolean isError, Class<?> optionalDataType) {
            this.isTimed = isTimed;
            this.isError = isError;
            this.optionalDataType = optionalDataType;
        }

        @Override
        public boolean isTimed() {
            return isTimed;
        }

        @Override
        public boolean isError() {
            return isError;
        }

        @Override
        public Class<?> getOptionalDataType() {
            return optionalDataType;
        }
    }

    public static final InstanceEvent<EventType> EXECUTION_SUCCESS = from(EventType.ExecutionSuccess);
    public static final InstanceEvent<EventType> EXECUTION_FAILED  = from(EventType.ExecutionFailed);

    /*Always refer to as constants*/protected InstanceEvent(T name, boolean isTimed, boolean isError) {
        super(name, isTimed, isError);
    }

    private static InstanceEvent<EventType> from(EventType type) {
        return new InstanceEvent<EventType>(type, type.isTimed(), type.isError());
    }
}


text:
void LoadOscProb(TString logLevel = "info") {

  // This macro will try to find the OscProb library
  // and load it in your session. You may consider
  // running it in your rootlogon.C file to be loaded
  // by default when you start ROOT.

  bool verbose = logLevel.Contains("v");
  bool quiet   = logLevel.Contains("q") && !verbose;

  // The library name
  TString s("libOscProb.so");

  // Search for the library here or in your library paths
  gSystem->FindFile(TString::Format("./:../:%s", gSystem->GetDynamicPath()), s);

  // Check if library file was found
  if(s.Length() == 0){
    if(!quiet) std::cout << "libOscProb not found!" << std::endl;
    return;
  }

  // Try to load the library and complain if failed
  int errCode = gSystem->Load(s.Data());

  // If loading failed, print message
  if(errCode != 0 && !quiet){

    switch(errCode){

      case 1: { // Library already loaded
        std::cout << "libOscProb already loaded at: ";
        TObjArray* libs = TString(gSystem->GetLibraries()).Tokenize(" ");

        for(int i =0; i<libs->GetEntries(); i++){

          TString lib = libs->At(i)->GetName();

          if(lib.Contains("libOscProb.so")){
            std::cout << lib << std::endl;
            s = lib;
          }

        }
        break;
      }
      default: std::cout << "libOscProb could not be loaded. Error Code: " << errCode << std::endl;

    }

  }
  else if(verbose){

    std::cout << "Loaded library " << s << std::endl;

  }

  if(verbose) std::cout << "Adding " << gSystem->DirName(s) << " to include path" << std::endl;
  gInterpreter->AddIncludePath(gSystem->DirName(s));

}


text:
--TEST--
similar_text(), error tests for missing parameters
--CREDITS--
Mats Lindh <mats at lindh.no>
#Testfest php.no
--FILE--
<?php
/* Prototype  : proto int similar_text(string str1, string str2 [, float percent])
* Description: Calculates the similarity between two strings
* Source code: ext/standard/string.c
*/

$extra_arg = 10;
echo "\n-- Testing similar_text() function with more than expected no. of arguments --\n";
similar_text("abc", "def", $percent, $extra_arg);

echo "\n-- Testing similar_text() function with less than expected no. of arguments --\n";
similar_text("abc");
?>
===DONE===
--EXPECTF--
-- Testing similar_text() function with more than expected no. of arguments --

Warning: similar_text() expects at most 3 parameters, 4 given in %s on line %d

-- Testing similar_text() function with less than expected no. of arguments --

Warning: similar_text() expects at least 2 parameters, 1 given in %s on line %d
===DONE===


text:
const markdown = require('markdown-it')()

export default markdown


text:
<?php
namespace dinnerandlove\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use dinnerandlove\MainBundle\Entity\UploadedImage as BaseImage;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 */
class DinnerPhoto extends BaseImage
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    protected $path;

    /**
     * @ORM\ManyToOne(targetEntity="dinnerandlove\MainBundle\Entity\Dinner", inversedBy="photos")
     * @Assert\NotBlank()
     */
    private $dinner;

    /**
     * @ORM\ManyToOne(targetEntity="dinnerandlove\UserBundle\Entity\User")
     * @Assert\NotBlank()
     */
    private $user;

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view.
        return 'uploads/dinner_photos';
    }

    protected function resizeSquare()
    {
      return true;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set path
     *
     * @param string $path
     */
    public function setPath($path)
    {
        $this->path = $path;
    }

    /**
     * Get path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Set dinner
     *
     * @param \dinnerandlove\MainBundle\Entity\Dinner $dinner
     * @return DinnerPhoto
     */
    public function setDinner(\dinnerandlove\MainBundle\Entity\Dinner $dinner = null)
    {
        $this->dinner = $dinner;

        return $this;
    }

    /**
     * Get dinner
     *
     * @return \dinnerandlove\MainBundle\Entity\Dinner
     */
    public function getDinner()
    {
        return $this->dinner;
    }

    /**
     * Set user
     *
     * @param \dinnerandlove\UserBundle\Entity\User $user
     * @return DinnerPhoto
     */
    public function setUser(\dinnerandlove\UserBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \dinnerandlove\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Customizing git — MNE 0.17.1 documentation</title>
    <link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="_static/reset-syntax.css" />

    <link rel="shortcut icon" href="_static/favicon.ico"/>
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />

    <link rel="stylesheet" href="_static/style.css " type="text/css" />
    <link rel="stylesheet" href="_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="_static/flag-icon.css" type="text/css" />

  <link rel="canonical" href="https://mne.tools/stable/index.html" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.17.1

Install

Documentation

API

Glossary

Examples

Contribute

  Site

  <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
    v0.17.1

  </button>

Development

v0.17 (stable)

v0.16

v0.15

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Customizing git

Overview

In detail

user.name and user.email

Aliases

Editor

Merging

<form action="search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Customizing git¶

Contents

Overview

In detail

user.name and user.email

Aliases

Editor

Merging

Overview¶

Your personal git configurations are saved in the .gitconfig file in
your home directory.
Here is an example .gitconfig file:

[user]
        name = Your Name
        email = you@yourdomain.example.com

[alias]
        ci = commit -a
        co = checkout
        st = status
        stat = status
        br = branch
        wdiff = diff --color-words

[core]
        editor = vim

[merge]
        summary = true

You can edit this file directly or you can use the git config --global
command:

git config --global user.name "Your Name"
git config --global user.email you@yourdomain.example.com
git config --global alias.ci "commit -a"
git config --global alias.co checkout
git config --global alias.st "status -a"
git config --global alias.stat "status -a"
git config --global alias.br branch
git config --global alias.wdiff "diff --color-words"
git config --global core.editor vim
git config --global merge.summary true

To set up on another computer, you can copy your ~/.gitconfig file,
or run the commands above.

In detail¶

user.name and user.email¶

It is good practice to tell git who you are, for labeling any changes
you make to the code.  The simplest way to do this is from the command
line:

git config --global user.name "Your Name"
git config --global user.email you@yourdomain.example.com

This will write the settings into your git configuration file,  which
should now contain a user section with your name and email:

[user]
      name = Your Name
      email = you@yourdomain.example.com

Of course you'll need to replace Your Name and you@yourdomain.example.com
with your actual name and email address.

Aliases¶

You might well benefit from some aliases to common commands.

For example, you might well want to be able to shorten git checkout
to git co.  Or you may want to alias git diff --color-words
(which gives a nicely formatted output of the diff) to git wdiff

The following git config --global commands:

git config --global alias.ci "commit -a"
git config --global alias.co checkout
git config --global alias.st "status -a"
git config --global alias.stat "status -a"
git config --global alias.br branch
git config --global alias.wdiff "diff --color-words"

will create an alias section in your .gitconfig file with contents
like this:

[alias]
        ci = commit -a
        co = checkout
        st = status -a
        stat = status -a
        br = branch
        wdiff = diff --color-words

Editor¶

You may also want to make sure that your editor of choice is used

git config --global core.editor vim

Merging¶

To enforce summaries when doing merges (~/.gitconfig file again):

[merge]
   log = true

Or from the command line:

git config --global merge.log true

GitHub

·

Mailing list

·

Gitter

·

What's new

·

Cite MNE

Back to top

© Copyright 2012-2019, MNE Developers. Last updated on 2019-02-22.


text:
package elasta.orm.table.data.populator;

import elasta.orm.upsert.FieldToColumnMapping;
import elasta.orm.upsert.TableData;
import io.vertx.core.json.JsonObject;

import java.util.*;

/**
 * Created by Jango on 2017-01-10.
 */
final public class TableDataPopulatorImpl implements TableDataPopulator {
    //    private final String table;
//    private final String primaryColumn;
//    private final FieldToColumnMapping[] fieldToColumnMappings;
//    private final List<DirectDependencyDataPopulator> directDependencyDataPopulators;
//    private final List<VirtualDependencyDataPopulator> virtualDependencyDataPopulators;
//
//    public TableDataPopulatorImpl(String table, String primaryColumn, FieldToColumnMapping[] fieldToColumnMappings, List<DirectDependencyDataPopulator> directDependencyDataPopulators, List<VirtualDependencyDataPopulator> virtualDependencyDataPopulators) {
//        Objects.requireNonNull(table);
//        Objects.requireNonNull(primaryColumn);
//        Objects.requireNonNull(fieldToColumnMappings);
//        Objects.requireNonNull(directDependencyDataPopulators);
//        Objects.requireNonNull(virtualDependencyDataPopulators);
//        this.table = table;
//        this.primaryColumn = primaryColumn;
//        this.fieldToColumnMappings = fieldToColumnMappings;
//        this.directDependencyDataPopulators = directDependencyDataPopulators;
//        this.virtualDependencyDataPopulators = virtualDependencyDataPopulators;
//    }
//
//    @Override
    public TableData populate(JsonObject entity
//        , Map<String, JsonObject> entityNameToParentEntityMap
    ) {
//
//        Objects.requireNonNull(entity);
//        Objects.requireNonNull(entityNameToParentEntityMap);
//
//        Map<String, Object> columnToValueMap = new LinkedHashMap<>();
//
//        for (FieldToColumnMapping fieldToColumnMapping : fieldToColumnMappings) {
//
//            final String column = fieldToColumnMapping.getField();
//
//            Object value = entity.getJsonObject(
//                column
//            );
//
//            if (value == null) {
//                continue;
//            }
//
//            columnToValueMap.put(
//                fieldToColumnMapping.getColumn(),
//                value
//            );
//        }
//
//        directDependencyDataPopulators
//            .stream()
//            .filter(directDependencyDataPopulator -> entity.containsKey(directDependencyDataPopulator.column()))
//            .forEach(directDependencyDataPopulator -> {
//
//                    final Map<String, Object> childColumnToValueMap = directDependencyDataPopulator.populateColumnToValueMap(
//                        Optional.ofNullable(
//                            entity.getJsonObject(directDependencyDataPopulator.column())
//                        )
//                    );
//
//                    columnToValueMap.putAll(childColumnToValueMap);
//                }
//            );
//
//        virtualDependencyDataPopulators
//            .stream()
//            .filter(virtualDependencyDataPopulator -> entityNameToParentEntityMap.containsKey(virtualDependencyDataPopulator.parentEntity()))
//            .forEach(virtualDependencyDataPopulator -> {
//
//                Map<String, Object> valueMap = virtualDependencyDataPopulator.populateColumnToValueMap(
//                    Optional.ofNullable(
//                        entityNameToParentEntityMap.get(virtualDependencyDataPopulator.parentEntity())
//                    )
//                );
//
//                columnToValueMap.putAll(valueMap);
//            });
//
//        return new TableData(table, new String[]{primaryColumn}, new JsonObject(columnToValueMap));
        return null;
    }
}


text:
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
 * Copyright 2008-2013 Pelican Mapping
 * http://osgearth.org
 *
 * osgEarth is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */
#include <osgDB/ReaderWriter>
#include <osgEarthDrivers/script_engine_v8/JavascriptEngineV8>
#include <osgEarthFeatures/ScriptEngine>
#include <osgEarth/Common>
#include <osgEarth/Config>
#include <osgDB/FileNameUtils>

class JavascriptEngineV8Factory : public osgEarth::Features::ScriptEngineDriver
{
public:
    JavascriptEngineV8Factory()
    {
        supportsExtension( "osgearth_scriptengine_javascript", "osgEarth scriptengine javascript plugin" );
        supportsExtension( "osgearth_scriptengine_javascript_v8", "osgEarth scriptengine javascript V8 plugin" );
    }

    virtual const char* className()
    {
        return "osgEarth ScriptEngine Javascript V8 Plugin";
    }

    virtual ReadResult readObject(const std::string& file_name, const osgDB::ReaderWriter::Options* options) const
    {
      if ( !acceptsExtension(osgDB::getLowerCaseFileExtension( file_name )) )
            return osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED;

        return osgDB::ReaderWriter::ReadResult( new JavascriptEngineV8( getScriptEngineOptions(options) ) );
    }
};

REGISTER_OSGPLUGIN(osgearth_scriptengine_javascript, JavascriptEngineV8Factory)


text:
image:
	docker build --tag docker-cleanup --rm .


text:
{% include head.html %}

{% if page.image.feature %}

  {% if page.image.feature contains 'https://' | escape or page.image.feature contains 'http://' | escape %}

  {% else %}

  {% endif %}
{% else %}

{% endif %}

{{page.title}}

{{page.date | date: "%b %d, %Y" }}

        {% for post in site.post %}

{{ post.title }}

{% if post.author %}{{ post.author  | strip_html | strip_newlines | truncate: 120 }}{% else %}{{ post.content | strip_html | strip_newlines | truncate: 120 }}{% endif %}

        {% endfor %}

      {{ content }}

        {% if page.previous.url %}
          « {{page.previous.title}}
        {% endif %}
        {% if page.next.url %}
          {{page.next.title}} »
        {% endif %}

      {% if page.comments %}

        Please enable JavaScript to view the comments powered by Disqus.
        comments powered by Disqus

      {% endif %}

{% include footer.html %}


text:
import {Subject} from 'rxjs/Subject';
import {Context} from './context';
import {Command} from './interfaces';

export class ReadPixel implements Command {

    stream = new Subject<Uint8Array>();

    constructor(
        private width: number,
        private height: number
    ) {}

    execute(ctx: Context) {
        let w = this.width;
        let h = this.height;
        let pixels = new Uint8Array(w * h * 4);
        ctx.gl.readPixels(0, 0, w, h, ctx.gl.RGBA, ctx.gl.UNSIGNED_BYTE, pixels);
        this.stream.next(pixels);
    }
}


text:
// PkgCmdID.cs
// MUST match PkgCmdID.h

namespace RakeRunner
{
    internal static class PkgCmdIDList
    {
        public const uint icmdCommandRakeMenu = 0x300;

        public const uint icmdRefresh = 0x401;
        public const uint icmdTasksList = 0x501;
    };
}


text:
package rest.application.config;

import java.util.Set;
import javax.ws.rs.core.Application;
import javax.ws.rs.ApplicationPath;

@ApplicationPath("resources")
public class ApplicationConfig extends Application {

	public Set<Class<?>> getClasses() {
        return getRestClasses();
    }

	//Auto-generated from RESTful web service wizard
    private Set<Class<?>> getRestClasses() {
		Set<Class<?>> resources = new java.util.HashSet<Class<?>>();

		resources.add(service.MessageEntityREST.class);
		return resources;
    }
}


text:
"""
Title Placeholder

Body placeholder
"""
# Built-in Modules
import ast
import csv
import json
import sys
import traceback
import unicodedata
import datetime as dt
import operator as op
import numpy as np
from dateutil.parser import parse as date_parse

# Third-party Modules
# Note the order and structure of matplotlib imports is intentional.
import matplotlib
# Note: this statement must be run before any other matplotlib imports are done.
matplotlib.use('AGG')
from matplotlib import pyplot as plt
from matplotlib import dates as mdate
from matplotlib import ticker as mtick

# My modules

# Collection of logging messages.
LOG = {'Threaddebug': [], 'Debug': [], 'Info': [], 'Warning': [], 'Critical': []}

# Unpack the payload data. The first element of the payload is the name of this script (we don't
# need that). As long as size isn't a limitation we will always send the entire payload as element
# 1.
try:
    payload = json.loads(sys.argv[1].encode("utf-8"))
    LOG['Debug'].append(f"[{payload['props']['name']}] payload unpacked successfully.")
except IndexError:
    pass

def __init__():
    """
    Title Placeholder

    Body placeholder
    :return:
    """

# =============================================================================
def convert_the_data(final_data, data_source, logger):
    """
    Convert data into form that matplotlib can understand

    Matplotlib can't plot values like 'Open' and 'Closed', so we convert them for plotting. We do
    this on the fly, and we don't change the underlying data in any way. Further, some data can be
    presented that should not be charted. For example, the WUnderground plugin will present '-99.0'
    when WUnderground is not able to deliver a rational value. Therefore, we convert '-99.0' to NaN
    values.
    -----
    :param logger:
    :param list final_data: the data to be charted
    :param str data_source:
    """

    LOG['Debug'].append(f"[{payload['props']['name']}] "
                        f"Coercing chart data to chart-able values where needed.")
    converter = {
        'true': 1, 'false': 0, 'open': 1, 'closed': 0, 'on': 1, 'off': 0, 'locked': 1,
        'unlocked': 0, 'up': 1, 'down': 0, '1': 1, '0': 0, 'heat': 1, 'armed': 1, 'disarmed': 0,
        '- data unavailable -': 'nan', 'data unavailable': 'nan', 'NA': 'nan', 'N/A': 'nan'
    }
    now = dt.datetime.now()
    now_text = dt.datetime.strftime(now, '%Y-%m-%d %H:%M:%S')

    # =============================================================================
    def is_number(s):
        """
        Title Placeholder

        Body placeholder
        :param s:
        :return:
        """
        try:
            float(s)
            return True

        except ValueError:
            pass

        try:
            unicodedata.numeric(s)
            return True

        except (TypeError, ValueError):
            pass

        return False

    for value in final_data:
        if value[1].lower() in converter:
            value[1] = converter[value[1].lower()]

    # We have converted all nonsense numbers to '-99.0'. Let's replace those with
    # 'NaN' for charting.
    final_data = [[n[0], 'NaN'] if n[1] == '-99.0' else n for n in final_data]

    # ================================ Process CSV ================================
    # If the CSV file is missing data or is completely empty, we generate a phony one and alert the
    # user. This helps avoid nasty surprises down the line.

    # ============================= CSV File is Empty =============================
    # Adds header and one observation. Length of CSV file goes from zero to two.
    if len(final_data) < 1:
        final_data.extend([('timestamp', 'placeholder'), (now_text, 0)])
        logger['Warning'].append(
            f"[{payload['props']['name']}] CSV file is empty. File: {data_source}"
        )

    # ===================== CSV File has Headers but no Data ======================
    # Adds one observation. Length of CSV file goes from one to two.
    if len(final_data) < 2:
        final_data.append((now_text, 0))
        logger['Warning'].append(
            f"[{payload['props']['name']}] CSV file does not have sufficient information to make "
            f"a useful plot. File: {data_source}"
        )

    # =============================== Malformed CSV ===============================
    # Test to see if any data element is a valid numeric and replace it with 'NaN' if it isn't.

    # Preserve the header row.
    headers = final_data[0]
    del final_data[0]

    # Data element contains an invalid string element. All proper strings like 'off' and 'true'
    # should already have been converted with self.convert_the_data() above.
    final_data = [(item[0], 'NaN') if not is_number(item[1]) else item for item in final_data]

    # Put the header row back in.
    final_data.insert(0, headers)

    return final_data

# =============================================================================
def eval_expr(expr):
    """
    Title Placeholder

    Body placeholder
    :param expr:
    :return:
    """
    LOG['Debug'].append(f"[{payload['props']['name']}] Evaluating expressions.")
    return eval_(ast.parse(expr, mode='eval').body)

# =============================================================================
def eval_(mode):
    """
    Title Placeholder

    Body placeholder
    :param mode:
    :return:
    """
    operators = {
        ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, ast.Pow: op.pow,
        ast.BitXor: op.xor, ast.USub: op.neg
    }

    if isinstance(mode, ast.Num):  # <number>
        value = mode.n
    elif isinstance(mode, ast.BinOp):  # <left> <operator> <right>
        value = operators[type(mode.op)](eval_(mode=mode.left), eval_(mode=mode.right))
    elif isinstance(mode, ast.UnaryOp):  # <operator> <operand> e.g., -1
        value = operators[type(mode.op)](eval_(mode=mode.operand))
    else:
        raise TypeError(mode)

    return value

# =============================================================================
def fix_rgb(color):
    """
    Title Placeholder

    Body placeholder
    :param color:
    :return:
    """
    LOG['Debug'].append(f"[{payload['props']['name']}] Coercing colors to #RRBBGG.")
    rgb = color.replace(' ', '').replace('#', '')
    return f"#{rgb}"

# =============================================================================
def format_axis(ax_obj):
    """
    Set various axis properties

    Note that this method purposefully accesses protected members of the _text class.
    -----
    :param class 'matplotlib.table.Table' ax_obj: matplotlib table object
    """

    LOG['Debug'].append(f"[{payload['props']['name']}] Setting axis properties.")
    ax_props = ax_obj.properties()
    ax_cells = ax_props['children']
    for cell in ax_cells:
        cell.set_facecolor(payload['p_dict']['faceColor'])
        cell._text.set_color(payload['p_dict']['fontColor'])
        cell._text.set_fontname(payload['p_dict']['fontMain'])
        cell._text.set_fontsize(int(payload['props']['fontSize']))
        cell.set_linewidth(int(plt.rcParams['lines.linewidth']))

        # This may not be supportable without including fonts with the plugin.
        # cell._text.set_fontstretch(1000)

        # Controls grid display
        if payload['props'].get('calendarGrid', True):
            cell.set_edgecolor(payload['p_dict']['spineColor'])
        else:
            cell.set_edgecolor(payload['p_dict']['faceColor'])

# =============================================================================
def format_axis_x_label(dev, p_dict, k_dict, logger):  # noqa
    """
    Format X axis label visibility and properties

    If the user chooses to display a legend, we don't want an axis label because they will fight
    with each other for space.
    -----
    :param dict logger:
    :param dict dev: device props
    :param dict p_dict: plotting parameters
    :param dict k_dict: plotting kwargs
    :return unicode result:
    """
    try:
        font_main           = p_dict.get('fontMain', 'Arial')  # Main font style
        font_size           = int(p_dict.get('tickFontSize', '8'))  # Main font size
        custom_size_font    = p_dict.get('customSizeFont', False)  # Use custom font sizes?  Bool
        custom_axis_label_x = p_dict.get('customAxisLabelX', '')
        custom_font_size    = int(p_dict.get('customTickFontSize', '8'))
        rotate              = int(p_dict.get('xAxisRotate', 0))
        show_legend         = p_dict.get('showLegend', False)  # Show legend?  Bool

        h_align = {'-90': 'left', '-45': 'left', '0': 'center', '45': 'right', '90': 'right'}

        # The label of the X axis ticks (not the axis label)
        if custom_size_font:
            plt.xticks(
                fontname=font_main, fontsize=custom_font_size, rotation=rotate,
                ha=h_align[str(rotate)]
            )
        else:
            plt.xticks(
                fontname=font_main, fontsize=font_size, rotation=rotate, ha=h_align[str(rotate)]
            )

        if not show_legend:
            # The label of the X axis (not the tick labels)
            plt.xlabel(custom_axis_label_x, **k_dict['k_x_axis_font'])

            if p_dict['verboseLogging']:
                logger['Threaddebug'].append(
                    f"[{payload['props']['name']}] No call for legend. Formatting X label."
                )

        if show_legend and custom_axis_label_x.strip(' ') not in ('', 'null'):
            logger['Debug'].append(
                f"[{payload['props']['name']}] X axis label is suppressed to make room for the "
                f"chart legend."
            )

    except (ValueError, TypeError) as err:
        logger['Threaddebug'].append(
            f"[{payload['props']['name']}] Problem formatting X labels.\n{err}"
        )

    except RuntimeError as err:
        if "exceeds Locator.MAXTICKS" in traceback.format_exc(err):
            logger['Critical'].append(
                f"[{payload['props']['name']}] Chart data will produce too many X axis ticks. "
                f"Check source data."
            )

# =============================================================================
def format_axis_x_min_max(p_dict, logger):
    """
    Format x-axis range limits

    Setting the limits before the plot turns off autoscaling, which causes the limit that's not set
    to behave weirdly at times. This block is meant to overcome that weirdness for something more
    desirable.
    -----
    :param dict p_dict: plotting parameters
    :param dict logger:
    """

    try:

        x_min = min(p_dict['data_array'])
        x_max = max(p_dict['data_array'])
        x_min_wanted = p_dict['xAxisMin']
        x_max_wanted = p_dict['xAxisMax']

        # Since the min / max is used here only for chart boundaries, we "trick" Matplotlib by
        # using a number that's very nearly zero.
        if x_min == 0:
            x_min = 0.000001

        if x_max == 0:
            x_max = 0.000001

        # Y min
        if isinstance(x_min_wanted, str) and x_min_wanted.lower() == 'none':
            if x_min > 0:
                x_axis_min = x_min * (1 - (1 / abs(x_min) ** 1.25))
            else:
                x_axis_min = x_min * (1 + (1 / abs(x_min) ** 1.25))
        else:
            x_axis_min = float(x_min_wanted)

        # Y max
        if isinstance(x_max_wanted, str) and x_max_wanted.lower() == 'none':
            if x_max > 0:
                x_axis_max = x_max * (1 + (1 / abs(x_max) ** 1.25))
            else:
                x_axis_max = x_max * (1 - (1 / abs(x_max) ** 1.25))

        else:
            x_axis_max = float(x_max_wanted)

        plt.xlim(xmin=x_axis_min, xmax=x_axis_max)

    except (ValueError, TypeError) as err:
        logger['Warning'].append(
            f"[{payload['props']['name']}] Error setting axis limits for x axis. Will rely on "
            f"matplotlib to determine limits. ({err})"
        )

# =============================================================================
def format_axis_x_scale(x_axis_bins, logger):
    """
    Format X axis scale based on user setting

    The format_axis_x_scale() method sets the bins for the X axis. Presently, we assume a date-based
    X axis.
    -----
    :param dict logger:
    :param list x_axis_bins:
    """

    try:
        if x_axis_bins == 'quarter-hourly':
            plt.gca().xaxis.set_major_locator(mdate.MinuteLocator(interval=15))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 1)))
        if x_axis_bins == 'half-hourly':
            plt.gca().xaxis.set_major_locator(mdate.MinuteLocator(interval=30))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 1)))
        elif x_axis_bins == 'hourly':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=1))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 24)))
        elif x_axis_bins == 'hourly_2':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=2))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 8)))
        elif x_axis_bins == 'hourly_4':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 8)))
        elif x_axis_bins == 'hourly_8':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 4)))
        elif x_axis_bins == 'hourly_12':
            plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 2)))
        elif x_axis_bins == 'daily':
            plt.gca().xaxis.set_major_locator(mdate.DayLocator(interval=1))
            plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 6)))
        elif x_axis_bins == 'weekly':
            plt.gca().xaxis.set_major_locator(mdate.DayLocator(interval=7))
            plt.gca().xaxis.set_minor_locator(mdate.DayLocator(interval=1))
        elif x_axis_bins == 'monthly':
            plt.gca().xaxis.set_major_locator(mdate.MonthLocator(interval=1))
            plt.gca().xaxis.set_minor_locator(mdate.DayLocator(interval=1))
        elif x_axis_bins == 'yearly':
            plt.gca().xaxis.set_major_locator(mdate.YearLocator())
            plt.gca().xaxis.set_minor_locator(mdate.MonthLocator(interval=12))

    except (ValueError, TypeError):
        logger['Threaddebug'].append(
            f"[{payload['props']['name']}] Problem formatting X axis scale: x_axis_bins = "
            f"{x_axis_bins}"
        )

# =============================================================================
def format_axis_x_ticks(ax, p_dict, k_dict, logger):
    """
    Format X axis tick properties

    Controls the format and placement of the tick marks on the X axis.
    -----
    :param class 'matplotlib.axes.AxesSubplot' ax:
    :param dict p_dict: plotting parameters
    :param dict k_dict: plotting kwargs
    :param dict logger:
    """

    try:
        # This should skip for devices that don't have date-based X axes.
        # if 'xAxisLabelFormat' in p_dict.keys():
        if 'xAxisLabelFormat' in p_dict:
            ax.tick_params(axis='x', **k_dict['k_major_x'])
            ax.tick_params(axis='x', **k_dict['k_minor_x'])
            ax.xaxis.set_major_formatter(mdate.DateFormatter(p_dict['xAxisLabelFormat']))
            format_axis_x_scale(x_axis_bins=p_dict.get('xAxisBins', '%A'), logger=LOG)

            # If the x-axis format has been set to None, let's hide the labels.
            if p_dict['xAxisLabelFormat'] == "None":
                ax.axes.xaxis.set_ticklabels([])

        return ax

    except (ValueError, TypeError):
        logger['Threaddebug'].append(
            f"[{payload['props']['name']}] Problem formatting X ticks Labels: {k_dict['k_major_x']}"
            f"\n{p_dict['xAxisLabelFormat']}\n{p_dict['xAxisBins']}"
        )

# =============================================================================
def format_axis_y_ticks(p_dict, k_dict, logger):
    """
    Format Y axis tick marks

    Controls the format and placement of Y ticks.
    -----
    :param dict p_dict: plotting parameters
    :param dict k_dict: plotting kwargs
    :param dict logger:
    """

    # custom_ticks_marks = p_dict['customTicksY'].strip()
    # custom_ticks_labels = p_dict['customTicksLabelY'].strip()
    custom_ticks_marks = [_.strip() for _ in p_dict['customTicksY']]
    custom_ticks_labels = [_.strip() for _ in p_dict['customTicksLabelY']]

    try:
        # Get the default tick values and labels (which we'll replace as needed.)
        marks, labels = plt.yticks()

        # If the user has not set custom tick values or labels, we're done.
        if len(custom_ticks_marks) == 0 and len(custom_ticks_labels)  == 0:
            return

        # If tick locations defined but tick labels are empty, let's use the tick
        # locations as the tick labels
        if len(custom_ticks_marks) > 0 and len(custom_ticks_labels)  == 0:
            custom_ticks_labels = custom_ticks_marks

        # Replace default Y tick values with the custom ones.
        # if custom_ticks_marks.lower() not in ('none', '') \
        #         and not custom_ticks_marks.isspace():
        #     marks = [float(_) for _ in custom_ticks_marks.split(",")]

        # Replace the default Y tick labels with the custom ones.
        # if custom_ticks_labels.lower() not in ('none', '') \
        #         and not custom_ticks_labels.isspace():
        #     labels = [f"{_.strip()}" for _ in custom_ticks_labels.split(",")]

        plt.yticks(marks, labels)

    except (KeyError, ValueError):
        logger['Threaddebug'].append(
            f"[{payload['props']['name']}] Problem formatting Y axis  ticks: customAxisLabelY = "
            f"{p_dict['customAxisLabelY']}"
        )
        logger['Threaddebug'].append(
            f"[{payload['props']['name']}] Problem formatting Y1 axis label: k_y_axis_font = "
            f"{k_dict['k_y_axis_font']}"
        )
        logger['Threaddebug'].append(
            f"[{payload['props']['name']}] Problem formatting Y1 axis label: customTicksY = "
            f"{p_dict['customTicksY']}"
        )

# =============================================================================
def format_axis_y(ax, p_dict, k_dict, logger):
    """
    Format Y1 axis display properties

    Controls the format and properties of the Y axis.
    -----
    :param class 'matplotlib.axes.AxesSubplot' ax:
    :param dict p_dict: plotting parameters
    :param dict k_dict: plotting kwargs
    :param dict logger:
    """
    # TODO: Balance the axis methods.  We should have:
    #       x_label
    #       x_scale
    #       x_ticks
    #       y1_label
    #       y1_scale
    #       y1_ticks
    #       y1_min_max
    #       y2_label
    #       y2_scale
    #       y2_ticks
    #       y2_min_max

    try:
        ax.tick_params(axis='y', **k_dict['k_major_y'])
        ax.tick_params(axis='y', **k_dict['k_minor_y'])
        ax.yaxis.set_major_formatter(
            mtick.FormatStrFormatter(f"%.{int(p_dict.get('yAxisPrecision', '0'))}f")
        )

        # Mirror Y axis values on Y2. Not all charts will support this option.
        try:
            if p_dict['yMirrorValues']:
                ax.tick_params(labelright=True)

                # A user may want tick labels only on Y2.
                if not p_dict['yMirrorValuesAlsoY1']:
                    ax.tick_params(labelleft=False)

        except KeyError:
            pass

        return ax

    except (ValueError, TypeError):
        name = payload['props']['name']
        logger['Threaddebug'].append(
            f"[{name}] Problem formatting Y ticks: k_major_y = {k_dict['k_major_y']}"
        )
        logger['Threaddebug'].append(
            f"[{name}] Problem formatting Y ticks: k_minor_x = {k_dict['k_minor_y']}"
        )
        lbl_fmt = mtick.FormatStrFormatter(
            f"[{name}] %.{int(p_dict['yAxisPrecision'])}f"
        )
        logger['Threaddebug'].append(
            f"[{name}] Problem formatting Y ticks: xAxisLabelFormat = {lbl_fmt}"
        )
        logger['Threaddebug'].append(
            f"[{name}] Problem formatting Y ticks: yMirrorValues = {p_dict['yMirrorValues']}"
        )
        logger['Threaddebug'].append(
            f"[{name}] Problem formatting Y ticks: yMirrorValuesAlsoY1 = "
            f"{p_dict['yMirrorValuesAlsoY1']}"
        )

# =============================================================================
def format_axis_y1_label(p_dict, k_dict, logger):
    """
    Format Y1 axis labels
    Controls the format and placement of labels for the Y1 axis.
    -----
    :param dict p_dict: plotting parameters
    :param dict k_dict: plotting kwargs
    :param dict logger:
    """

    font_main = p_dict.get('fontMain', 'Arial')  # Main font style
    rotate = int(p_dict.get('yAxisRotate', 0))
    v_align = {'-90': 'center', '-45': 'bottom', '0': 'center', '45': 'top', '90': 'center'}

    try:
        plt.ylabel(p_dict.get('customAxisLabelY', ''), **k_dict['k_y_axis_font'])

        if p_dict['customSizeFont']:
            plt.yticks(
                fontname=font_main, fontsize=int(p_dict['customTickFontSize']), rotation=rotate,
                va=v_align[str(rotate)]
            )
        else:
            plt.yticks(
                fontname=font_main, fontsize=int(p_dict['tickFontSize']), rotation=rotate,
                va=v_align[str(rotate)]
            )

    except (ValueError, TypeError):
        name = payload['props']['name']
        logger['Threaddebug'].append(
            f"[{name}] Problem formatting Y1 axis label: customAxisLabelY "
            f"= {p_dict['customAxisLabelY']}"
        )
        logger['Threaddebug'].append(
            f"[{name}] Problem formatting Y1 axis label: k_y_axis_font = "
            f"{k_dict['k_y_axis_font']}"
        )

# =============================================================================
def format_axis_y1_min_max(p_dict, logger):
    """
    Format Y1 axis range limits

    Setting the limits before the plot turns off autoscaling, which causes the limit that's not set
    to behave weirdly at times. This block is meant to overcome that weirdness for something more
    desirable.
    -----
    :param dict p_dict: plotting parameters
    :param dict logger:
    """

    try:

        y_min = min(p_dict['data_array'])
        y_max = max(p_dict['data_array'])
        y_min_wanted = p_dict['yAxisMin']
        y_max_wanted = p_dict['yAxisMax']

        # Since the min / max is used here only for chart boundaries, we "trick" Matplotlib by
        # using a number that's very nearly zero.
        if y_min == 0:
            y_min = 0.000001

        if y_max == 0:
            y_max = 0.000001

        # Y min
        if isinstance(y_min_wanted, str) and y_min_wanted.lower() == 'none':
            if y_min > 0:
                y_axis_min = y_min * (1 - (1 / abs(y_min) ** 1.25))
            else:
                y_axis_min = y_min * (1 + (1 / abs(y_min) ** 1.25))
        else:
            y_axis_min = float(y_min_wanted)

        # Y max
        if isinstance(y_max_wanted, str) and y_max_wanted.lower() == 'none':
            if y_max > 0:
                y_axis_max = y_max * (1 + (1 / abs(y_max) ** 1.25))
            else:
                y_axis_max = y_max * (1 - (1 / abs(y_max) ** 1.25))

        else:
            y_axis_max = float(y_max_wanted)

        plt.ylim(ymin=y_axis_min, ymax=y_axis_max)

    except (ValueError, TypeError):
        logger['Warning'].append(
            f"[{payload['props']['name']}] Error setting axis limits for Y1. Will rely on "
            f"Matplotlib to determine limits."
        )

# =============================================================================
# this is currently unused.
def format_axis_y2_label(p_dict, k_dict, logger):
    """
    Format Y2 axis properties

    Controls the format and placement of labels for the Y2 axis.
    -----
    :param dict p_dict: plotting parameters
    :param dict k_dict: plotting kwargs
    :param dict logger:
    """

    font_main = p_dict.get('fontMain', 'Arial')  # Main font style

    try:
        plt.ylabel(p_dict['customAxisLabelY2'], **k_dict['k_y_axis_font'])

        if p_dict['customSizeFont']:
            plt.yticks(fontname=font_main, fontsize=int(p_dict['customTickFontSize']))
        else:
            plt.yticks(fontname=font_main, fontsize=int(p_dict['tickFontSize']))

    except (KeyError, ValueError) as err:
        logger['Threaddebug'].append(
            f"[{payload['props']['name']}] Problem formatting axis labels: {err}"
        )

# =============================================================================
def format_best_fit_line_segments(ax, dates_to_plot, line, p_dict, logger):
    """
    Adds best fit line segments to plots

    The format_best_fit_line_segments method provides a utility to add "best fit lines" to select
    types of charts (best fit lines are not appropriate for all chart types).
    -----
    :param class 'matplotlib.axes.AxesSubplot' ax:
    :return numpy.ndarray dates_to_plot:
    :param int line:
    :param dict p_dict: plotting parameters
    :return ax:
    :param dict logger:
    """

    LOG['Debug'].append(f"[{payload['props']['name']}] Formatting best fit line segments.")
    try:
        color = p_dict.get(f'line{line}BestFitColor', '#FF0000')

        ax.plot(
            np.unique(dates_to_plot),
            np.poly1d(np.polyfit(dates_to_plot, p_dict[f'y_obs{line}'], 1))
            (np.unique(dates_to_plot)),
            color=color,
            zorder=1
        )

        return ax

    except TypeError as sub_error:
        name = payload['props']['name']
        logger['Threaddebug'].append(f"[{name}] p_dict: {p_dict}.")
        logger['Threaddebug'].append(f"[{name} dates_to_plot: {dates_to_plot}.")
        logger['Warning'].append(
            f"[{name} There is a problem with the best fit line segments settings. "
            f"Error: {sub_error}. See plugin log for more information."
        )

# =============================================================================
def format_custom_line_segments(ax, plug_dict, p_dict, k_dict, logger, orient="horiz"):
    """
    Chart custom line segments handler

    Process any custom line segments and add them to the matplotlib axes object.
    -----
    :param dict plug_dict:
    :param class 'matplotlib.axes.AxesSubplot' ax:
    :param dict p_dict: plotting parameters
    :param dict k_dict: plotting kwargs
    :param dict logger:
    :param str orient: orientation of custom line segments
    """

    # Plot the custom lines if needed.  Note that these need to be plotted after the legend is
    # established, otherwise some characteristics of the min/max lines will take over the legend
    # props.

    if p_dict['verboseLogging']:
        logger['Debug'].append(f"[{payload['props']['name']}] Formatting custom line segments.")
        logger['Debug'].append(f"Custom Segments Payload: {p_dict['customLineSegments']}")

    if p_dict['enableCustomLineSegments'] and p_dict['customLineSegments'] not in ("", "None"):
        try:
            # constants_to_plot will be (val, rgb) or ((val, rgb), (val, rgb))
            constants_to_plot = p_dict['customLineSegments']
            cls = ax

            # If a single tuple comes in, we need to tuple the tuple.  (a, b) --> ((a, b),)
            if not isinstance(constants_to_plot[0], tuple):
                constants_to_plot = (constants_to_plot,)

            for element in constants_to_plot:

                # ===============================  Horizontal  ================================
                if orient == 'horiz':
                    if isinstance(element, tuple):
                        cls = ax.axhline(
                            element[0],
                            color=element[1],
                            linestyle=p_dict['customLineStyle'],
                            marker='',
                            **k_dict['k_custom']
                        )

                    # If we want to promote custom line segments, we need to add them to the list
                    # that's used to calculate the Y axis limits.
                    if plug_dict.get('promoteCustomLineSegments', False):
                        p_dict['data_array'].append(element[0])

                # ================================  Vertical  =================================
                elif orient == 'vert':
                    if isinstance(element, tuple):
                        cls = ax.axvline(
                            element[0],
                            color=element[1],
                            linestyle=p_dict['customLineStyle'],
                            marker='',
                            **k_dict['k_custom']
                        )

                    if plug_dict.get('promoteCustomLineSegments', False):
                        p_dict['data_array'].append(element[0])

                # ==================================  Other  ==================================
                else:
                    cls = ax.axhline(
                        y=constants_to_plot[0],
                        color=constants_to_plot[1],
                        linestyle=p_dict['customLineStyle'],
                        marker='',
                        **k_dict['k_custom']
                    )

                    if plug_dict.get('promoteCustomLineSegments', False):
                        p_dict['data_array'].append(constants_to_plot[0])

            return cls

        except Exception as sub_error:
            logger['Warning'].append(
                f"[{payload['props']['name']}] There is a problem with the custom line segments "
                f"settings. {sub_error}. See plugin log for more information."
            )

# =============================================================================
def format_dates(list_of_dates, logger):
    """
    Convert date strings to date objects

    Convert string representations of date values to mdate values for charting.
    -----
    :param list list_of_dates:
    :param dict logger:
    """

    LOG['Debug'].append(f"[{payload['props']['name']}] Formatting dates.")
    dates_to_plot = []
    dates_to_plot_m = []

    try:
        dates_to_plot = [date_parse(obs) for obs in list_of_dates]
        dates_to_plot_m = mdate.date2num(dates_to_plot)

        return dates_to_plot_m

    except (KeyError, ValueError):
        name = payload['props']['name']
        logger['Threaddebug'].append(
            f"[{name}] Problem formatting dates: list_of_dates = {list_of_dates}"
        )
        logger['Threaddebug'].append(
            f"[{name}] Problem formatting dates: dates_to_plot = {dates_to_plot}"
        )
        logger['Threaddebug'].append(
            f"[{name}] Problem formatting dates: dates_to_plot_m = {dates_to_plot_m}"
        )

# =============================================================================
def format_grids(p_dict, k_dict, logger):
    """
    Format matplotlib grids

    Format grids for visibility and properties.
    -----
    :param dict p_dict: plotting parameters
    :param dict k_dict: plotting kwargs
    :param dict logger:
    """

    LOG['Debug'].append(f"[{payload['props']['name']}] Formatting grids.")

    try:
        if p_dict['showxAxisGrid']:
            plt.gca().xaxis.grid(True, **k_dict['k_grid_fig'])

        if p_dict['showyAxisGrid']:
            plt.gca().yaxis.grid(True, **k_dict['k_grid_fig'])

    except (KeyError, ValueError):
        logger['Threaddebug'].append(
            f"[{payload['props']['name']}]Problem formatting grids: showxAxisGrid = "
            f"{p_dict['showxAxisGrid']}"
        )
        logger['Threaddebug'].append(
            f"[{payload['props']['name']}] Problem formatting grids: k_grid_fig = "
            f"{k_dict['k_grid_fig']}"
        )

# =============================================================================
def format_title(p_dict, k_dict, loc, align='center', logger=None):
    """
    Plot the figure's title
    -----
    :param p_dict:
    :param k_dict:
    :param loc:
    :param str align:
    :param dict logger:
    :return:
    """
    try:
        plt.suptitle(p_dict['chartTitle'], position=loc, ha=align, **k_dict['k_title_font'])
    except KeyError as sub_error:
        logger['Warning'].append(f"[{payload['props']['name']}] Title Error: {sub_error}")

# =============================================================================
def get_data(data_source, logger):
    """
    Retrieve data from CSV file.

    Reads data from source CSV file and returns a list of tuples for charting. The data are
    provided as unicode strings [('formatted date', 'observation'), ...]
    -----
    :param unicode data_source:
    :param dict logger:
    """

    LOG['Debug'].append(f"[{payload['props']['name']}] Retrieving CSV data.")

    final_data = []
    now = dt.datetime.now()
    now_text = dt.datetime.strftime(now, '%Y-%m-%d %H:%M:%S')

    try:
        # Get the data
        with open(data_source, "r", encoding="utf-8") as data_file:
            csv_data = csv.reader(data_file, delimiter=',')

            # Convert the csv object to a list
            _ = [final_data.append(item) for item in csv_data]

        # Process the data a bit more for charting
        final_data = convert_the_data(final_data=final_data, data_source=data_source, logger=LOG)

        return final_data

    # If we can't find the target CSV file, we create a phony proxy which the plugin can process
    # without dying.
    except Exception as sub_error:
        final_data.extend([('timestamp', 'placeholder'), (now_text, 0)])
        logger['Warning'].append(
            f"[{payload['props']['name']}] Error downloading CSV data: {sub_error}. See plugin "
            f"log for more information."
        )

        return final_data

# =============================================================================
def hide_anomalies(data, props=True, logger=[]):
    """Detect outliers in data and replace them with 'NaN'.

    Credit: https://gist.github.com/wmlba/89bc2f4556b8ee397ca7a5017b497657#file-outlier_std-py
    -----
    :param list data:
    :param dict props:
    :param dict logger:
    """
    LOG['Debug'].append(f"[{payload['props']['name']}] Identifying and disguising anomalous data.")

    anomalies = []

    std_val = int(props.get('filterAnomalies', "0"))

    if std_val > 0:
        # Set upper and lower limit to 2 standard deviations
        data_std  = np.std(data)
        data_mean = np.mean(data)
        filter_val   = data_std * std_val

        lower_limit = data_mean - filter_val
        upper_limit = data_mean + filter_val

        # Generate outliers
        for outlier in data:
            if outlier > upper_limit or outlier < lower_limit:
                anomalies.append(outlier)

        final_data = [_ if _ not in anomalies else 'NaN' for _ in data]

        if 'NaN' in final_data:
            logger['Warning'].append(
                f"[{payload['props']['name']}] Outliers in data are hidden (greater than "
                f"{std_val} standard deviations [{filter_val}])."
            )
        value = final_data

    else:
        value = data

    return value

# =============================================================================
def make_chart_figure(width, height, p_dict):
    """
    Create the matplotlib figure object and create the main axes element.

    Create the figure object for charting and include one axes object. The method also add a few
    customizations when defining the objects.
    -----
    :param float width:
    :param float height:
    :param dict p_dict: plotting parameters
    """

    dpi = float(plt.rcParams['savefig.dpi'])
    height = float(height)
    width = float(width)

    fig = plt.figure(1, figsize=(width / dpi, height / dpi))
    ax = fig.add_subplot(111, facecolor=p_dict['faceColor'])
    ax.margins(0.04, 0.05)
    _ = [ax.spines[spine].set_color(p_dict['spineColor'])
         for spine in ('top', 'bottom', 'left', 'right')
         ]

    return ax

# =============================================================================
def prune_data(x_data, y_data, limit, new_old, logger):  # noqa
    """
    Prune data to display subset of available data

    The prune_data() method is used to show a subset of available data. Users enter a number of
    days into a device config dialog, the method then drops any observations that are outside that
    window.
    -----
    :rtype: object
    :param list x_data:
    :param list y_data:
    :param int limit:
    :param unicode new_old:
    :param dict logger:
    :return:
    """

    LOG['Debug'].append(f"[{payload['props']['name']}] Pruning data as needed.")

    now = dt.datetime.now()
    delta = now - dt.timedelta(days=limit)
    logger['Debug'].append(
        f"[{payload['props']['name']}] Pruning chart data: {delta} through {now}."
    )

    # Convert dates from string to datetime for filters
    for i, x in enumerate(x_data):
        x_data[i] = dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f')

    # Create numpy arrays from the data
    x_obs_d = np.array(x_data)
    y_obs_d = np.array(y_data)

    # Get the indexes of the date data that fits the time window
    idx = np.where((x_obs_d >= delta) & (x_obs_d <= now))

    # Keep only the indexed observations, and put them back into lists
    final_x = x_obs_d[idx].tolist()
    final_y = y_obs_d[idx].tolist()

    # If final_x is of length zero, no observations fit the requested time
    # mask. We return empty lists so that there's something to chart.
    if len(final_x) == 0:
        logger['Warning'].append(
            f"[{payload['props']['name']}] All data outside time series limits. No observations "
            f"to return."
        )
        final_x = [dt.datetime.now()]
        final_y = [0]

    # Return dates back to string form (they get processed later by matplotlib) mdate.
    for i, x in enumerate(final_x):
        final_x[i] = dt.datetime.strftime(x, '%Y-%m-%d %H:%M:%S.%f')

    return final_x, final_y

# =============================================================================
def save(logger):
    """
    Title Placeholder

    Body placeholder
    -----
    :param logger:
    :return:
    """
    try:
        top_margin    = 0.9
        bottom_margin = 0.2
        if payload['props']['chart_type'] == 'calendar':
            bottom_margin = 0.34
        elif payload['props']['chart_type'] == 'composite forecast':
            top_margin = 0.93
            bottom_margin = 0.05

        if payload['p_dict']['chartPath'] != '' and payload['p_dict']['fileName'] != '':
            plt.tight_layout()
            plt.subplots_adjust(top=top_margin, bottom=bottom_margin)
            plt.savefig(
                f"{payload['p_dict']['chartPath']}{payload['p_dict']['fileName']}",
                **payload['k_dict']['k_plot_fig']
            )
            logger['Debug'].append(f"[{payload['props']['name']}] Chart file saved to disk.")

        else:
            if payload['props']['isChart']:
                logger['Warning'].append(f"[{payload['props']['name']}] Chart not saved.")

        # Note that this garbage collection may be unneeded since the process will end.
        plt.clf()
        plt.close('all')

    except RuntimeError as err:
        # There are too many observations in the CSV data.
        if "exceeds Locator.MAXTICKS" in traceback.format_exc(err):
            logger['Critical'].append(f"[{payload['props']['name']}] Chart not saved. [Too many observeations.]")


text:
"""
The MIT License (MIT)

Copyright 2015 Umbrella Tech.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from django.forms import ModelForm
from django.forms import CharField
from django.forms import PasswordInput
from suap_webconf.models import Participante

__author__ = 'Kelson da Costa Medeiros <kelsoncm@gmail.com>'

class ParticipanteAnonimoForm(ModelForm):

    username = CharField(label='CPF/Matricula')

    class Meta:
        model = Participante
        fields = ['nome', 'username', 'email', 'celular', ]
        hidden_fields = ['evento']

class ParticipanteManualForm(ModelForm):

    password = CharField(widget=PasswordInput)

    class Meta:
        model = Participante
        fields = ['username', 'password', ]
        hidden_fields = ['evento']

    def get_participante(self):
        return Participante.objects.filter(evento=self.instance.evento,
                                           username=self.data['username'],
                                           password=self.data['password']).first()

    def is_valid(self):
        if super(ParticipanteManualForm, self).is_valid():
            if self.get_participante():
                return True
            else:
                self.add_error(None, 'O usuário e/ou a senha estão errados.')
                return False
        else:
            return False


text:
//Problem 14. Modify a Bit at Given Position

//We are given an integer number n, a bit value v (v=0 or 1) and a position p.
//Write a sequence of operators (a few lines of C# code) that modifies n to hold the value v at the position p
//from the binary representation of n while preserving all other bits in n.
//Examples:

//n binary representation of n  p	    v	   binary result	result
//5	    00000000 00000101	      2	    0	00000000 00000001	  1
//0	    00000000 00000000	      9	    1	00000010 00000000	  512
//15	00000000 00001111	      1	    1	00000000 00001111	  15
//5343  00010100 11011111	      7	    0	00010100 01011111	  5215
//62241 11110011 00100001	      11	0	11110011 00100001	  62241

using System;

class ModifyBitAtGivenPosition
{
	static void Main()
	{
		string task = "Problem 14. Modify a Bit at Given Position\n\nWe are given an integer number n, a bit value v (v=0 or 1) and a position p.\nWrite a sequence of operators (a few lines of C# code) that modifies n to hold\nthe value v at the position p from the binary representation of n while\npreserving all other bits in n.\nExamples:\nn  binary representation of n	p	v	binary result	      result\n5	00000000 00000101	2	0	00000000 00000001	1\n0	00000000 00000000	9	1	00000010 00000000	512\n15	00000000 00001111	1	1	00000000 00001111	15\n5343	00010100 11011111	7	0	00010100 01011111	5215\n62241	11110011 00100001	11	0	11110011 00100001	62241\n";
		string separator = new string('*', Console.WindowWidth);

		Console.WriteLine(task);
		Console.WriteLine(separator);

		Console.WriteLine("Enter number:");
		int number = int.Parse(Console.ReadLine());

		Console.WriteLine("Enter position:");
		int position = int.Parse(Console.ReadLine());

		Console.WriteLine("Enter value:");
		int value = int.Parse(Console.ReadLine());

		int result = (number & ~(1 << position)) | (value << position);

		Console.WriteLine("number: {0}    result: {1}", number, result);
	}
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Make-Out Mood Enhancer</title>
		<link>http://bvs.wikidot.com/forum/t-47664/make-out-mood-enhancer</link>
		<description>Posts in the discussion thread "Make-Out Mood Enhancer" - How?</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 04:49:21 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-47664#post-127272</guid>
				<title>Re: Make-Out Mood Enhancer</title>
				<link>http://bvs.wikidot.com/forum/t-47664/make-out-mood-enhancer#post-127272</link>
				<description></description>
				<pubDate>Tue, 18 Mar 2008 19:35:56 +0000</pubDate>
				<wikidot:authorName>BvS-Uzuki</wikidot:authorName>				<wikidot:authorUserId>78144</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

Yeah, I updated the Wiki's potion palace page.

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-47664#post-127268</guid>
				<title>Re: Make-Out Mood Enhancer</title>
				<link>http://bvs.wikidot.com/forum/t-47664/make-out-mood-enhancer#post-127268</link>
				<description></description>
				<pubDate>Tue, 18 Mar 2008 19:29:54 +0000</pubDate>
				<wikidot:authorName>Fax</wikidot:authorName>				<wikidot:authorUserId>90931</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

Yeah, but you've got to do it while in bankai. More info here.

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-47664#post-127261</guid>
				<title>Re: Make-Out Mood Enhancer</title>
				<link>http://bvs.wikidot.com/forum/t-47664/make-out-mood-enhancer#post-127261</link>
				<description></description>
				<pubDate>Tue, 18 Mar 2008 19:21:09 +0000</pubDate>
				<wikidot:authorName>BvS-Uzuki</wikidot:authorName>				<wikidot:authorUserId>78144</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

I think you need to mix a Stark Moonlight with a Stark Moonlight.

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-47664#post-127241</guid>
				<title>Make-Out Mood Enhancer</title>
				<link>http://bvs.wikidot.com/forum/t-47664/make-out-mood-enhancer#post-127241</link>
				<description></description>
				<pubDate>Tue, 18 Mar 2008 18:51:51 +0000</pubDate>
				<wikidot:authorName>Fax</wikidot:authorName>				<wikidot:authorUserId>90931</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

Anyone know how to make one of these?

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


text:
package com.decoverri.treasureGenerator.dao.treasure.complement;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.decoverri.treasureGenerator.enums.MagicItemStrength;
import com.decoverri.treasureGenerator.model.treasure.complement.ScrollLevel;

@Component
public class ScrollLevelDao {

	private Session session;

	@Autowired
	public ScrollLevelDao(Session session) {
		this.session = session;
	}

	public void saveOrUpdate(ScrollLevel scroll) {
		session.saveOrUpdate(scroll);
	}

	public int getScrollLevel(MagicItemStrength strength, int roll) {
		Query query = session.createQuery("select sl.spellLevel from ScrollLevel sl where sl.strength = :strength and :roll >= bottomValue and :roll <=topValue")
							.setParameter("strength", strength)
							.setParameter("roll", roll);
		return (Integer) query.list().get(0);
	}

}


text:
package server

import (
	"fmt"
	"time"

	"github.com/containers/storage"
	pkgstorage "github.com/kubernetes-incubator/cri-o/pkg/storage"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"golang.org/x/net/context"
	pb "k8s.io/kubernetes/pkg/kubelet/apis/cri/v1alpha1/runtime"
)

// ImageStatus returns the status of the image.
func (s *Server) ImageStatus(ctx context.Context, req *pb.ImageStatusRequest) (resp *pb.ImageStatusResponse, err error) {
	const operation = "image_status"
	defer func() {
		recordOperation(operation, time.Now())
		recordError(operation, err)
	}()

	logrus.Debugf("ImageStatusRequest: %+v", req)
	image := ""
	img := req.GetImage()
	if img != nil {
		image = img.Image
	}
	if image == "" {
		return nil, fmt.Errorf("no image specified")
	}
	images, err := s.StorageImageServer().ResolveNames(image)
	if err != nil {
		if err == pkgstorage.ErrCannotParseImageID {
			images = append(images, image)
		} else {
			return nil, err
		}
	}
	// match just the first registry as that's what kube meant
	image = images[0]
	status, err := s.StorageImageServer().ImageStatus(s.ImageContext(), image)
	if err != nil {
		if errors.Cause(err) == storage.ErrImageUnknown {
			return &pb.ImageStatusResponse{}, nil
		}
		return nil, err
	}
	resp = &pb.ImageStatusResponse{
		Image: &pb.Image{
			Id:          status.ID,
			RepoTags:    status.RepoTags,
			RepoDigests: status.RepoDigests,
			Size_:       *status.Size,
		},
	}
	logrus.Debugf("ImageStatusResponse: %+v", resp)
	return resp, nil
}


text:
function switchMessage(name, thing) {
  switch (thing) {
    case 'controller': {
      return 'are you sure you wish to delete ' + name + ' ' + thing + ' ?';
    }
    case 'model': {
      return (
        'this will also delete the migrations for this model which could cause error when running migrations, are you sure you want to delete ' +
        name +
        ' ' +
        thing +
        ' ?'
      );
    }
    default:
      null;
  }
}
const deleteQuestionPrompt = (name, thing) => {
  return [
    {
      type: 'confirm',
      name: 'confirmation',
      message: switchMessage(name, thing)
    }
  ];
};

module.exports = deleteQuestionPrompt;