text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision.serialization;

import com.yahoo.config.provision.AllocatedHosts;
import com.yahoo.config.provision.ClusterMembership;
import com.yahoo.config.provision.DockerImage;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.slime.ArrayTraverser;
import com.yahoo.slime.Cursor;
import com.yahoo.slime.Inspector;
import com.yahoo.slime.Slime;
import com.yahoo.slime.SlimeUtils;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;

/**
 * The hosts allocated to an application.
 * This can be serialized to/from JSON.
 * This is immutable.
 *
 * @author Ulf Lilleengen
 * @author bratseth
 */
public class AllocatedHostsSerializer {

    // WARNING: Since there are multiple servers in a ZooKeeper cluster and they upgrade one by one
    //          (and rewrite all nodes on startup), changes to the serialized format must be made
    //          such that what is serialized on version N+1 can be read by version N:
    //          - ADDING FIELDS: Always ok
    //          - REMOVING FIELDS: Stop reading the field first. Stop writing it on a later version.
    //          - CHANGING THE FORMAT OF A FIELD: Don't do it bro.

    private static final String mappingKey = "mapping";
    private static final String hostSpecKey = "hostSpec";
    private static final String hostSpecHostNameKey = "hostName";
    private static final String hostSpecMembershipKey = "membership";

    private static final String realResourcesKey = "realResources";
    private static final String advertisedResourcesKey = "advertisedResources";
    private static final String requestedResourcesKey = "requestedResources";
    private static final String vcpuKey = "vcpu";
    private static final String memoryKey = "memory";
    private static final String diskKey = "disk";
    private static final String bandwidthKey = "bandwidth";
    private static final String diskSpeedKey = "diskSpeed";
    private static final String storageTypeKey = "storageType";
    private static final String architectureKey = "architecture";
    private static final String gpuKey = "gpu";
    private static final String gpuCountKey = "gpuCount";
    private static final String gpuMemoryKey = "gpuMemory";

    /** Wanted version */
    private static final String hostSpecVespaVersionKey = "vespaVersion";

    /** Wanted docker image repo */
    private static final String hostSpecDockerImageRepoKey = "dockerImageRepo";

    /** Current version */
    private static final String hostSpecCurrentVespaVersionKey = "currentVespaVersion";
    private static final String hostSpecNetworkPortsKey = "ports";

    public static byte[] toJson(AllocatedHosts allocatedHosts) throws IOException {
        Slime slime = new Slime();
        toSlime(allocatedHosts, slime.setObject());
        return SlimeUtils.toJsonBytes(slime);
    }

    public static void toSlime(AllocatedHosts allocatedHosts, Cursor cursor) {
        Cursor array = cursor.setArray(mappingKey);
        for (HostSpec host : allocatedHosts.getHosts())
            toSlime(host, array.addObject().setObject(hostSpecKey));
    }

    private static void toSlime(HostSpec host, Cursor object) {
        object.setString(hostSpecHostNameKey, host.hostname());
        host.membership().ifPresent(membership -> {
            object.setString(hostSpecMembershipKey, membership.stringValue());
            object.setString(hostSpecVespaVersionKey, membership.cluster().vespaVersion().toFullString());
            membership.cluster().dockerImageRepo().ifPresent(repo -> object.setString(hostSpecDockerImageRepoKey, repo.untagged()));
        });
        toSlime(host.realResources(), object.setObject(realResourcesKey));
        toSlime(host.advertisedResources(), object.setObject(advertisedResourcesKey));
        host.requestedResources().ifPresent(resources -> toSlime(resources, object.setObject(requestedResourcesKey)));
        host.version().ifPresent(version -> object.setString(hostSpecCurrentVespaVersionKey, version.toFullString()));
        host.networkPorts().ifPresent(ports -> NetworkPortsSerializer.toSlime(ports, object.setArray(hostSpecNetworkPortsKey)));
    }

    private static void toSlime(NodeResources resources, Cursor resourcesObject) {
        resourcesObject.setDouble(vcpuKey, resources.vcpu());
        resourcesObject.setDouble(memoryKey, resources.memoryGb());
        resourcesObject.setDouble(diskKey, resources.diskGb());
        resourcesObject.setDouble(bandwidthKey, resources.bandwidthGbps());
        resourcesObject.setString(diskSpeedKey, diskSpeedToString(resources.diskSpeed()));
        resourcesObject.setString(storageTypeKey, storageTypeToString(resources.storageType()));
        resourcesObject.setString(architectureKey, architectureToString(resources.architecture()));
        if (!resources.gpuResources().isDefault()) {
            Cursor gpuObject = resourcesObject.setObject(gpuKey);
            gpuObject.setLong(gpuCountKey, resources.gpuResources().count());
            gpuObject.setDouble(gpuMemoryKey, resources.gpuResources().memoryGb());
        }
    }

    public static AllocatedHosts fromJson(byte[] json) {
        return fromSlime(SlimeUtils.jsonToSlime(json).get());
    }

    public static AllocatedHosts fromSlime(Inspector inspector) {
        Inspector array = inspector.field(mappingKey);
        Set<HostSpec> hosts = new LinkedHashSet<>();
        array.traverse((ArrayTraverser)(i, host) -> {
            hosts.add(hostFromSlime(host.field(hostSpecKey)));
        });
        return AllocatedHosts.withHosts(hosts);
    }

    private static HostSpec hostFromSlime(Inspector object) {
        if (object.field(hostSpecMembershipKey).valid()) { // Hosted
            return new HostSpec(object.field(hostSpecHostNameKey).asString(),
                                nodeResourcesFromSlime(object.field(realResourcesKey)),
                                nodeResourcesFromSlime(object.field(advertisedResourcesKey)),
                                optionalNodeResourcesFromSlime(object.field(requestedResourcesKey)), // TODO: Make non-optional when we serialize NodeResources.unspecified()
                                membershipFromSlime(object),
                                optionalString(object.field(hostSpecCurrentVespaVersionKey)).map(com.yahoo.component.Version::new),
                                NetworkPortsSerializer.fromSlime(object.field(hostSpecNetworkPortsKey)),
                                optionalDockerImage(object.field(hostSpecDockerImageRepoKey)));
        }
        else {
            return new HostSpec(object.field(hostSpecHostNameKey).asString(),
                                NetworkPortsSerializer.fromSlime(object.field(hostSpecNetworkPortsKey)));
        }
    }

    private static NodeResources nodeResourcesFromSlime(Inspector resources) {
        return new NodeResources(resources.field(vcpuKey).asDouble(),
                                 resources.field(memoryKey).asDouble(),
                                 resources.field(diskKey).asDouble(),
                                 resources.field(bandwidthKey).asDouble(),
                                 diskSpeedFromSlime(resources.field(diskSpeedKey)),
                                 storageTypeFromSlime(resources.field(storageTypeKey)),
                                 architectureFromSlime(resources.field(architectureKey)),
                                 gpuResourcesFromSlime(resources.field(gpuKey)));
    }

    private static NodeResources.GpuResources gpuResourcesFromSlime(Inspector gpu) {
        if (!gpu.valid()) return NodeResources.GpuResources.getDefault();
        return new NodeResources.GpuResources((int) gpu.field(gpuCountKey).asLong(),
                                              gpu.field(gpuMemoryKey).asDouble());
    }

    private static NodeResources optionalNodeResourcesFromSlime(Inspector resources) {
        if ( ! resources.valid()) return NodeResources.unspecified();
        return nodeResourcesFromSlime(resources);
    }

    private static NodeResources.DiskSpeed diskSpeedFromSlime(Inspector diskSpeed) {
        return switch (diskSpeed.asString()) {
            case "fast" -> NodeResources.DiskSpeed.fast;
            case "slow" -> NodeResources.DiskSpeed.slow;
            case "any" -> NodeResources.DiskSpeed.any;
            default -> throw new IllegalStateException("Illegal disk-speed value '" + diskSpeed.asString() + "'");
        };
    }

    private static String diskSpeedToString(NodeResources.DiskSpeed diskSpeed) {
        return switch (diskSpeed) {
            case fast -> "fast";
            case slow -> "slow";
            case any -> "any";
        };
    }

    private static NodeResources.StorageType storageTypeFromSlime(Inspector storageType) {
        return switch (storageType.asString()) {
            case "remote" -> NodeResources.StorageType.remote;
            case "local" -> NodeResources.StorageType.local;
            case "any" -> NodeResources.StorageType.any;
            default -> throw new IllegalStateException("Illegal storage-type value '" + storageType.asString() + "'");
        };
    }

    private static String storageTypeToString(NodeResources.StorageType storageType) {
        return switch (storageType) {
            case remote -> "remote";
            case local -> "local";
            case any -> "any";
        };
    }

    private static NodeResources.Architecture architectureFromSlime(Inspector architecture) {
        if ( ! architecture.valid()) return NodeResources.Architecture.x86_64;
        return switch (architecture.asString()) {
            case "x86_64" -> NodeResources.Architecture.x86_64;
            case "arm64" -> NodeResources.Architecture.arm64;
            case "any" -> NodeResources.Architecture.any;
            default -> throw new IllegalStateException("Illegal architecture value '" + architecture.asString() + "'");
        };
    }

    private static String architectureToString(NodeResources.Architecture architecture) {
        return switch (architecture) {
            case x86_64 -> "x86_64";
            case arm64 -> "arm64";
            case any -> "any";
        };
    }

    private static ClusterMembership membershipFromSlime(Inspector object) {
        return ClusterMembership.from(object.field(hostSpecMembershipKey).asString(),
                                      com.yahoo.component.Version.fromString(object.field(hostSpecVespaVersionKey).asString()),
                                      object.field(hostSpecDockerImageRepoKey).valid()
                                              ? Optional.of(DockerImage.fromString(object.field(hostSpecDockerImageRepoKey).asString()))
                                              : Optional.empty());
    }

    private static Optional<String> optionalString(Inspector inspector) {
        if ( ! inspector.valid()) return Optional.empty();
        return Optional.of(inspector.asString());
    }

    private static Optional<DockerImage> optionalDockerImage(Inspector inspector) {
        if ( ! inspector.valid()) return Optional.empty();
        return Optional.of(DockerImage.fromString(inspector.asString()));
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.geode.internal.cache;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Test;

public class VMLRURegionMapTest {

  @Test
  public void shouldBeMockable() throws Exception {
    VMLRURegionMap mockVMLRURegionMap = mock(VMLRURegionMap.class);

    when(mockVMLRURegionMap.centralizedLruUpdateCallback()).thenReturn(1);

    mockVMLRURegionMap.changeTotalEntrySize(1);

    verify(mockVMLRURegionMap, times(1)).changeTotalEntrySize(1);

    assertThat(mockVMLRURegionMap.centralizedLruUpdateCallback()).isEqualTo(1);
  }
}


text:
package com.rong.mineralistic.blocks;

import com.rong.mineralistic.OreManager;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.BlockFalling;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;

import java.util.List;
import java.util.Random;

public class BlockOreGravel extends BlockFalling implements IMetaLocalization {

    private int index;
    private IIcon[] textures;

    public BlockOreGravel(int index) {
        super(Material.craftedSnow);

        this.index = index;

        this.setBlockName(OreManager.gravelOre);
        this.setCreativeTab(CreativeTabs.tabBlock);
        this.setHardness(5.0F);
        this.setResistance(5.0F);
        this.setStepSound(soundTypeGravel);
    }

    @Override
    public void registerBlockIcons(IIconRegister iconReg) {
        this.textures = new IIcon[OreManager.getSubtypeCount(this.index)];

        for (int meta = 0; meta < this.textures.length; meta++) {
            textures[meta] = iconReg.registerIcon(OreManager.getTextureName(OreManager.gravelOre, this.index, meta));
        }
    }

    @Override
    public IIcon getIcon(int side, int meta) {
        return meta >= 0 && meta < textures.length ? textures[meta] : textures[0];
    }

    @Override
    @SideOnly(Side.CLIENT)
    public void randomDisplayTick(World world, int x, int y, int z, Random random) {
        OreManager.get(index, world.getBlockMetadata(x, y, z)).blockDisplayTick(world, x, y, z, random);
    }

    @Override
    @SideOnly(Side.CLIENT)
    @SuppressWarnings("unchecked")
    public void getSubBlocks(Item item, CreativeTabs tab, List list) {
        for (int meta = 0; meta < OreManager.getSubtypeCount(index); meta++) {
            list.add(new ItemStack(item, 1, meta));
        }
    }

    @Override
    public int getLightValue(IBlockAccess world, int x, int y, int z) {
        return OreManager.get(index, world.getBlockMetadata(x, y, z)).lightValue();
    }

    @Override
    public int damageDropped(int meta) {
        return meta;
    }

    @Override
    public String getUnlocalizedName(int meta) {
        return super.getUnlocalizedName() + "." + OreManager.get(index, meta).unlocalizedName();
    }
}


text:
use common::sense;

use Mojo::Base -strict;

$ENV{MOJO_MODE} = 'production';
$ENV{APPCONF_DIRS} = '/etc';

require Mojolicious::Commands;
Mojolicious::Commands->start_app('Essi::Mojo');


text:
package de.danoeh.antennapod.syndication.util;

import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/** Parses several date formats. */
public class SyndDateUtils {
	private static final String TAG = "DateUtils";

	private static final String[] RFC822DATES = { "dd MMM yy HH:mm:ss Z", };

	/** RFC 3339 date format for UTC dates. */
	public static final String RFC3339UTC = "yyyy-MM-dd'T'HH:mm:ss'Z'";

	/** RFC 3339 date format for localtime dates with offset. */
	public static final String RFC3339LOCAL = "yyyy-MM-dd'T'HH:mm:ssZ";

	private static ThreadLocal<SimpleDateFormat> RFC822Formatter = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat(RFC822DATES[0], Locale.US);
		}

	};

	private static ThreadLocal<SimpleDateFormat> RFC3339Formatter = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat(RFC3339UTC, Locale.US);
		}

	};

	public static Date parseRFC822Date(String date) {
		Date result = null;
		if (date.contains("PDT")) {
			date = date.replace("PDT", "PST8PDT");
		}
		if (date.contains(",")) {
			// Remove day of the week
			date = date.substring(date.indexOf(",") + 1).trim();
		}
		SimpleDateFormat format = RFC822Formatter.get();
		for (int i = 0; i < RFC822DATES.length; i++) {
			try {
				format.applyPattern(RFC822DATES[i]);
				result = format.parse(date);
				break;
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (result == null) {
			Log.e(TAG, "Unable to parse feed date correctly");
		}

		return result;
	}

	public static Date parseRFC3339Date(String date) {
		Date result = null;
		SimpleDateFormat format = RFC3339Formatter.get();
		boolean isLocal = date.endsWith("Z");
		if (date.contains(".")) {
			// remove secfrac
			int fracIndex = date.indexOf(".");
			String first = date.substring(0, fracIndex);
			String second = null;
			if (isLocal) {
				second = date.substring(date.length() - 1);
			} else {
				if (date.contains("+")) {
					second = date.substring(date.indexOf("+"));
				} else {
					second = date.substring(date.indexOf("-"));
				}
			}

			date = first + second;
		}
		if (isLocal) {
			try {
				result = format.parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			format.applyPattern(RFC3339LOCAL);
			// remove last colon
			StringBuffer buf = new StringBuffer(date.length() - 1);
			int colonIdx = date.lastIndexOf(':');
			for (int x = 0; x < date.length(); x++) {
				if (x != colonIdx)
					buf.append(date.charAt(x));
			}
			String bufStr = buf.toString();
			try {
				result = format.parse(bufStr);
			} catch (ParseException e) {
				e.printStackTrace();
				Log.e(TAG, "Unable to parse date");
			} finally {
				format.applyPattern(RFC3339UTC);
			}

		}

		return result;

	}

	/**
	 * Takes a string of the form [HH:]MM:SS[.mmm] and converts it to
	 * milliseconds.
	 */
	public static long parseTimeString(final String time) {
		String[] parts = time.split(":");
		long result = 0;
		int idx = 0;
		if (parts.length == 3) {
			// string has hours
			result += Integer.valueOf(parts[idx]) * 3600000L;
			idx++;
		}
		result += Integer.valueOf(parts[idx]) * 60000L;
		idx++;
		result += (Float.valueOf(parts[idx])) * 1000L;
		return result;
	}

    public static String formatRFC822Date(Date date) {
        SimpleDateFormat format = RFC822Formatter.get();
        return format.format(date);
    }

    public static String formatRFC3339Local(Date date) {
        SimpleDateFormat format = RFC3339Formatter.get();
        format.applyPattern(RFC3339LOCAL);
        String result = format.format(date);
        format.applyPattern(RFC3339UTC);
        return result;
    }

    public static String formatRFC3339UTC(Date date) {
        SimpleDateFormat format = RFC3339Formatter.get();
        format.applyPattern(RFC3339UTC);
        return format.format(date);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="NiceSpinner">
        <attr name="arrowTint" format="color" />
        <attr name="hideArrow" format="boolean" />
        <attr name="arrowDrawable" format="reference|color"/>
        <attr name="dropDownListPaddingBottom" format="dimension"/>
        <attr name="backgroundSelector" format="integer"/>
        <attr name="textTint" format="color"/>
    </declare-styleable>
</resources>


text:
require 'spec_helper'
#require 'user'
#require 'todo_item'

describe "reverting records" do

  it "finds that the user Adam has not changed yet" do
    React::IsomorphicHelpers.load_context
    ReactiveRecord.load do
      User.find_by_first_name("Adam")
    end.then do |user|
      expect(user).not_to be_changed
    end
  end

  it "creates a new todo which should be changed (because its new)" do
    new_todo = TodoItem.new({title: "Adam is not getting this todo"})
    expect(new_todo).to be_changed
  end

  it "adds the todo to adam's todos and expects adam to change" do
    adam = User.find_by_first_name("Adam")
    adam.todo_items << TodoItem.find_by_title("Adam is not getting this todo")
    expect(adam).to be_changed
  end

  it "will show that the new todo is still changed" do
    expect(TodoItem.find_by_title("Adam is not getting this todo")).to be_changed
  end

  it "can be reverted and the todo will not be changed" do
    todo = TodoItem.find_by_title("Adam is not getting this todo")
    todo.revert
    expect(todo).not_to be_changed
  end

  it "will not have changed adam" do
    adam = User.find_by_first_name("Adam")
    expect(User.find_by_first_name("Adam")).not_to be_changed
  end

  it "is time to test going the other way, lets give adam a todo again" do
    new_todo = TodoItem.new({title: "Adam is still not getting this todo"})
    adam = User.find_by_first_name("Adam")
    adam.todo_items << new_todo
    expect(adam).to be_changed
  end

  it "an be revert" do
    adam = User.find_by_first_name("Adam")
    adam.revert
    expect(adam).not_to be_changed
  end

  it "finds the todo is still changed" do
    expect(TodoItem.find_by_title("Adam is still not getting this todo")).to be_changed
  end

  async "can change an attribute, revert, and make sure nothing else changes" do
    ReactiveRecord.load do
      User.find_by_email("mitch@catprint.com").last_name
      User.find_by_email("mitch@catprint.com").todo_items.all.count
    end.then do |original_todo_count|
      puts "current todo count for mitch: #{original_todo_count}"
      mitch = User.find_by_email("mitch@catprint.com")
      original_last_name = mitch.last_name
      mitch.last_name = "xxxx"
      mitch.save do
        mitch.revert
        new_items_count = mitch.todo_items.all.count
        mitch.last_name = original_last_name
        mitch.save.then do
          async { expect(new_items_count).to eq(original_todo_count) }
        end
      end
    end
  end
end


text:
@interface SMCallTraceTimeCostModel : NSObject

@property (nonatomic, strong) NSString *className;       //类名
@property (nonatomic, strong) NSString *methodName;      //方法名
@property (nonatomic, assign) BOOL isClassMethod;        //是否是类方法
@property (nonatomic, assign) NSTimeInterval timeCost;   //时间消耗
@property (nonatomic, assign) NSUInteger callDepth;      //Call 层级
@property (nonatomic, copy) NSString *path;              //路径
@property (nonatomic, assign) BOOL lastCall;             //是否是最后一个 Call
@property (nonatomic, assign) NSUInteger frequency;      //访问频次
@property (nonatomic, strong) NSArray <SMCallTraceTimeCostModel *> *subCosts;

- (NSString *)des;

@end


text:
Nemyslím si, že je Responzivní Web Design stále nutné představovat, když je to nyní snad všude. Každopádně se můžete ptát *proč je sekce o RWD v Sass manuálu?* Ve skutečnosti existuje pár věcí, které mohou být udělány tak, aby se s breakpointy pracovalo jednodušeji, takže myslím, že by nebyl špatný nápad je tady uvést.

### Naming breakpoints

Myslím si, že mohu bez problému říci, že media queries by neměla být vázána na specifické zařízení. Například pokoušet se mířit přímo na iPady nebo Blackberry telefony je určitě špatný nápad. Media queries by se měla starat o různé velikosti obrazovky, dokud se design nerozboří a nenastoupí další media query.

Ze stejného důvodu by breakpointy neměly být pojmenovány podle zařízení ale podle něčeho obecnějšího. Hlavně proto, že některé telefony jsou nyní větší než tablety, některé tablety větší než malé počítače atd.

{% include snippets/rwd/01/index.html %}

V tomto bodě naprosto stačí, pokud použijeme jakoukoli jmennou konvenci, která dává smysl a není spjata s konkrétními zařízeními.

{% include snippets/rwd/02/index.html %}

Předešlý příklad používá vnořené mapy pro definování breakpointů, každopádně opravdu záleží jen na vás, jaký druh správy použijete. Můžete se rozhodnout pro textové řetězce, spíše než-li pro vnitřní mapy, kvůli větší pružnosti (tedy '(min-width: 800px)').

**Další četba:**

* [Naming Media Queries](https://css-tricks.com/naming-media-queries/)

### Správce breakpointů

Jakmile pojmenujete své breakpointy tak, jak chcete, budete potřebovat najít způsob, jak je používat v media queries. Je mnoho způsobů jak tak učinit, ale musím říci, že nejvíce fandím breakpointové mapě, kterou čtu pomocí getter funkce. Tento způsob je zároveň jednoduchý a efektivní.

{% include snippets/rwd/03/index.html %}

Je zřejmé, že je to poměrně zjednodušující řešení pro správu breakpointů. Pokud potřebujete něco tolerantnějšího, doporučuji vám, abyste znovu nevynalézali kolo a použili něco co bylo ověřeno jako efektivní, právě jako Sass-MQ, Breakpoint nebo include-media.

**Další četba:**

* [Managing Responsive Breakpoints in Sass](https://www.sitepoint.com/managing-responsive-breakpoints-sass/)
* [Approaches to Media Queries in Sass](https://css-tricks.com/approaches-media-queries-sass/)

### Použití Media Queries

Ne tak dávno probíhala poměrně vzrušující debata o tom, kde by se měla media queries psát: patří do selektorů (jak to umožňuje Sass) nebo by se měly psát striktně mimo ně? Musím uznat, že jsem vášnivým zastáncem systému *media-queries-v-selektorech* a myslím si, že to funguje skvěle s ideou *komponent*.

{% include snippets/rwd/04/index.html %}

Což vede k následujícímu CSS výstupu:

{% include snippets/rwd/05/index.html %}

Mohli jste slyšet, že tato konvence vede k duplikování media queries v CSS výstupu. A je to rozhodně pravda. I když byl udělán test a finální verdikt je, že na tom nezáleží jakmile Gzip (nebo něco podobného) dokončí svou věc:

> … probírali jsme, zda existují problémy s výkonem v porovnání kombinování vs rozházení Media Queries a dospěli jsme k závěru, že v nejhorším případě sice ano, ale v nejlepším případě v podstatě vůbec ne.

> — [Sam Richards](https://twitter.com/snugug), ohledně [Breakpoint](http://breakpoint-sass.com/)

Pokud máte obavu ohledně duplicitních media queries, pořád můžete použít nástroj, který je spojí k sobě, jako například [tento gem](https://github.com/aaronjensen/sass-media_query_combiner), každopádně vás musím varovat, že pokud přesunete CSS někam jinam, může to mít negativní účinky. Nikdy nevíte, jestli je pořadí důležité.

**Další četba:**

* [Inline or Combined Media queries? Fight!](https://benfrain.com/inline-or-combined-media-queries-in-sass-fight/)
* [Sass::MediaQueryCombiner](https://github.com/aaronjensen/sass-media_query_combiner)


text:
layout: default
title: Welcome
---

		{% include navbar.html %}

		{% include image-hero.html %}

		{% include features.html %}

		{% include home-blockquote.html %}

		{% include services.html %}

		{% include work-gallery.html %}

		{% include pricing-tables.html %}

		{% include contact.html %}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Fail: (1104) The value type returned by a FunctionDefinition's lambda
    must be either boolean or numeric (L2V2 Section 3.5.6).
-->
<sbml xmlns="http://www.sbml.org/sbml/level2/version3" level="2" version="3">
  <model>
    <listOfFunctionDefinitions>
      <functionDefinition id="pow">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
        <semantics>
          <lambda>
            <bvar> <ci> x </ci> </bvar>
            <bvar> <ci> y </ci></bvar>
            <apply/>
          </lambda>
          </semantics>
        </math>
      </functionDefinition>
    </listOfFunctionDefinitions>
  </model>
</sbml>


text:
import {css} from 'glamor'

export const storyWrapper = css({
    overflow: 'hidden',
    maxHeight: '100%'
})

export const storyInterface = css({
    height: '100%',
    width: '100%',
    overflowY: 'scroll',
    border: 'solid 1px white',
    padding: '1rem',
    scrollBar: 'none',
    paddingRight: '70px'
})

const terminal = css.keyframes({
    'from': {width: '0em'},
    'to': {width: '40rem'}
})

export const staticNarration = css({
    fontSize: '1.4rem',
    animation: `${terminal} 4s steps(44) 1s 1 normal both`,
    whiteSpace: 'nowrap',
    overflowX: 'hidden'
})

export const dynamicStory = css({
    fontSize: '1.4rem'
})


text:
class UsbChooserContext : public ChooserContextBase,
                          public device::UsbService::Observer {
 public:
  explicit UsbChooserContext(Profile* profile);
  ~UsbChooserContext() override;

  // These methods from ChooserContextBase are overridden in order to expose
  // ephemeral devices through the public interface.
  std::vector<scoped_ptr<base::DictionaryValue>> GetGrantedObjects(
      const GURL& requesting_origin,
      const GURL& embedding_origin) override;
  std::vector<scoped_ptr<ChooserContextBase::Object>> GetAllGrantedObjects()
      override;
  void RevokeObjectPermission(const GURL& requesting_origin,
                              const GURL& embedding_origin,
                              const base::DictionaryValue& object) override;

  // Grants |requesting_origin| access to the USB device known to
  // device::UsbService as |guid|.
  void GrantDevicePermission(const GURL& requesting_origin,
                             const GURL& embedding_origin,
                             const std::string& guid);

  // Revokes |requesting_origin|'s access to the USB device known to
  // device::UsbService as |guid|.
  void RevokeDevicePermission(const GURL& requesting_origin,
                              const GURL& embedding_origin,
                              const std::string& guid);

  // Checks if |requesting_origin| (when embedded within |embedding_origin| has
  // access to the USB device known to device::UsbService as |guid|.
  bool HasDevicePermission(const GURL& requesting_origin,
                           const GURL& embedding_origin,
                           const std::string& guid);

 private:
  // ChooserContextBase implementation.
  bool IsValidObject(const base::DictionaryValue& object) override;

  // device::UsbService::Observer implementation.
  void OnDeviceRemoved(scoped_refptr<device::UsbDevice> device) override;

  bool is_off_the_record_;
  std::map<std::pair<GURL, GURL>, std::set<std::string>> ephemeral_devices_;
  device::UsbService* usb_service_;
  ScopedObserver<device::UsbService, device::UsbService::Observer> observer_;

  DISALLOW_COPY_AND_ASSIGN(UsbChooserContext);
};

#endif  // CHROME_BROWSER_USB_USB_CHOOSER_CONTEXT_H_


text:
Fragments are a powerful UI concept in Android. They represent a self-contained UI portion of an Activity's layout and logic.

Here's some stuff that you should read about them:
- [Fragments Design Philosophy, Fragments Lifecycle](http://developer.android.com/guide/components/fragments.html)
- [Dynamic UI with Fragments (see the three links below)](http://developer.android.com/training/basics/fragments/index.html)
- [Check out the sample (Eclipse project)](http://developer.android.com/shareables/training/FragmentBasics.zip)

Try to answer the following questions:
- Why were fragments introduced in Android 3.0/4.0?
- When should you use fragments?
- What is a `FragmentManager`? What is a `FragmentTransaction`?
- How would a `Fragment` communicate with it's host `Activity`?
- Should Fragment A **know** about Fragment B? If not, how would they communicate?

#### AsyncTasks
Easily manage both background and UI calculations:
- [AsyncTask reference](http://developer.android.com/reference/android/os/AsyncTask.html)
- [AsyncTask tutorial](http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html)
- [AsyncTask retain configuration change](http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html)

Try to answer the following questions:
- How would you implement AsyncTask yourself?
- What would you use AsyncTask for?
- How can an AsyncTask cause a leak?


text:
WorkerImp :: WorkerImp (EventProcessor &parent, WorkerList &putHereWhenDone) {

	// load up the initialization
	executionEngine.swap (parent);
	repository.swap (putHereWhenDone);

}

WorkerImp::ProcessWorkUnit(WorkToDoMessage &msg) {
	Timer clock;
	clock.Restart();

	// run the work unit
	msg.workUnit.Run ();

	// and put ourselves into the queue of idle workunits
	// evProc.repository.Add (msg.myName);

	// send back the result
	WorkDoneMessage_Factory (evProc.executionEngine, clock.GetTime(),
		msg.workUnit, msg.myName);
}


text:
package uk.joshiejack.horticulture.world;

import uk.joshiejack.horticulture.block.BlockSapling;
import uk.joshiejack.horticulture.block.HorticultureBlocks;
import uk.joshiejack.horticulture.HorticultureConfig;
import uk.joshiejack.horticulture.item.HorticultureItems;
import uk.joshiejack.horticulture.item.ItemCrop;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootEntryItem;
import net.minecraft.world.storage.loot.LootPool;
import net.minecraft.world.storage.loot.RandomValueRange;
import net.minecraft.world.storage.loot.conditions.LootCondition;
import net.minecraft.world.storage.loot.functions.LootFunction;
import net.minecraft.world.storage.loot.functions.SetCount;
import net.minecraft.world.storage.loot.functions.SetMetadata;
import net.minecraftforge.event.LootTableLoadEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

import static uk.joshiejack.horticulture.Horticulture.MODID;

@SuppressWarnings("ConstantConditions, unused")
@Mod.EventBusSubscriber(modid = MODID)
public class DungeonLoot {
    @SubscribeEvent
    public static void onDungeonLootLoad(LootTableLoadEvent event) {
        if (HorticultureConfig.enableDungeonChests) {
            if (event.getName().equals(new ResourceLocation("minecraft:chests/simple_dungeon")) ||
                    event.getName().equals(new ResourceLocation("minecraft:chests/village_blacksmith"))) {
                LootPool pool = event.getTable().getPool("main");
                pool.addEntry(getEntry("horticulture_strawberry", ItemCrop.Crops.STRAWBERRY, 2, 3));
                pool.addEntry(getEntry("horticulture_corn", ItemCrop.Crops.CORN, 1, 2));
                pool.addEntry(getEntry("horticulture_sweet_potato", ItemCrop.Crops.SWEET_POTATO, 2, 4));
                pool.addEntry(getEntry("horticulture_orange", BlockSapling.Sapling.ORANGE, 2));
                pool.addEntry(getEntry("horticulture_peach", BlockSapling.Sapling.PEACH, 3));
            }
        }
    }

    private static LootEntryItem getEntry(String name, BlockSapling.Sapling sapling, int max) {
        LootCondition[] conditions = new LootCondition[0];
        return new LootEntryItem(Item.getItemFromBlock(HorticultureBlocks.SAPLING), 6, 0,
                new LootFunction[]{ new SetMetadata(conditions, new RandomValueRange(sapling.ordinal())),
                        new SetCount(conditions, new RandomValueRange(1, max))}, conditions, name);
    }

    private static LootEntryItem getEntry(String name, ItemCrop.Crops crops, int min, int max) {
        LootCondition[] conditions = new LootCondition[0];
        return new LootEntryItem(HorticultureItems.SEEDS, 8, 0,
                new LootFunction[]{ new SetMetadata(conditions, new RandomValueRange(crops.ordinal())),
                new SetCount(conditions, new RandomValueRange(min, max))}, conditions, name);
    }
}


text:
<?php

namespace frontend\models\produccion;

use Yii;

/**
 * This is the model class for table "ProduccionesCiclos".
 *
 * @property integer $IdProduccionCiclos
 * @property integer $IdProduccionDetalle
 * @property integer $IdEstatus
 * @property string $Tipo
 * @property string $FechaCreacion
 * @property integer $Linea
 */
class ProduccionesCiclos extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'ProduccionesCiclos';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['IdProduccionDetalle'], 'required'],
            [['IdProduccionDetalle', 'IdEstatus', 'Linea'], 'integer'],
            [['Tipo'], 'string'],
            [['FechaCreacion'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'IdProduccionCiclos' => 'Id Produccion Ciclos',
            'IdProduccionDetalle' => 'Id Produccion Detalle',
            'IdEstatus' => 'Id Estatus',
            'Tipo' => 'Tipo',
            'FechaCreacion' => 'Fecha Creacion',
            'Linea' => 'Linea',
        ];
    }
}


text:
package org.fusesource.fabric.api;

/**
 * The Fabric Constants
 */
public interface Constants {

    String AGENT_PID = "org.fusesource.fabric.agent";
    String DATASTORE_TYPE_PID = "org.fusesource.fabric.datastore";
    String ZOOKEEPER_CLIENT_PID = "org.fusesource.fabric.zookeeper";
    String ZOOKEEPER_SERVER_PID = "org.fusesource.fabric.zookeeper.server";

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

In-VM pipe support which removes the overhead of local loopback communication.

What is 'in-VM pipe'?

    In-VM pipe is a direct event forwarding mechanism between two
	ProtocolHandlers in the
    same Java Virtual Machine.  Using in-VM pipe, you can remove the overhead
    of encoding and decoding which is caused uselessly by local loopback
    network communication.  Here are some useful situations possible:

SMTP server and SPAM filtering server,

web server and Servlet/JSP container.

    Please refer to
    Tennis
    example.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="En blogg för nära och kära.">

    <title>Om mig - Morgan i London</title>

    <link rel="canonical" href="http://morganstrom.github.io/about/">

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

    <link rel="stylesheet" href="/css/clean-blog.css">

    <link rel="stylesheet" href="/css/syntax.css">

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            Morgan i London

                    Hem

                    Om mig

                    Kontakt

Om mig

                    Personen bakom bloggen

Hello!

My name is Morgan and I'm a psychologist with a special interest in statistics and psychometrics. Please have a look at some stuff I've done in the links at the bottom!

I work at Cubiks, an international assessment and development consultancy. Being a part of the products team, my main focus is on ensuring high quality of our tests and solutions.

I've previously been working as a clinical psychologist at the Habilitation Centre, and with test development at Pearson Assessment. My experience in psychological assessment comes from both research and practice.

I grew up in the countryside near Linköping, and currently live in Birkastan, Stockholm. I graduated with a Master's degree from the Psychologist Programme with an orientation toward Sports at Umeå university in 2012.

My Master's thesis was a randomized controlled trial of an online intervention for depression. The paper is now published in a peer-reviewed scientific journal, available online for free. The data and analyses in R-code are also openly available on datadryad.org.

To get in touch, click any of the icons below or the button "Kontakt" on the top!

Copyright © Morgan i London 2015


text:
import * as React from 'react';
import { expect } from 'chai';
import { getClasses } from '@material-ui/core/test-utils';
import describeConformance from '@material-ui/core/test-utils/describeConformance';
import { createClientRender } from 'test/utils/createClientRender';
import createMount from 'test/utils/createMount';
import createServerRender from 'test/utils/createServerRender';
import Fab from './Fab';
import ButtonBase from '../ButtonBase';
import Icon from '../Icon';

describe('<Fab />', () => {
  const mount = createMount();
  const render = createClientRender({ strict: false });
  let classes;

  before(() => {
    classes = getClasses(<Fab>Fab</Fab>);
  });

  describeConformance(<Fab>Conformance?</Fab>, () => ({
    classes,
    inheritComponent: ButtonBase,
    mount,
    refInstanceof: window.HTMLButtonElement,
    skip: ['componentProp'],
  }));

  it('should render with the root class but no others', () => {
    const { getByRole } = render(<Fab>Fab</Fab>);
    const button = getByRole('button');

    expect(button).to.have.class(classes.root);
    expect(button).not.to.have.class(classes.primary);
    expect(button).not.to.have.class(classes.secondary);
    expect(button).not.to.have.class(classes.extended);
    expect(button).not.to.have.class(classes.focusVisible);
    expect(button).not.to.have.class(classes.disabled);
    expect(button).not.to.have.class(classes.colorInherit);
    expect(button).not.to.have.class(classes.mini);
    expect(button).not.to.have.class(classes.fullWidth);
    expect(button).not.to.have.class(classes.sizeSmall);
    expect(button).not.to.have.class(classes.sizeMedium);
  });

  it('should render an extended floating action button', () => {
    const { getByRole } = render(<Fab variant="extended">Fab</Fab>);
    const button = getByRole('button');

    expect(button).to.have.class(classes.root);
    expect(button).to.have.class(classes.extended);
  });

  it('should render a primary floating action button', () => {
    const { getByRole } = render(<Fab color="primary">Fab</Fab>);
    const button = getByRole('button');

    expect(button).to.have.class(classes.root);
    expect(button).to.have.class(classes.primary);
    expect(button).not.to.have.class(classes.secondary);
  });

  it('should render a secondary floating action button', () => {
    const { getByRole } = render(<Fab color="secondary">Fab</Fab>);
    const button = getByRole('button');

    expect(button).to.have.class(classes.root);
    expect(button).not.to.have.class(classes.primary);
    expect(button).to.have.class(classes.secondary);
  });

  it('should render a small floating action button', () => {
    const { getByRole } = render(<Fab size="small">Fab</Fab>);
    const button = getByRole('button');

    expect(button).to.have.class(classes.root);
    expect(button).to.have.class(classes.sizeSmall);
    expect(button).not.to.have.class(classes.sizeMedium);
  });

  it('should render a medium floating action button', () => {
    const { getByRole } = render(<Fab size="medium">Fab</Fab>);
    const button = getByRole('button');

    expect(button).to.have.class(classes.root);
    expect(button).not.to.have.class(classes.sizeSmall);
    expect(button).to.have.class(classes.sizeMedium);
  });

  it('should have a ripple by default', () => {
    const wrapper = mount(<Fab>Fab</Fab>);

    expect(wrapper.find(ButtonBase).props()).not.to.have.property('disableRipple');
  });

  it('should pass disableRipple to ButtonBase', () => {
    const wrapper = mount(<Fab disableRipple>Fab</Fab>);

    expect(wrapper.find(ButtonBase).props()).to.have.property('disableRipple', true);
  });

  it('should have a focusRipple by default', () => {
    const wrapper = mount(<Fab>Fab</Fab>);

    expect(wrapper.find(ButtonBase).props()).to.have.property('focusRipple', true);
  });

  it('should pass disableFocusRipple to ButtonBase', () => {
    const wrapper = mount(<Fab disableFocusRipple>Fab</Fab>);

    expect(wrapper.find(ButtonBase).props()).to.have.property('focusRipple', false);
  });

  it('should render Icon children with right classes', () => {
    const childClassName = 'child-woof';
    const iconChild = <Icon data-testid="icon" className={childClassName} />;
    const { getByTestId } = render(<Fab>{iconChild}</Fab>);
    const renderedIconChild = getByTestId('icon');

    expect(renderedIconChild).not.to.equal(null);
    expect(renderedIconChild).to.have.class(childClassName);
  });

  describe('server-side', () => {
    // Only run the test on node.
    if (!/jsdom/.test(window.navigator.userAgent)) {
      return;
    }
    const serverRender = createServerRender({ expectUseLayoutEffectWarning: true });

    it('should server-side render', () => {
      const markup = serverRender(<Fab>Fab</Fab>);
      expect(markup.text()).to.equal('Fab');
    });
  });
});


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

/*=============================================================================================
	AndroidPlatformMemory.h: Android platform memory functions
==============================================================================================*/

#pragma once
#include "GenericPlatform/GenericPlatformMemory.h"

/**
 *	Android implementation of the FGenericPlatformMemoryStats.
 */
struct FPlatformMemoryStats : public FGenericPlatformMemoryStats
{};

/**
* Android implementation of the memory OS functions
**/
struct CORE_API FAndroidPlatformMemory : public FGenericPlatformMemory
{
	// Begin FGenericPlatformMemory interface
	static void Init();
	static FPlatformMemoryStats GetStats();
	static const FPlatformMemoryConstants& GetConstants();
	static FMalloc* BaseAllocator();
	static void* BinnedAllocFromOS( SIZE_T Size );
	static void BinnedFreeToOS( void* Ptr );
	// End FGenericPlatformMemory interface
};

typedef FAndroidPlatformMemory FPlatformMemory;


text:
package org.dcsc.core.user.permission;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Set;

@Deprecated
@Repository
public interface RolePermissionRepository extends JpaRepository<RolePermission, RolePermissionId> {
    Set<RolePermission> findByRoleId(Long roleId);
}


text:
#ifndef __openma_base_logger_h
#define __openma_base_logger_h

#include "openma/base_export.h"
#include "openma/base/macros.h" // _OPENMA_NOEXCEPT

#include <utility> // std::forward

namespace ma
{
  template<typename... Args> static inline void info(const char* msg, Args&&... args) _OPENMA_NOEXCEPT;
  template<typename... Args> static inline void warning(const char* msg, Args&&... args) _OPENMA_NOEXCEPT;
  template<typename... Args> static inline void error(const char* msg, Args&&... args) _OPENMA_NOEXCEPT;

  enum class Message : char {Info = 0x01, Warning, Error};

  class OPENMA_BASE_EXPORT Logger
  {
  public:
    struct OPENMA_BASE_EXPORT Device
    {
      Device() _OPENMA_NOEXCEPT;
      virtual ~Device() _OPENMA_NOEXCEPT;

      virtual void write(Message category, const char* msg) _OPENMA_NOEXCEPT = 0;

      Device(const Device& ) = delete;
      Device(Device&& ) _OPENMA_NOEXCEPT = delete;
      Device& operator=(const Device& ) = delete;
      Device& operator=(Device&& ) _OPENMA_NOEXCEPT = delete;
    };

    static void mute(bool active) _OPENMA_NOEXCEPT;
    static Device* device() _OPENMA_NOEXCEPT;
    static void setDevice(Device* output) _OPENMA_NOEXCEPT;

    static Logger& instance();
    void prepareAndSendMessage(Message category, const char* msg, ...);
    void sendMessage(Message category, const char* msg);

    ~Logger() _OPENMA_NOEXCEPT;

    Logger(const Logger& ) = delete;
    Logger(Logger&& ) _OPENMA_NOEXCEPT = delete;
    Logger& operator=(const Logger& ) = delete;
    Logger& operator=(Logger&& ) _OPENMA_NOEXCEPT = delete;

  private:
    Logger();

    struct Private;
    Private* mp_Pimpl;
  };

  // ----------------------------------------------------------------------- //

  namespace __details
  {
    template<typename... Args>
    static inline void _send_message(Message category, const char* msg, Args&&... args)
    {
      Logger::instance().prepareAndSendMessage(category, msg, std::forward<Args>(args)...);
    };

    template<>
    inline void _send_message<>(Message category, const char* msg)
    {
      Logger::instance().sendMessage(category, msg);
    };
  };

  // ----------------------------------------------------------------------- //

  template<typename... Args> static inline void info(const char* msg, Args&&... args) _OPENMA_NOEXCEPT
  {
    __details::_send_message(Message::Info,msg,std::forward<Args>(args)...);
  };

  template<typename... Args> static inline void warning(const char* msg, Args&&... args) _OPENMA_NOEXCEPT
  {
    __details::_send_message(Message::Warning,msg,std::forward<Args>(args)...);
  };

  template<typename... Args> static inline void error(const char* msg, Args&&... args) _OPENMA_NOEXCEPT
  {
    __details::_send_message(Message::Error,msg,std::forward<Args>(args)...);
  };
};

#endif // __openma_base_logger_h


text:
<!DOCTYPE html>

	<title>XMLConverter</title>
	<meta name="keywords" content="testbox.build-testbox.testbox.system.util.concurrent.Callable interface">

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

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

<link href='https://fonts.googleapis.com/css?family=Ubuntu:400,300,300italic,400italic,700,700italic|Ubuntu+Mono' rel='stylesheet' type='text/css' />

	<link type="text/css" rel="stylesheet" href="../../../../../highlighter/styles/shCoreDefault.css">

			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#class-navigation">
				Toggle navigation

			</button>
			TestBox v2.3.0

 overview

  package

						 class

Class Definition

Constructor Summary

Constructor Detail

Inherited Methods

Method Summary

Method Detail

Property Summary

Property Detail

					 Frames

	testbox.build-testbox.testbox.system.util

Class

 XMLConverter

lucee.Component
    testbox.build-testbox.testbox.system.util.XMLConverter

A utility tool that can marshall data to XML

Class Attributes:

				output

				: false

				synchronized

				: false

				accessors

				: false

				persistent

				: false

				Constructor Summary

				init()

			Method Summary

			string

			arrayToXML(array data, [boolean useCDATA='false'], string rootName='')

			     Converts an array into XML with no headers.

			string

			objectToXML(any data, [boolean useCDATA='false'], string rootName='')

			     Converts an object(entity) into XML by inspecting its properties and then calling the appropriate getters on it.

			string

			queryToXML(query data, [string CDATAColumns=''], [string columnlist='[runtime expression]'], [boolean useCDATA='false'], string rootName='')

			     Converts a query to XML with no headers.

			private string

			safeText(string txt, [boolean useCDATA='false'])

			     Create a safe xml text.

			string

			structToXML(any data, [boolean useCDATA='false'], string rootName='')

			     Converts a struct into XML with no headers.

			string

			toXML(any data, [string columnlist], [boolean useCDATA='false'], [boolean addHeader='true'], string encoding='UTF-8', [string delimiter=','], string rootName='')

			     Convert any type of data to XML.

			private any

			translateValue(struct args, any targetValue)

			     Translate a value into XML.

			private string

			unicodeWin1252(string value)

			     Converts MS-Windows superset characters (Windows-1252) into their XML friendly unicode counterparts.

				Methods inherited from class lucee.Component

					None

				Constructor Detail

	init

	public init()

			Method Detail

arrayToXML

	public string arrayToXML(array data, [boolean useCDATA='false'], string rootName='')

Converts an array into XML with no headers.

Parameters:

data - The array to convert

useCDATA - Use CDATA content for ALL values. False by default

rootName - The name of the root element, else it defaults to the internal defaults.

objectToXML

	public string objectToXML(any data, [boolean useCDATA='false'], string rootName='')

Converts an object(entity) into XML by inspecting its properties and then calling the appropriate getters on it.

Parameters:

data - The structure, object, any to convert.

useCDATA - Use CDATA content for ALL values

rootName - The name of the root element, else it defaults to the internal defaults.

queryToXML

	public string queryToXML(query data, [string CDATAColumns=''], [string columnlist='[runtime expression]'], [boolean useCDATA='false'], string rootName='')

Converts a query to XML with no headers.

Parameters:

data - The query to convert

CDATAColumns - Which columns to wrap in cdata tags

columnlist - Choose which columns to include in the translation, by default it uses all the columns in the query

useCDATA - Use CDATA content for ALL values

rootName - The name of the root element, else it defaults to the internal defaults.

safeText

	private string safeText(string txt, [boolean useCDATA='false'])

Create a safe xml text

Parameters:

txt

useCDATA - Use CDATA content for ALL values

structToXML

	public string structToXML(any data, [boolean useCDATA='false'], string rootName='')

Converts a struct into XML with no headers.

Parameters:

data - The structure, object, any to convert.

useCDATA - Use CDATA content for ALL values

rootName - The name of the root element, else it defaults to the internal defaults.

toXML

	public string toXML(any data, [string columnlist], [boolean useCDATA='false'], [boolean addHeader='true'], string encoding='UTF-8', [string delimiter=','], string rootName='')

Convert any type of data to XML. This method will auto-discover the type. Valid types are array,query,struct

Parameters:

data - The data to convert to xml

columnlist - Choose which columns to inspect, by default it uses all the columns in the query, if using a query

useCDATA - Use CDATA content for ALL values. The default is false

addHeader - Add an xml header to the packet returned.

encoding - The character encoding of the header. UTF-8 is the default

delimiter - The delimiter in the list. Comma by default

rootName - The name of the root element, else it defaults to the internal defaults.

translateValue

	private any translateValue(struct args, any targetValue)

Translate a value into XML

Parameters:

args - The original argument collection

targetValue - The value to translate

unicodeWin1252

	private string unicodeWin1252(string value)

Converts MS-Windows superset characters (Windows-1252) into their XML friendly unicode counterparts

Parameters:

value


text:
title: In-Depth Guide to the Best Free Fonts
---

{% assign latest_typefaces = site.typefaces | sort: 'date_added' | reverse %}
{% assign latest_pairings = site.pairings | sort: 'date_added' | reverse %}

Guide to Only the Best
 Open-Source Typefaces

  {% for typeface in latest_typefaces limit:10 %}
    {% include sample.html %}
  {% endfor %}

Latest pairings

  {% for pairing in latest_pairings %}
    {% include pairing-sample.html %}
  {% endfor %}


text:
'use strict';

var SensorRetries = function (sensor, maxRetries, logger) {
    this._sensor = sensor;
    this._maxRetries = maxRetries;
    this._logger = logger;
};

SensorRetries.prototype.get = function (callback) {

    var that = this;

    this._sensor.getAll(function (err, values) {

        if (err) {
            that._logger.debug(err);
            return callback(err);
        }

        var result = {},
            retryList = [],
            retries = 0;

        Object.keys(values).forEach(function (key) {

            result[key] = { value: values[key] };

            if (values[key] === false) {
                retryList.push(key);
            }
        });

        if (retryList.length === 0) {
            return callback(null, result);
        }

        return that.retry(0, retryList, result, callback);
    });
};

SensorRetries.prototype.retry = function (retries, keys, result, callback) {

    var that = this;

    retries += 1;

    if (retries > this._maxRetries) {

        keys.forEach(function (key) {
            result[key].retries = retries;
        });

        return callback(null, result);
    }

    return this._sensor.get(keys, function (err, values) {

        if (err) return callback(err);

        var retryList = [];

        values.forEach(function (value, index) {

            var key = keys[index];

            if (value === false) {
                retryList.push(key);
            } else {
                result[key].value = value;
                result[key].retries = retries;
            }
        });

        if (retryList.length === 0) {
            return callback(null, result);
        }

        return that.retry(retries, retryList, result, callback);
    });
};

module.exports = SensorRetries;


text:
module ActionView
  module Helpers
    module Tags # :nodoc:
      class ColorField < TextField # :nodoc:
        def render
          options = @options.stringify_keys
          options["value"] ||= validate_color_string(value)
          @options = options
          super
        end

        private

          def validate_color_string(string)
            regex = /#[0-9a-fA-F]{6}/
            if regex.match?(string)
              string.downcase
            else
              "#000000"
            end
          end
      end
    end
  end
end


text:
require 'rails_helper'

RSpec.describe KeywordArticle, type: :model do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
.. _contributing:

Contributing
============

Encouraging more people to help develop pvlib-python is essential to our
success. Therefore, we want to make it easy and rewarding for you to
contribute.

Easy ways to contribute
-----------------------

Here are a few ideas for you can contribute, even if you are new to
pvlib-python, git, or Python:

* Make `GitHub issues <https://github.com/pvlib/pvlib-python/issues>`_
  and contribute to the conversation about how to resolve them.
* Read issues and pull requests that other people created and
  contribute to the conversation about how to resolve them.
* Improve the documentation and the unit tests.
* Improve the IPython/Jupyter Notebook tutorials or write new ones that
  demonstrate how to use pvlib-python in your area of expertise.
* If you have MATLAB experience, you can help us keep pvlib-python
  up to date with PVLIB_MATLAB or help us develop common unit tests.
  For more, see `Issue #2 <https://github.com/pvlib/pvlib-python/issues/2>`_
  and `Issue #3 <https://github.com/pvlib/pvlib-python/issues/3>`_.
* Tell your friends and colleagues about pvlib-python.
* Add your project to our
  `Projects and publications that use pvlib-python wiki
  <https://github.com/pvlib/pvlib-python/wiki/Projects-and-publications-
  that-use-pvlib-python>`_.

How to contribute new code
--------------------------

Contributors to pvlib-python use GitHub's pull requests to add/modify
its source code. The GitHub pull request process can be intimidating for
new users, but you'll find that it becomes straightforward once you use
it a few times. Please let us know if you get stuck at any point in the
process. Here's an outline of the process:

#. Create a GitHub issue and get initial feedback from users and
   maintainers. If the issue is a bug report, please include the
   code needed to reproduce the problem.
#. Obtain the latest version of pvlib-python: Fork the pvlib-python
   project to your GitHub account, ``git clone`` your fork to your computer.
#. Make some or all of your changes/additions and ``git commit`` them to
   your local repository.
#. Share your changes with us via a pull request: ``git push`` your
   local changes to your GitHub fork, then go to GitHub make a pull
   request.

The Pandas project maintains an excellent `contributing page
<https://github.com/pydata/pandas/wiki/Contributing>`_ that goes into
detail on each of these steps. Also see GitHub's `Set Up Git
<https://help.github.com/articles/set-up-git/>`_ and `Using Pull
Requests <https://help.github.com/articles/using-pull-requests/>`_.

Note that you do not need to make all of your changes before creating a
pull request. Your pull requests will automatically be updated when you
commit new changes and push them to GitHub. This gives everybody an easy
way to comment on the code and can make the process more efficient.

We strongly recommend using virtual environments for development.
Virtual environments make it trivial to switch between different
versions of software. This `astropy guide
<http://astropy.readthedocs.org/en/latest/development/workflow/
virtual_pythons.html>`_ is a good reference for virtual environments. If
this is your first pull request, don't worry about using a virtual
environment.

You must include documentation and unit tests for any new or improved
code. We can provide help and advice on this after you start the pull
request.

The maintainers will follow same procedures, rather than making direct
commits to the main repo. Exceptions may be made for extremely minor
changes, such as fixing documentation typos.

This documentation
------------------
If this documentation is unclear, help us improve it! Consider looking
at `IPython <https://github.com/ipython/ipython/wiki/Dev:-Index>`_,
`pandas <https://github.com/pydata/pandas/wiki>`_, and
`Sandia-Labs/PVLIB_Python#33 <https://github.com/Sandia-Labs/
PVLIB_Python/issues/33>`_ for inspiration.


text:
DefaultCamera::DefaultCamera()
    : viewMatrix(glm::mat4())
{
}

DefaultCamera::~DefaultCamera()
{
}

glm::mat4& DefaultCamera::getView()
{
    return viewMatrix;
}

void DefaultCamera::handleTerrainHeight(float f)
{
}

void DefaultCamera::cancelMovement()
{
}

glm::vec3 DefaultCamera::getPosition()
{
    return glm::vec3(0.0, 0.0, 0.0);
}

void DefaultCamera::updateCameraPosition(SDL_Event&)
{
}

void DefaultCamera::setPosition(glm::vec3)
{
}

void DefaultCamera::repositionCamera()
{
}

GLfloat DefaultCamera::getHeight()
{
    return 0.0f;
}

void DefaultCamera::prepareCamera()
{
}

void DefaultCamera::onGamepadAxis(int, float)
{
}

glm::vec3 DefaultCamera::getCameraDirection()
{
    return glm::vec3(0.0, 0.0, 0.0);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<testcase xmlns="http://xlt.xceptance.com/xlt-script/2" version="6">
  <tags>product,pdp,quickview,layout,variations</tags>
  <description>Verifies the structure/layout of quickview (QV) and product details pages (PDP) of variation products

# Setup
Open the site and remove cookies

#  Scope
Validate the displaying of product data either via quickview or via product detail page.

- validate structure of the QV
- go from QV to PDP
- validate stucture of PDP
- check if product name, price, and product number are the same on both
- search for product name and validate PDP again</description>
  <codecomment># Setup - Start Session</codecomment>
  <module name="modules.helper.FHelper_Session_flowToStartSession"/>
  <codecomment>Navigate to Womens/Clothing/Dresses</codecomment>
  <action name="CategoryLevel1"/>
  <module name="modules.global.headerfooternav.MGlobal_Nav_clickCategoryLevel1ByName">
    <parameter name="nameLevel1" value="${variationProductCategoryLevel1}"/>
  </module>
  <action name="CategoryLevel2"/>
  <module name="modules.global.headerfooternav.MGlobal_Nav_clickCategoryLevel2ByName">
    <parameter name="nameLevel2" value="${variationProductCategoryLevel2}"/>
  </module>
  <action name="CategoryLevel3"/>
  <module name="modules.global.headerfooternav.MGlobal_Nav_clickCategoryLevel3ByName">
    <parameter name="nameLevel3" value="${variationProductCategoryLevel3}"/>
  </module>
  <action name="SortByName"/>
  <codecomment>Sort products to ensure, that the needed product is on the catalog page</codecomment>
  <module name="modules.pages.catalog.MCatalog_Option_selectSortByByLabel">
    <parameter name="sortByLabel" value="Product Name A - Z"/>
  </module>
  <codecomment># Scope</codecomment>
  <codecomment>--------------------------------</codecomment>
  <codecomment>## Variation Product

- Validate Quickview for variation product
- Validate PDP for variation product
- Check if product name, price, and product number are the same</codecomment>
  <codecomment>--------------------------------</codecomment>
  <codecomment>Hover over Product and click on quick view buttom</codecomment>
  <action name="VariationProductQuickview"/>
  <module name="modules.pages.catalog.MCatalog_clickQuickViewByProductTitle">
    <parameter name="title" value="${variationProductName}"/>
  </module>
  <codecomment>Verify quick view page</codecomment>
  <codecomment>Caution: if you click on an product via QV usully a color is selected</codecomment>
  <module name="modules.pages.product.productquickview.VProductQV_validateHeader">
    <parameter name="prevButtonState" value=":not([disabled])"/>
    <parameter name="nextButtonState" value=":not([disabled])"/>
  </module>
  <module name="modules.pages.product.VProduct_validatePricePattern">
    <parameter name="pricePattern" value="${storefront_pricePattern}"/>
  </module>
  <module name="modules.pages.product.VProduct_validatePDPandQVShared">
    <comment>Currently PDP and QV share a lot, hence we validate that here</comment>
  </module>
  <module name="modules.pages.product.VProduct_validateProductVariations"/>
  <module name="modules.pages.product.VProduct_validateColorIsSelected"/>
  <module name="modules.pages.product.VProduct_validateSizeIsNotSelected"/>
  <module name="modules.pages.product.VProduct_validateAdd2CartButtonIsDisabled"/>
  <module name="modules.pages.product.productquickview.VProductQV_validateQVOnlyElements"/>
  <module name="modules.pages.product.VProduct_validateThumbnails"/>
  <module name="modules.pages.product.VProduct_validateSozialSharing"/>
  <codecomment>Store product informations to check them later</codecomment>
  <module name="modules.pages.product.MProduct_storeBasicData">
    <parameter name="productName_varName" value="productName"/>
    <parameter name="productNumber_varName" value="productNumber"/>
    <parameter name="productPriceSales_varName" value="productPrice"/>
  </module>
  <module name="modules.pages.product.MProduct_storeQuantity">
    <parameter name="productQuantity_varName" value="productQuantity"/>
  </module>
  <action name="ProductDetailPageFromQV"/>
  <codecomment>Goto PDP from QV</codecomment>
  <module name="modules.pages.product.productquickview.MProductQV_clickViewFullDetails">
    <parameter name="productName" value="${variationProductName}"/>
  </module>
  <codecomment>Verify product detail page</codecomment>
  <codecomment>Caution: on the pdp ususlly no color is selected if there are more than one color</codecomment>
  <module name="modules.global.headerfooternav.VNavigation_validateBreadcrumb">
    <parameter name="breadcrumbPath" value="*${variationProductCategoryLevel1} ${variationProductCategoryLevel2} ${variationProductCategoryLevel3} ${productName}"/>
  </module>
  <module name="modules.pages.product.VProduct_validatePricePattern">
    <parameter name="pricePattern" value="${storefront_pricePattern}"/>
  </module>
  <module name="modules.pages.product.VProduct_validatePDPandQVShared"/>
  <module name="modules.pages.product.VProduct_validateProductVariations"/>
  <module name="modules.pages.product.VProduct_validateColorIsNotSelected"/>
  <module name="modules.pages.product.VProduct_validateSizeIsNotSelected"/>
  <module name="modules.pages.product.VProduct_validateAdd2CartButtonIsDisabled"/>
  <module name="modules.pages.product.VProduct_validateSozialSharing"/>
  <module name="modules.pages.product.productdetailpage.VProductDetailPage_validatePDPOnlyElements"/>
  <module name="modules.pages.product.VProduct_validateThumbnails"/>
  <module name="modules.pages.product.productdetailpage.VProductDetailPage_validateRecommendations"/>
  <codecomment>Check are the stored values form QV the same on PDP</codecomment>
  <module name="modules.pages.product.VProduct_validateBasicData">
    <parameter name="productName" value="${productName}"/>
    <parameter name="productNumber" value="${productNumber}"/>
    <parameter name="productPrice" value="${productPrice}"/>
  </module>
  <module name="modules.pages.product.VProduct_validatesQuantity">
    <parameter name="productQuantity" value="${productQuantity}"/>
  </module>
  <codecomment>Go back to Homepage</codecomment>
  <action name="BackToHomepage"/>
  <module name="modules.global.headerfooternav.MGlobal_Header_clickGoToHomepageViaLogo"/>
  <action name="SearchProductByName"/>
  <codecomment>Search product by name, ensure that the PDP found by search is identical to the PDP by navigation from QV.</codecomment>
  <codecomment>Caution: even if there is only one color if you search for the variation master there will be no color selected</codecomment>
  <module name="modules.pages.search.MSearch_enterTextAndSubmit">
    <parameter name="searchText" value="${productName}"/>
  </module>
  <module name="modules.global.headerfooternav.VNavigation_validateBreadcrumb">
    <parameter name="breadcrumbPath" value="*${variationProductCategoryLevel1} ${variationProductCategoryLevel2} ${variationProductCategoryLevel3} ${productName}"/>
  </module>
  <module name="modules.pages.product.VProduct_validatePricePattern">
    <parameter name="pricePattern" value="${storefront_pricePattern}"/>
  </module>
  <module name="modules.pages.product.VProduct_validatePDPandQVShared"/>
  <module name="modules.pages.product.VProduct_validateProductVariations"/>
  <module name="modules.pages.product.VProduct_validateColorIsNotSelected"/>
  <module name="modules.pages.product.VProduct_validateSizeIsNotSelected"/>
  <module name="modules.pages.product.VProduct_validateAdd2CartButtonIsDisabled"/>
  <module name="modules.pages.product.VProduct_validateSozialSharing"/>
  <module name="modules.pages.product.productdetailpage.VProductDetailPage_validatePDPOnlyElements"/>
  <module name="modules.pages.product.VProduct_validateThumbnails"/>
  <module name="modules.pages.product.productdetailpage.VProductDetailPage_validateRecommendations"/>
  <codecomment>Validate the stored values form QV on the PDP</codecomment>
  <module name="modules.pages.product.VProduct_validateBasicData">
    <parameter name="productName" value="${productName}"/>
    <parameter name="productNumber" value="${productNumber}"/>
    <parameter name="productPrice" value="${productPrice}"/>
  </module>
  <module name="modules.pages.product.VProduct_validatesQuantity">
    <parameter name="productQuantity" value="${productQuantity}"/>
  </module>
</testcase>


text:
"""Increase note max size

Revision ID: 1c847ae1209a
Revises: bbd695323107
Create Date: 2016-07-29 11:18:00.550197

"""

# revision identifiers, used by Alembic.
revision = '1c847ae1209a'
down_revision = '2ce75615b24d'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('itemaudit', 'notes', type_=sa.VARCHAR(1024), existing_type=sa.VARCHAR(length=512), nullable=True)
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('itemaudit', 'notes', type_=sa.VARCHAR(512), existing_type=sa.VARCHAR(length=1024), nullable=True)
    ### end Alembic commands ###