text:
package io.netty.resolver.dns;

import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.UnstableApi;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;

import static io.netty.resolver.dns.DnsServerAddresses.sequential;

/**
 * A {@link DnsServerAddressStreamProvider} which will use predefined default DNS servers to use for DNS resolution.
 * These defaults do not respect your host's machines defaults.
 *

 * This may use the JDK's blocking DNS resolution to bootstrap the default DNS server addresses.
 */
@UnstableApi
public final class DefaultDnsServerAddressStreamProvider implements DnsServerAddressStreamProvider {
    private static final InternalLogger logger =
            InternalLoggerFactory.getInstance(DefaultDnsServerAddressStreamProvider.class);
    public static final DefaultDnsServerAddressStreamProvider INSTANCE = new DefaultDnsServerAddressStreamProvider();

    private static final List<InetSocketAddress> DEFAULT_NAME_SERVER_LIST;
    private static final InetSocketAddress[] DEFAULT_NAME_SERVER_ARRAY;
    private static final DnsServerAddresses DEFAULT_NAME_SERVERS;
    static final int DNS_PORT = 53;

    static {
        final List<InetSocketAddress> defaultNameServers = new ArrayList<InetSocketAddress>(2);

        // Using jndi-dns to obtain the default name servers.
        //
        // See:
        // - http://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-dns.html
        // - http://mail.openjdk.java.net/pipermail/net-dev/2017-March/010695.html
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        env.put("java.naming.provider.url", "dns://");
        try {
            DirContext ctx = new InitialDirContext(env);
            String dnsUrls = (String) ctx.getEnvironment().get("java.naming.provider.url");
            String[] servers = dnsUrls.split(" ");
            for (String server : servers) {
                try {
                    defaultNameServers.add(SocketUtils.socketAddress(new URI(server).getHost(), DNS_PORT));
                } catch (URISyntaxException e) {
                    logger.debug("Skipping a malformed nameserver URI: {}", server, e);
                }
            }
        } catch (NamingException ignore) {
            // Will try reflection if this fails.
        }

        if (defaultNameServers.isEmpty()) {
            try {
                Class<?> configClass = Class.forName("sun.net.dns.ResolverConfiguration");
                Method open = configClass.getMethod("open");
                Method nameservers = configClass.getMethod("nameservers");
                Object instance = open.invoke(null);

                @SuppressWarnings("unchecked")
                final List<String> list = (List<String>) nameservers.invoke(instance);
                for (String a: list) {
                    if (a != null) {
                        defaultNameServers.add(new InetSocketAddress(SocketUtils.addressByName(a), DNS_PORT));
                    }
                }
            } catch (Exception ignore) {
                // Failed to get the system name server list via reflection.
                // Will add the default name servers afterwards.
            }
        }

        if (!defaultNameServers.isEmpty()) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Default DNS servers: {} (sun.net.dns.ResolverConfiguration)", defaultNameServers);
            }
        } else {
            Collections.addAll(
                    defaultNameServers,
                    SocketUtils.socketAddress("8.8.8.8", DNS_PORT),
                    SocketUtils.socketAddress("8.8.4.4", DNS_PORT));

            if (logger.isWarnEnabled()) {
                logger.warn(
                        "Default DNS servers: {} (Google Public DNS as a fallback)", defaultNameServers);
            }
        }

        DEFAULT_NAME_SERVER_LIST = Collections.unmodifiableList(defaultNameServers);
        DEFAULT_NAME_SERVER_ARRAY = defaultNameServers.toArray(new InetSocketAddress[defaultNameServers.size()]);
        DEFAULT_NAME_SERVERS = sequential(DEFAULT_NAME_SERVER_ARRAY);
    }

    private DefaultDnsServerAddressStreamProvider() {
    }

    @Override
    public DnsServerAddressStream nameServerAddressStream(String hostname) {
        return DEFAULT_NAME_SERVERS.stream();
    }

    /**
     * Returns the list of the system DNS server addresses. If it failed to retrieve the list of the system DNS server
     * addresses from the environment, it will return {@code "8.8.8.8"} and {@code "8.8.4.4"}, the addresses of the
     * Google public DNS servers.
     */
    public static List<InetSocketAddress> defaultAddressList() {
        return DEFAULT_NAME_SERVER_LIST;
    }

    /**
     * Returns the {@link DnsServerAddresses} that yields the system DNS server addresses sequentially. If it failed to
     * retrieve the list of the system DNS server addresses from the environment, it will use {@code "8.8.8.8"} and
     * {@code "8.8.4.4"}, the addresses of the Google public DNS servers.
     *

     * This method has the same effect with the following code:
     *

     * DnsServerAddresses.sequential(DnsServerAddresses.defaultAddressList());
     *

     *

     */
    public static DnsServerAddresses defaultAddresses() {
        return DEFAULT_NAME_SERVERS;
    }

    /**
     * Get the array form of {@link #defaultAddressList()}.
     * @return The array form of {@link #defaultAddressList()}.
     */
    static InetSocketAddress[] defaultAddressArray() {
        return DEFAULT_NAME_SERVER_ARRAY.clone();
    }
}


text:
require 'rails_helper'

RSpec.describe Item, type: :model do
  it { should validate_presence_of(:name) }
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<meta name='description' content='This is the next post in a series re-discovering Serilog v2.
In the introduction to the Serilog Console Sink I mentioned about how you can use a number of ways to configure Serilog. Below is a simple guide on which approach you may like to take when setting up your configuration.
 mermaid.initialize({startOnLoad:true}); graph TD C(Serilog Configuration) --| | Y{What do I want? } Y --| Code | D(Fluent Interface) Y --| A File | Z{What file type?'>

<meta property='og:title' content='Exploring Serilog v2 - Configuration • Get Amongst It!'>
<meta property='og:description' content='This is the next post in a series re-discovering Serilog v2.
In the introduction to the Serilog Console Sink I mentioned about how you can use a number of ways to configure Serilog. Below is a simple guide on which approach you may like to take when setting up your configuration.
 mermaid.initialize({startOnLoad:true}); graph TD C(Serilog Configuration) --| | Y{What do I want? } Y --| Code | D(Fluent Interface) Y --| A File | Z{What file type?'>
<meta property='og:url' content='https://merbla.com/2018/04/05/exploring-serilog-v2---configuration/'>
<meta property='og:site_name' content='Get Amongst It!'>
<meta property='og:type' content='article'><meta property='article:section' content='Posts'><meta property='article:tag' content='serilog'><meta property='article:published_time' content='2018-04-05T00:00:00+10:00'/><meta property='article:modified_time' content='2018-04-05T00:00:00+10:00'/><meta name='twitter:card' content='summary'><meta name='twitter:site' content='@matthewerbs'>

<meta name="generator" content="Hugo 0.36" />

  <title>Exploring Serilog v2 - Configuration • Get Amongst It!</title>
  <link rel='canonical' href='https://merbla.com/2018/04/05/exploring-serilog-v2---configuration/'>

  <link rel='icon' href='/favicon.ico'>
<link rel='stylesheet' href='/assets/css/main.9efb8af6.css'><link rel='stylesheet' href='/assets/css/custom.css'>

    Skip to Main Menu

    Get Amongst It!

    Matthew's Musings

          Open Github account in new tab<svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"/>

</svg>

          Open Twitter account in new tab<svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <path d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z"/>

</svg>

          Open Instagram account in new tab<svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <rect x="2" y="2" width="20" height="20" rx="5" ry="5"/>
  <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/>
  <line x1="17.5" y1="6.5" x2="17.5" y2="6.5"/>

</svg>

          Open Linkedin account in new tab<svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"/>
  <rect x="2" y="9" width="4" height="12"/>
  <circle cx="4" cy="4" r="2"/>

</svg>

Tags

        .net

        Octopus Deploy

        R

        Splunk

        Activedirectory

        Ad

        Afl

        Azure

        Beginner

        Bouldering

        Cli

        Climbing

        Devops

        Fitzroy

        Github

        Oss

        Powershell

        Serilog

        Splunk

        Stats

        Webapp

    Skip to Content

<button id='sidebar-toggler' class='hamburger hamburger--arrow sidebar-toggler' type='button' aria-controls='sidebar' aria-expanded='false'>
  Toggle Sidebar

</button>

        Posts

        Speaking

        Projects

        About

Exploring Serilog v2 - Configuration

  <svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
  <line x1="16" y1="2" x2="16" y2="6"/>
  <line x1="8" y1="2" x2="8" y2="6"/>
  <line x1="3" y1="10" x2="21" y2="10"/>

</svg>
Posted on
  <time class='entry-date' datetime='2018-04-05T00:00:00+10:00'>2018, Apr 05</time>

<svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <circle cx="12" cy="12" r="10"/>
  <polyline points="12 6 12 12 15 15"/>

</svg>
4 mins read

This is the next post in a series re-discovering Serilog v2.

In the introduction to the Serilog Console Sink I mentioned about how you can use a number of ways to configure Serilog.  Below is a simple guide on which approach you may like to take when setting up your configuration.

graph TD

C(Serilog Configuration) -->|   | Y{What do I want? }
Y -->| Code | D(Fluent Interface)
Y -->| A File | Z{What file type? }
Z -->| | E(JSON)
Z -->| | F(XML)
E -->| | H(Serilog.Settings.Configuration)
F -->| | J(Serilog.Settings.AppSettings)

The diagram is a little simple… so you may want to consider what other features are available.  To take a closer look, checkout the following GitHub repositories.

Serilog.Settings.Configuration

This is the package to use if you are considering a JSON approach to configuration, for example in ASP.NET Core.  Under the hood this package currently uses the Microsoft.Extensions.DependencyModel & Microsoft.Extensions.Configuration.Abstractions packages.  The library works by infering the configuraion of key method overloads to setup Serilog.  This includes:

Minimum Level of events to be logged

Enrichment of events

Filtering of events

Sink configuration

Audit Sinks

A Quick Example

Let’s create a quick console app, that logs to both the console and a file sinks whilst using a appsetting.json file for configuration.

dotnet new console -n example-console

cd example-console

dotnet add package Serilog.Settings.Configuration

dotnet add package Microsoft.Extensions.Configuration.Json

dotnet add package Serilog.Sinks.Console

dotnet add package Serilog.Sinks.File

dotnet add package Serilog.Enrichers.Process

touch appsettings.json

Open the Program.cs and add the following.

using System;
using System.IO;
using Serilog;
using Serilog.Events;
using Serilog.Core;
using Microsoft.Extensions.Configuration;

namespace example_console
{
    class Program
    {
        static void Main(string[] args)
        {
            // Read the appsettings file
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            // Apply the config to the logger
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();

            Log.Verbose("This is a verbose statement");
            Log.Debug("This is a debug statement");
            Log.Information("This is a info statement");
            Log.Warning("This is a warning statement");
            Log.Error(new IndexOutOfRangeException(), "This is an error statement");
            Log.Fatal(new AggregateException(), "This is an fatal statement");
        }
    }
}

Then open appsettings.json and add the following setup.

{
    "Serilog": {
      "Using": ["Serilog.Sinks.Console"],
      "MinimumLevel": "Information",
      "Enrich": ["WithProcessId"],
      "WriteTo": [
        { "Name": "File", "Args": { "path": "serilog-configuration-sample.txt" } },
        {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp} [{Level}] {Message} {Exception} {Properties} {NewLine}",
          "theme": "Serilog.Sinks.SystemConsole.Themes.SystemConsoleTheme::Literate, Serilog.Sinks.Console"
        }
      }],
      "Properties": {
        "Application": "Exploring Serilog v2"
      }
    }
  }

A couple of gotchas to remember.

Make sure your using/namespace declarations are correct, Sinks will not be discovered if there is a typo. e.g. "Using": ["Serilog.Sinks.Console", "Not A Sink Namespace"]

Ensure the args you pass to sinks are exposed via the fluent configuration.  I have been bitten by slight inconsistencies in how Sinks are configured.  If you are interested how some of the internals work, check out ConfigurationReader.

Links

GitHub

NuGet

Serilog.Settings.AppSettings

If you are looking for a more traditional XML based approach, then check out Serilog.Settings.AppSettings.  This library is the best option when using an <appsettings> block and uses a similar approach to the Serilog.Settings.Configuration package.

A Quick Example

Once again, let’s create a quick console app. Following the previous example this will also log to both the console and a file sinks however this time a example.config file will be targeted.

dotnet new console -n example-console

cd example-console

dotnet add package System.Configuration.ConfigurationManager

dotnet add package Serilog.Settings.AppSettings

dotnet add package Serilog.Sinks.Console

dotnet add package Serilog.Sinks.File

dotnet add package Serilog.Enrichers.Process

touch appsettings.config

Open the Program.cs and add the same following code.

using System;
using System.IO;
using Serilog;
using Serilog.Events;
using Serilog.Core;

namespace example_console
{
    class Program
    {
        static void Main(string[] args)
        {
            var basePath = AppDomain.CurrentDomain.BaseDirectory;
            var configFile = Path.GetFullPath(Path.Combine(basePath, "appsettings.config"));

            // Apply the config to the logger
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.AppSettings(filePath: configFile)
                .CreateLogger();

            Log.Verbose("This is a verbose statement");
            Log.Debug("This is a debug statement");
            Log.Information("This is a info statement");
            Log.Warning("This is a warning statement");
            Log.Error(new IndexOutOfRangeException(), "This is an error statement");
            Log.Fatal(new AggregateException(), "This is an fatal statement");
        }
    }
}

Then open .csproj and add the following to ensure the config file is copied.

  <ItemGroup>
    <None Update="appsettings.config">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>

Finally open appsettings.config and add the following setup.  Here we setup the console and file sinks along with a process enricher.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="serilog:using:Console" value="Serilog.Sinks.Console" />
    <add key="serilog:write-to:Console"/>
    <add key="serilog:write-to:Console.outputTemplate" value="[{Timestamp} [{Level}] {Message} {Exception} {Properties} {NewLine}" />
    <add key="serilog:using:File" value="Serilog.Sinks.File" />
    <add key="serilog:write-to:File"/>
    <add key="serilog:write-to:File.path" value="serilog-configuration-sample.txt" />
    <add key="serilog:using:Process" value="Serilog.Enrichers.Process" />
    <add key="serilog:enrich:WithProcessId"/>
  </appSettings>
</configuration>

Links

GitHub

NuGet

The is another new kid on the block I did forget to mention.  It is early days, however using the lessons of logs past, this library attempts to unify the configuration of Serilog and onboard users more seemlessly.

Serilog.Settings.Combined

Links

GitHub

NuGet

Get Amongst It!!

  <svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <path d="M22,19a2,2,0,0,1-2,2H4a2,2,0,0,1-2-2V5A2,2,0,0,1,4,3H9l2,3h9a2,2,0,0,1,2,2Z"/>

</svg>

  Categories: Exploring-serilog-v2

  <svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <path d="M20.59,13.41l-7.17,7.17a2,2,0,0,1-2.83,0L2,12V2H12l8.59,8.59A2,2,0,0,1,20.59,13.41Z"/>
  <line x1="7" y1="7" x2="7" y2="7"/>

</svg>

  Tags: Serilog

        <svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <line x1="20" y1="12" x2="4" y2="12"/>
  <polyline points="10 18 4 12 10 6"/>

</svg>
 Previous
        Previous post: Exploring Serilog v2 - The Console Sink

        Next post: Exploring Serilog v2 - ASP.Net CoreNext <svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <line x1="4" y1="12" x2="20" y2="12"/>
  <polyline points="14 6 20 12 14 18"/>

</svg>

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

          Open Github account in new tab<svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"/>

</svg>

          Open Twitter account in new tab<svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <path d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z"/>

</svg>

          Open Instagram account in new tab<svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <rect x="2" y="2" width="20" height="20" rx="5" ry="5"/>
  <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/>
  <line x1="17.5" y1="6.5" x2="17.5" y2="6.5"/>

</svg>

          Open Linkedin account in new tab<svg class='icon' viewbox='0 0 24 24' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' aria-hidden='true'>

  <path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"/>
  <rect x="2" y="9" width="4" height="12"/>
  <circle cx="4" cy="4" r="2"/>

</svg>

 © 2018 Matthew Erbs


text:
BomberLua is a botgame, inspired from Robocode. You don't control the character like in any other bomberman clone; instead, you write a script which will use the information provided by the game on the playing board to move the character and attack the others (which are controlled by other scripts).

Bomberman was chosen because of the particularity of the gaming board (which is not empty as Robocode's was): bombermen need to find their path on the board and to make a way to its enemies. Dodging bombs is not always easy, because you need to find a safe place to go everytime you or an enemy drops a bomb.

The game is written in C++, using SDL, SDL_image and Lua 5.1, by remram44, Insomniak (display and graphics) and acieroid (Python interface, still WIP).

# Rules

For the moment, the playing board is fixed (11x11): grid of ROCK blocks completed by BRICK blocks, except in the 4 corners, where the bombermen begin.

Only the BRICK blocks are destroyable. Bombs have a fixed range of 1 block in each direction.

The scripts are executed in parallel in separated threads. They are loaded before the beginning of the game and the placing of bombermen; however they already have access to the gaming board. A script may use this preliminary phase of 5 seconds to calculate some informations, for instance concerning pathfinding (even if the current board size does not justify it). The ready() function must be called before the 5 seconds are spent, or the bot will not be allowed to play. The ready() function returns at the beginning of the game, when all functions are available.

The functions that allow a script to act are blocking, which means they only return when the action is finished and when the bomberman can act again. The duration of the action is:

* 0.5 seconds for a movement (move() function);
* 0.1 seconds to drop a bomb (bomb() function);

# Scripts

For the moment, only the Lua and Python scripting language are supported (with a limitation for Python; cf bug 1). The support of other languages is not planned but may be added easily (please contact me if you can add support for a new language).

During the game, bots have access to the following function:

* get_self : this function returns informations on the bomberman which is controlled by the bot. It returns a table containing two fields: posx and posy, the position of the character on the board.
* get_bombers : returns a table of all bombermen. Each bomberman is represented by a number (which identifies the bomberman for the whole game); the structure associated is the same as get_self returns.
* get_field : returns the board, in form of a table. The fields w and h indicates the size of the board, and to each string "x,y" is associated the type of the cell, which may be:
** "rock": an undestroyable wall
** "brick": a wall that may be destroyed by a bomb
** un nombre : no wall, but a bomb that will explode in that amount of time (in seconds)
** "explosion" : an explosion
** "empty" : nothing
* move : allows the character to move. You may pass "left", "right", "up" or "down" to move in the desired direction.
* bomb : drops a bomb.

# Planned

Planned features for future versions:

* Several boards, of different sizes (loading from a file and random generation);
* Bonuses, appearing randomly when a BRICK block is destroyed:
** Range: each bonus improves the range of the bombs by 1 block;
** Speed: improves the walking speed of the character.
* Saving and playing back replays.

# Downloading and installing

As many of my projects, BomberLua is hosted on Github; you will find the latest version of the sources there, along with packages for so-called 'stable' versions of the program.

# Usage

A graphical "launcher" written with Qt allows you to launch the game without using the commandline. Otherwise, you can use the following parameters:

* -i to enable graphical display
* 1 to 4 scripts to load

Examples :

    ./bomberlua -i bots/test.lua bots/scripted.lua bots/test.lua # Linux
    bomberlua.exe -i bots\test.lua bots\scripted.lua bots\test.lua # Windows


text:
<?php
global $Amaintable,$AdispArray,$typename,$AcreateItemId,$item,$AnoEntries,$Athistableid,$Afootertext;
if (empty ($Amaintable['n'])) return;

include_once 'gtdfuncs.inc.php';

$sep=$onready='';
/*  we are in itemreport, and this item (potentially) has some child types,
    so loop over each type, and add a "create item" row to each table
*/
foreach ($Amaintable['n'] as $key=>$maintable) {
    $i=count($maintable);
    $isempty=($i===0);

    // create an extra row, hidden, and use that as a template for new items.
    $maintable[$i]=array('doreport'=>true,'row.class'=>'sortbottom hidden creatortemplate');
    foreach ($AdispArray['n'][$key] as $field=>$dummy)
        $maintable[$i][$field]='';
    $maintable[$i]['itemId']='0';
    $maintable[$i]['title']="title";

    // now create the next row, for the bit that triggers the item creation
    $i++;
    $maintable[$i]=array('categoryId'=>$item['categoryId'],'doreport'=>'');
    foreach ($AdispArray['n'][$key] as $field=>$dummy)
        $maintable[$i][$field]='';
    $maintable[$i]['itemId']=$AcreateItemId['n'][$key];
    $maintable[$i]['title']="Add new {$typename[$key]}";
    $maintable[$i]['row.class']='sortbottom creator';
    $maintable[$i]['NA']=null;

    // remove the existing creation row in the table footer
    $footertext=$Afootertext['n'][$key];
    foreach ($footertext as $ndx=>$foot) {
        if (strstr($foot,'Add new')!==false) array_splice($footertext,$ndx);
    }
    $Afootertext['n'][$key]=$footertext;

    // store our changes in the array of tables that are to be output
    $Amaintable['n'][$key]=$maintable;

    if (!$isempty) continue; // cycle onto next iteration if there are children of this type

    // now do something fancy with tables that would have been empty, but for our meddling
    $link=$AnoEntries['n'][$key];
    $tableid=$Athistableid['n'][$key];
    $onready .= $sep.$tableid.':"'
                .escapeforjavascript($link)
                .'"'."\n";
    $sep=',';
}
?>
<script type='text/javascript'>
/* <![CDATA[ */
$(document).ready(function(){
    GTD.ajax.setNoChildren({
    <?php echo $onready; ?>
    });
});
/* ]]> */
</script>


text:
from kraken.core.maths import Vec3
from kraken.core.maths.xfo import Xfo
from kraken.core.maths.constants import *

from kraken.core.objects.components.base_example_component import BaseExampleComponent

from kraken.core.objects.attributes.attribute_group import AttributeGroup
from kraken.core.objects.attributes.scalar_attribute import ScalarAttribute
from kraken.core.objects.attributes.bool_attribute import BoolAttribute
from kraken.core.objects.attributes.string_attribute import StringAttribute

from kraken.core.objects.constraints.pose_constraint import PoseConstraint

from kraken.core.objects.component_group import ComponentGroup
from kraken.core.objects.hierarchy_group import HierarchyGroup
from kraken.core.objects.locator import Locator
from kraken.core.objects.joint import Joint
from kraken.core.objects.space import Space
from kraken.core.objects.control import Control

from kraken.core.objects.operators.kl_operator import KLOperator

from kraken.core.profiler import Profiler
from kraken.helpers.utility_methods import logHierarchy

from OSS.OSS_control import *
from OSS.OSS_component import OSS_Component

COMPONENT_NAME = "teeth"

class OSSTeeth(OSS_Component):
    """Teeth Component Base"""

    def __init__(self, name='teeth', parent=None):
        super(OSSTeeth, self).__init__(name, parent)

        # ===========
        # Declare IO
        # ===========
        # Declare Inputs Xfos

        # Declare Output Xfos
        self.teethOutputTgt = self.createOutput('teeth', dataType='Xfo', parent=self.outputHrcGrp).getTarget()

        # Declare Input Attrs

class OSSTeethGuide(OSSTeeth):
    """Teeth Component Guide"""

    def __init__(self, name='teeth', parent=None):

        Profiler.getInstance().push("Construct Teeth Guide Component:" + name)
        super(OSSTeethGuide, self).__init__(name, parent)

        # =========
        # Controls
        # =========
        # Guide Controls
        self.teethCtrl = Control('teeth', parent=self.ctrlCmpGrp, shape="null")
        self.teethCtrl.setColor("pink")

        data = {
                "name": name,
                "location": "M",
                "teethXfo": Xfo(Vec3(0.0, 0.0, 0.0)),
                'teethCtrlCrvData': self.teethCtrl.getCurveData()
               }

        self.loadData(data)

        Profiler.getInstance().pop()

    # =============
    # Data Methods
    # =============
    def saveData(self):
        """Save the data for the component to be persisted.

        Return:
        The JSON data object

        """

        data = super(OSSTeethGuide, self).saveData()

        data['teethXfo'] = self.teethCtrl.xfo
        #data['teethCtrlCrvData'] = self.teethCtrl.getCurveData()

        return data

    def loadData(self, data):
        """Load a saved guide representation from persisted data.

        Arguments:
        data -- object, The JSON data object.

        Return:
        True if successful.

        """

        super(OSSTeethGuide, self).loadData( data )

        self.teethCtrl.xfo = data['teethXfo']
        #self.teethCtrl.setCurveData(data['teethCtrlCrvData'])

        globalScale = self.globalComponentCtrlSizeInputAttr.getValue()
        globalScaleVec =Vec3(globalScale, globalScale, globalScale)

        self.teethCtrl.scalePoints(globalScaleVec)
        return True

    def getRigBuildData(self):
        """Returns the Guide data used by the Rig Component to define the layout of the final rig..

        Return:
        The JSON rig data object.

        """

        data = super(OSSTeethGuide, self).getRigBuildData()

        data['teethXfo'] = self.teethCtrl.xfo
        data['teethCtrlCrvData'] = self.teethCtrl.getCurveData()

        return data

    # ==============
    # Class Methods
    # ==============
    @classmethod
    def getComponentType(cls):
        """Enables introspection of the class prior to construction to determine if it is a guide component.

        Return:
        The true if this component is a guide component.

        """

        return 'Guide'

    @classmethod
    def getRigComponentClass(cls):
        """Returns the corresponding rig component class for this guide component class

        Return:
        The rig component class.

        """

        return OSSTeethRig

class OSSTeethRig(OSSTeeth):
    """Teeth Component"""

    def __init__(self, name='Teeth', parent=None):

        Profiler.getInstance().push("Construct Teeth Rig Component:" + name)
        super(OSSTeethRig, self).__init__(name, parent)

    def createControls(self, data):

        # =========
        # Controls
        # =========
        # Teeth

        self.teethCtrl = Control(self.getName(), parent=self.ctrlCmpGrp, shape="circle")
        self.teethSpace = self.teethCtrl.insertSpace()
        self.teethSpace.xfo = data['teethXfo']
        self.teethCtrl.xfo = data['teethXfo']
        #self.teethCtrl.setCurveData(data['teethCtrlCrvData'])
        self.teethCtrl.setColor("turquoise")

        self.teethCtrl.scalePoints(Vec3(Vec3(2.5,2.5,2.5)))
        self.teethCtrl.rotatePoints(90.0, 0.0, 0.0)

        # ==========
        # Deformers
        # ==========

        self.teethDef = Joint(self.getName(), parent=self.deformersLayer)
        self.teethDef.setComponent(self)

        self.parentSpaceInputTgt.childJoints = [self.teethDef]

        # ==============
        # Constrain I/O
        # ==============
        # Constraint inputs

        # ==============
        # Constrain I/O
        # ==============
        # Constraint inputs
        self.teethInputConstraint = self.teethSpace.constrainTo(self.parentSpaceInputTgt, maintainOffset=True)

        # Constraint outputs
        self.teethOutputTgtConstraint = self.teethOutputTgt.constrainTo(self.teethCtrl)
        self.teethDefConstraint = self.teethDef.constrainTo(self.teethCtrl)

        self.teethOutputTgtConstraint.evaluate()

        Profiler.getInstance().pop()

    def loadData(self, data=None):
        """Load a saved guide representation from persisted data.

        Arguments:
        data -- object, The JSON data object.

        Return:
        True if successful.

        """

        super(OSSTeethRig, self).loadData( data )

        self.createControls(data)

        globalScale = Vec3(data['globalComponentCtrlSize'], data['globalComponentCtrlSize'], data['globalComponentCtrlSize'])
        self.teethCtrl.scalePoints(globalScale)

        self.tagAllComponentJoints([self.getDecoratedName()] + self.tagNames)

from kraken.core.kraken_system import KrakenSystem
ks = KrakenSystem.getInstance()
ks.registerComponent(OSSTeethGuide)
ks.registerComponent(OSSTeethRig)


text:
package com.tle.web.institution.tab;

import com.tle.core.system.SystemConfigService;
import com.tle.web.freemarker.FreemarkerFactory;
import com.tle.web.freemarker.annotations.ViewFactory;
import com.tle.web.institution.InstitutionSection;
import com.tle.web.sections.SectionContext;
import com.tle.web.sections.SectionResult;
import com.tle.web.sections.SectionTree;
import com.tle.web.sections.annotations.EventFactory;
import com.tle.web.sections.annotations.EventHandlerMethod;
import com.tle.web.sections.annotations.TreeLookup;
import com.tle.web.sections.equella.annotation.PlugKey;
import com.tle.web.sections.events.RenderEventContext;
import com.tle.web.sections.events.js.EventGenerator;
import com.tle.web.sections.generic.AbstractPrototypeSection;
import com.tle.web.sections.render.HtmlRenderer;
import com.tle.web.sections.standard.Button;
import com.tle.web.sections.standard.Checkbox;
import com.tle.web.sections.standard.TextField;
import com.tle.web.sections.standard.annotations.Component;
import javax.inject.Inject;

@SuppressWarnings("nls")
public class ServerMessageTab extends AbstractPrototypeSection<Object> implements HtmlRenderer {
  @Inject private SystemConfigService systemConfigService;

  @ViewFactory private FreemarkerFactory viewFactory;
  @EventFactory private EventGenerator events;

  @TreeLookup private InstitutionSection institutionSection;

  @Component private Checkbox enabled;
  @Component private TextField message;

  @Component
  @PlugKey(value = "institutions.server.message.save", global = true)
  private Button save;

  @Override
  public void registered(String id, SectionTree tree) {
    super.registered(id, tree);
    save.setClickHandler(events.getNamedHandler("saveClicked"));
  }

  @EventHandlerMethod
  public void saveClicked(SectionContext context) {
    systemConfigService.setServerMessage(message.getValue(context), enabled.isChecked(context));
  }

  @Override
  public SectionResult renderHtml(RenderEventContext context) {
    if (systemConfigService.adminPasswordNotSet()) {
      return null;
    }

    enabled.setChecked(context, systemConfigService.isServerMessageEnabled());
    message.setValue(context, systemConfigService.getServerMessage());
    return viewFactory.createResult("tab/servermessage.ftl", context);
  }

  @Override
  public Class<Object> getModelClass() {
    return Object.class;
  }

  @Override
  public String getDefaultPropertyName() {
    return "server_message";
  }

  public Checkbox getEnabled() {
    return enabled;
  }

  public TextField getMessage() {
    return message;
  }

  public Button getSave() {
    return save;
  }
}


text:
var testScene = {
    name: "Scene 1",
    Backgrounds: [
        {
            height: 420, width: 840, positionX: 0, positionY: 0,
            Draw: function(d) {
                d.drawImage(document.getElementById("background-scene1"), 0, 0);
            }
        }
    ],
	Objects: [new ObjectTest(), new ObjectTestNoOffset(), new ObjectFireBall({x:50, y:300, speed:1.5, angle:0, size:32}), new ObjectFireBall({x:150, y:300, speed:1, angle:0, size:32})],
    Foregrounds: [],
    Terrain: [
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Bricks", "Bricks" , "Bricks", "Bricks", "Bricks", "Bricks", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Bricks", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Bricks", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Bricks","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Bricks","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Bricks","Bricks","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Bricks","Bricks","Empty", "Empty", "Empty", "Bricks", "Bricks"]
    ]
}
var testSceneB = {
    name: "Scene 2",
    Backgrounds: [
        {
            height: 420, width: 840, positionX: 0, positionY: 0,
            Draw: function(d) {
                d.drawImage(document.getElementById("spritesheet"), 0, 0);
            }
        }
    ],
	Objects: [new ObjectTest(), new ObjectTestNoOffset(), new ObjectFireBall({x:50, y:300, speed:1.5, angle:0, size:32}), new ObjectFireBall({x:150, y:300, speed:1, angle:0, size:32})],
    Foregrounds: [],
    Terrain: [
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Bricks", "Bricks" , "Bricks", "Bricks", "Bricks", "Bricks", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Bricks", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Bricks", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Bricks","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Empty","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Bricks","Empty","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Bricks","Bricks","Empty", "Empty", "Empty", "Empty", "Bricks"],
        [ "Bricks", "Bricks", "Empty", "Empty", "Empty", "Bricks","Bricks","Empty", "Empty", "Empty", "Bricks", "Bricks"]
    ]
}


text:
@extends('layouts.master')

@section('content')

Meeting Request Form

@if (session('request_sent'))

        Your meeting request has been sent. Thank you.

    Add new meeting
@else
    @include('common.form')
@endif

@stop


text:
/*
 * DAFFIE events for Earlab Functional Interface
 */
#ifndef _EFI_EVENT_H
#define _EFI_EVENT_H

#include "CMatrixN.h"
#include "CSpike.h"
#include "CEarlabDataStream.h"

#include <daffie/event.h>

#define MAX_DATASIZE         0xffff  /* (64*1024 - 1) */

#define EFI_FILENAME_SIZE       256
#define EFI_NAMESIZE             64
#define EFI_MAXARG               16
#define EFI_MAXDIM               10

/*
 * EFI Dimension descriptors
 */
#define EFI_NONE                   0 /* NONE              */

#define EFI_DIM_SAMPLE             10  /* scalar sample    */
#define EFI_DIM_TIME               20  /* time             */
#define EFI_DIM_CHANNEL            30  /* channels         */
#define EFI_DIM_DELAY              40  /* delays           */
#define EFI_DIM_REPS               50  /* repetitons       */

/* Scalar types */
#define EFI_WAVEFORM_PRESSURE      1  /* micropascals      */
#define EFI_WAVEFORM_DISPLACEMENT  2  /* nanometers        */
#define EFI_WAVEFORM_VOLTAGE       3  /* microvolts        */
#define EFI_NERUON_ST              4  /* spike train times */
#define EFI_NERUON_IFR             5  /* firing rates      */

/*
 * Status messages
 */

/* Report types (type) */
#define EFI_STATUS_LOAD            1 /* Module load             */
#define EFI_STATUS_PARAM           2 /* Module parameters       */
#define EFI_STATUS_CONFIG          3 /* Module configuration    */
#define EFI_STATUS_START           4 /* Module start            */
#define EFI_STATUS_STOP            5 /* Module stop             */
#define EFI_STATUS_ADVANCE         6 /* Module advance          */
#define EFI_STATUS_SEND            7 /* Module send data        */
#define EFI_STATUS_CONTROL         8 /* Msg for control layer   */
#define EFI_STATUS_FRAME           9 /* Frame msg from control  */
#define EFI_STATUS_UNLOAD         10 /* Module unload           */

#define EFI_STATUS_MAXTYPE 10

static char *
StatusTypeMsg[] = {
	"INVALID",
	"load",
	"param",
	"config",
	"start",
	"stop",
	"advance",
	"send",
	"control",
	"frame",
	"unload",
	NULL
};

/* Status indicator (status) */
#define EFI_STATUS_OK              1 /* operation okay          */
#define EFI_STATUS_READY           1 /* module ready (equiv OK) */
#define EFI_STATUS_IDLE            2 /* module is idle          */
#define EFI_STATUS_STARTING        3 /* operation starting      */
#define EFI_STATUS_WAITDATA        4 /* module awaiting data    */
#define EFI_STATUS_INFO            5 /* information             */
#define EFI_STATUS_WARNING         6 /* possible error          */
#define EFI_STATUS_ERROR           7 /* fatal runtime error     */
#define EFI_STATUS_DIED            8 /* client prematurely died */

#define EFI_STATUS_MAXSTATUS EFI_STATUS_DIED

static char *
StatusStatusMsg[] = {
	"UNKNOWN",
	"ready",
	"idle",
	"starting",
	"waitdata",
	"info",
	"warning",
	"run error",
	"died",
};

/*
 * Control types
 */
#define EFI_CTL_QUERY   1
#define EFI_CTL_PROBE   2
#define EFI_CTL_STATUS  3

/*
 * NB in the DATA events:
 *     elems is total elements for this frame which may comprise
 *           multiple events
 *     index0,indexN are element indices for this event
 */
typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	int             elems;                  /* total elem in stream   */
	int             tag;                    /* stream tag             */
	int             frame;                  /* frame number           */
	short           endian;                 /* 0=little, 1=big        */
	short           type;                   /* data type (wave,spike) */
	int             index0;                 /* first element of data  */
	int             indexN;                 /* last element of data   */
	MATRIXN_T       data[1];                /* data payload           */
} EVENT_EFI_WAVEDATA;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	int             elems;                  /* total elem in stream   */
	int             tag;                    /* stream tag             */
	int             frame;                  /* frame number           */
	short           endian;                 /* 0=little, 1=big        */
	short           type;                   /* data type (wave,spike) */
	int             index0;                 /* first element of data  */
	int             indexN;                 /* last element of data   */
	TSpike          data[1];                /* data payload           */
} EVENT_EFI_SPIKEDATA;

/*
 * The following is the "untyped" version of an EFI DATA stream
 * are not used as actual events, but only as a placeholder for
 * one of the actual typed events
 */
typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	int             elems;                  /* number of elements     */
	int             tag;                    /* stream tag             */
	int             frame;                  /* frame number           */
	short           endian;                 /* 0=little, 1=big        */
	short           type;                   /* data type (wave,spike) */
	int             index0;                 /* first element of data  */
	int             indexN;                 /* last element of data   */
	BYTE            data[4];                /* data payload           */
} EVENT_EFI_DATA;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	int             ninput;                 /* Number of input args   */
	int             input_type[EFI_MAXARG]; /* Types of input args    */
	int             input_rank[EFI_MAXARG][EFI_MAXDIM]; /* Number of elements  */
	int             noutput;                /* Number of outputs      */
	int             output_type[EFI_MAXARG];/* Type of outputs        */
	int             output_rank[EFI_MAXARG][EFI_MAXDIM]; /* Number of elements  */
	int             output_size[EFI_MAXARG];/* Max number of elements */
} EVENT_EFI_START;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	int             rc;                     /* return code            */
} EVENT_EFI_STOP;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	int             exitcode;               /* Exit code              */
} EVENT_EFI_UNLOAD;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	int             frame;                  /* Frame number           */
} EVENT_EFI_ADVANCE;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	int             type;                   /* Status being reported  */
	int             status;                 /* Status                 */
	int             detail;                 /* Where the devil lives  */
	int             frame;                  /* Frame number           */
	int             timestamp;              /* Timestamp in millisecs */
} EVENT_EFI_STATUS;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	char            filename[EFI_FILENAME_SIZE];
	char            section[EFI_NAMESIZE];
} EVENT_EFI_PARAMETER_FILE;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	char            paramspec[4];           /* parameter spec as a string */
} EVENT_EFI_PARAMETER_SET;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	char            name[EFI_NAMESIZE];     /* Module name            */
	int             ninput;                 /* Number of input args   */
	int             input_type[EFI_MAXARG]; /* Types of input args    */
	int             noutput;                /* Number of outputs      */
	int             output_type[EFI_MAXARG];/* Type of outputs        */
} EVENT_EFI_SPEC;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	int             ninput;                 /* Number of input args   */
	int             input_type[EFI_MAXARG]; /* Types of input args    */
	int             input_desc[EFI_MAXARG]; /* Input array descriptor */
	int             input_tag[EFI_MAXARG];  /* Tag for input          */
	int             input_from[EFI_MAXARG]; /* Source of input        */
	int             input_rank[EFI_MAXARG][EFI_MAXDIM]; /* Array dims */
	int             input_size[EFI_MAXARG]; /* Max # of elements      */
	int             noutput;                /* Number of outputs      */
	int             output_type[EFI_MAXARG];/* Type of outputs        */
	int             output_desc[EFI_MAXARG];/* Output array descriptor*/
	int             output_tag[EFI_MAXARG]; /* Tag for output         */
	int             output_to[EFI_MAXARG];  /* Destination of output  */
	int             output_rank[EFI_MAXARG][EFI_MAXDIM];/* Array dims */
	int             output_size[EFI_MAXARG];/* Max # of elements      */
} EVENT_EFI_CONFIG;

typedef struct {
	BYTE            data[MAX_DATASIZE];     /* maximum payload        */
} EVENT_EFI_MAXDATA;

typedef struct {
	EVENT_HEAD      head;                   /* DAFFIE header          */
	int             type;                   /* Control type           */
	int             param;                  /* Argument/parameter     */
	int             value;                  /* Value of above         */
	int             flag;                   /* Flag                   */
	int             tag;                    /* Tag for response       */
	int             clientid;               /* Client to send to      */
} EVENT_EFI_CTL;

#define ET_EFI_SPEC              1000
#define ET_EFI_CONFIG            1001
#define ET_EFI_STATUS            1002
#define ET_EFI_PARAMETER_FILE    1010
#define ET_EFI_START             1011
#define ET_EFI_ADVANCE           1012
#define ET_EFI_STOP              1013
#define ET_EFI_CTL               1014
#define ET_EFI_UNLOAD            1015
#define ET_EFI_PARAMETER_SET     1016
#define ET_EFI_WAVEDATA          1017
#define ET_EFI_SPIKEDATA         1018

#define ET_EFI_DATA_LO ET_EFI_WAVEDATA
#define ET_EFI_DATA_HI ET_EFI_SPIKEDATA

#define ET_EFI_MIN 1000
#define ET_EFI_MAX 1019

#define EFI_EVENTS \
	EVENT_EFI_SPEC           ev_efi_spec;           \
	EVENT_EFI_CONFIG         ev_efi_config;         \
	EVENT_EFI_PARAMETER_FILE ev_efi_parameter_file; \
	EVENT_EFI_START          ev_efi_start;          \
	EVENT_EFI_ADVANCE        ev_efi_advance;        \
	EVENT_EFI_STOP           ev_efi_stop;           \
	EVENT_EFI_UNLOAD         ev_efi_unload;         \
	EVENT_EFI_CTL            ev_efi_ctl;            \
	EVENT_EFI_MAXDATA        ev_efi_maxdata;        \
	EVENT_EFI_WAVEDATA       ev_efi_wavedata;       \
	EVENT_EFI_SPIKEDATA      ev_efi_spikedata;      \

#include "agentd.h"

#endif


text:
package com.github.romankh3.image.comparison.model;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("Unit-level testing for {@link ExcludedAreas} object.")
public class ExcludedAreasUnitTest {

    @DisplayName("Should properly create bean")
    @Test
    public void shouldProperlyCreateBean() {
        //when
        ExcludedAreas excludedAreas = new ExcludedAreas();

        //then
        assertNotNull(excludedAreas);
    }

    @DisplayName("Should properly get rectangle list")
    @Test
    public void shouldProperlyWorkGettingRectangleList() {
        //given
        List<Rectangle> rectangles = Arrays.asList(Rectangle.createDefault(), Rectangle.createZero());

        //when
        ExcludedAreas excludedAreas = new ExcludedAreas(rectangles);

        //then
        assertEquals(rectangles, excludedAreas.getExcluded());
    }

}


text:
package org.mybatis.guice.configuration;

public interface ErrorMapper {
  public int selectCount();
}


text:
using System.Collections.Generic;
using System.Linq;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
using Castle.Windsor;
using Common.Logging;
using Common.Logging.Simple;
using CommonServiceLocator.WindsorAdapter;
using FluentAssertions;
using Highway.Data.EntityFramework.Tests.Mapping;
using Highway.Data.EntityFramework.Tests.Properties;
using Highway.Data.EntityFramework.Tests.TestQueries;
using Highway.Data.EntityFramework.Tests.UnitTests;
using Highway.Data.Tests.TestDomain;
using Microsoft.Practices.ServiceLocation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;

namespace Highway.Data.EntityFramework.Tests.Queries
{
    [TestClass]
    public class Given_A_ProjectionQuery_Object
    {
        internal static IWindsorContainer container;

        [ClassInitialize]
        public static void SetupClass(TestContext context)
        {
            container = new WindsorContainer();
            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
            container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));
            container.Register(Component.For<IDataContext>().ImplementedBy<TestDataContext>().DependsOn(
                new {connectionString = Settings.Default.Connection}).LifestyleTransient(),
                Component.For<IMappingConfiguration>().ImplementedBy<FooMappingConfiguration>().
                    LifestyleTransient(),
                Component.For<ILog>().ImplementedBy<NoOpLogger>());
        }

        [TestMethod]
        public void When_Passing_To_A_Repository_Query_Object_Then_It_Executes_Against_Context()
        {
            //Arrange
            var context = MockRepository.GenerateStrictMock<IDataContext>();
            context.Expect(x => x.AsQueryable<Foo>()).Return(new List<Foo>().AsQueryable()).Repeat.Once();
            var repository = new Repository(context);

            //Act
            repository.Find(new FindFooName());

            //Assert
            context.VerifyAllExpectations();
        }

        [TestMethod]
        public void When_Executed_Returns_An_IEnumerable_Of_Items()
        {
            //Arrange
            var context = MockRepository.GenerateStrictMock<IDataContext>();
            context.Expect(x => x.AsQueryable<Foo>()).Return(new List<Foo>().AsQueryable()).Repeat.Once();
            var query = new FindFooName();

            //Act
            IEnumerable<string> items = query.Execute(context);

            //Assert
            context.VerifyAllExpectations();
            items.Should().NotBeNull();
        }

        [TestMethod]
        public void When_Paging_Should_Affect_The_Base_Query_Before_It_Is_Executed()
        {
            //Arrange
            var targetFoo = new Foo {Name = "Test"};
            var context = MockRepository.GenerateStrictMock<IDataContext>();
            context.Expect(x => x.AsQueryable<Foo>()).Return(new List<Foo>
            {
                new Foo(),
                new Foo(),
                new Foo(),
                new Foo(),
                targetFoo
            }.AsQueryable()).Repeat.Once();
            var query = new FindFooName();

            //Act
            IEnumerable<string> retVal = query.Skip(4).Take(1).Execute(context);

            //Assert
            retVal.First().Should().Be(targetFoo.Name);
        }

        [TestMethod]
        public void When_Calling_Output_Sql_with_Context_It_Outputs_SQL()
        {
            //arrange
            var target = new FindFooName();

            var context = container.Resolve<IDataContext>();

            //act
            string sqlOutput = target.OutputSQLStatement(context);

            //assert

            sqlOutput.Should().NotBeNull();
            sqlOutput.Should().Contain("FROM");
        }
    }
}


text:
require 'socket'

module DockerWatcher
  class Server
    attr_reader :name, :docker

    def initialize(conn_string)
      @docker = Docker::Connection.new(conn_string, {read_timeout: 3600 * 24 * 365})
      Docker.version(@docker) # force the lazy connection to connect

      @name = if !!conn_string.index('unix')
        Socket.gethostname
      else
        conn_string.split('/')[2].split(':').first
      end
    end

    def stream!
      retries = 0
      begin
        DaemonKit.logger.info("Connecting to #{name} for events")
        Docker::Event.stream({}, @docker) do |event|
          retries = 0
          yield event
        end
      rescue Docker::Error::TimeoutError
        DaemonKit.logger.error($!.message + "\n" + $!.backtrace.join("\n"))
        DaemonKit.logger.debug("Docker #{name} stream timed out, reconnecting")
        retry
      rescue Excon::Errors::SocketError
        DaemonKit.logger.error($!.message + "\n" + $!.backtrace.join("\n"))
        DaemonKit.logger.error("Docker #{name} stream closed, will attempt to reconnect in 5 seconds")
        sleep 5 if retries >= 3
        retries += 1
        retry
      end
    end

  end
end


text:
<CORSConfiguration>
    <CORSRule>
        <!-- At least one AllowedOrigin or AllowedMethod must be specified -->
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>


text:
<?php
/*********************************************************************
 *
 * FILE:				drive.php
 * AUTHOR:			Jake Breindel
 * DATE:				4-7-2014
 *
 * DESRIPTION:
 * 	Drive endpoint for accessing the drive api.
 *
 **********************************************************************/

// You'll want to include security here
require('main.inc.php');

// IF this for a specific file
if($_GET['file']){
	$page='drive-file.inc.php';
}
// ELSE show the list page
else{
	$page='drive.inc.php';
}

require(STAFFINC_DIR.'header.inc.php');
require(STAFFINC_DIR.$page);
include(STAFFINC_DIR.'footer.inc.php');

?>


text:
package com.amazonaws.services.rds.model.transform;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.internal.ListWithAutoConstructFlag;
import com.amazonaws.services.rds.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * Modify Option Group Request Marshaller
 */
public class ModifyOptionGroupRequestMarshaller implements Marshaller<Request<ModifyOptionGroupRequest>, ModifyOptionGroupRequest> {

    public Request<ModifyOptionGroupRequest> marshall(ModifyOptionGroupRequest modifyOptionGroupRequest) {

        if (modifyOptionGroupRequest == null) {
            throw new AmazonClientException("Invalid argument passed to marshall(...)");
        }

        Request<ModifyOptionGroupRequest> request = new DefaultRequest<ModifyOptionGroupRequest>(modifyOptionGroupRequest, "AmazonRDS");
        request.addParameter("Action", "ModifyOptionGroup");
        request.addParameter("Version", "2014-10-31");

        if (modifyOptionGroupRequest.getOptionGroupName() != null) {
            request.addParameter("OptionGroupName", StringUtils.fromString(modifyOptionGroupRequest.getOptionGroupName()));
        }

        java.util.List<OptionConfiguration> optionsToIncludeList = modifyOptionGroupRequest.getOptionsToInclude();
        int optionsToIncludeListIndex = 1;

        for (OptionConfiguration optionsToIncludeListValue : optionsToIncludeList) {
            OptionConfiguration optionConfigurationMember = optionsToIncludeListValue;
            if (optionConfigurationMember != null) {
                if (optionConfigurationMember.getOptionName() != null) {
                    request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".OptionName", StringUtils.fromString(optionConfigurationMember.getOptionName()));
                }
                if (optionConfigurationMember.getPort() != null) {
                    request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".Port", StringUtils.fromInteger(optionConfigurationMember.getPort()));
                }

                java.util.List<String> dBSecurityGroupMembershipsList = optionConfigurationMember.getDBSecurityGroupMemberships();
                int dBSecurityGroupMembershipsListIndex = 1;

                for (String dBSecurityGroupMembershipsListValue : dBSecurityGroupMembershipsList) {
                    if (dBSecurityGroupMembershipsListValue != null) {
                        request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".DBSecurityGroupMemberships.DBSecurityGroupName." + dBSecurityGroupMembershipsListIndex, StringUtils.fromString(dBSecurityGroupMembershipsListValue));
                    }

                    dBSecurityGroupMembershipsListIndex++;
                }

                java.util.List<String> vpcSecurityGroupMembershipsList = optionConfigurationMember.getVpcSecurityGroupMemberships();
                int vpcSecurityGroupMembershipsListIndex = 1;

                for (String vpcSecurityGroupMembershipsListValue : vpcSecurityGroupMembershipsList) {
                    if (vpcSecurityGroupMembershipsListValue != null) {
                        request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".VpcSecurityGroupMemberships.VpcSecurityGroupId." + vpcSecurityGroupMembershipsListIndex, StringUtils.fromString(vpcSecurityGroupMembershipsListValue));
                    }

                    vpcSecurityGroupMembershipsListIndex++;
                }

                java.util.List<OptionSetting> optionSettingsList = optionConfigurationMember.getOptionSettings();
                int optionSettingsListIndex = 1;

                for (OptionSetting optionSettingsListValue : optionSettingsList) {
                    OptionSetting optionSettingMember = optionSettingsListValue;
                    if (optionSettingMember != null) {
                        if (optionSettingMember.getName() != null) {
                            request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".OptionSettings.OptionSetting." + optionSettingsListIndex + ".Name", StringUtils.fromString(optionSettingMember.getName()));
                        }
                        if (optionSettingMember.getValue() != null) {
                            request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".OptionSettings.OptionSetting." + optionSettingsListIndex + ".Value", StringUtils.fromString(optionSettingMember.getValue()));
                        }
                        if (optionSettingMember.getDefaultValue() != null) {
                            request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".OptionSettings.OptionSetting." + optionSettingsListIndex + ".DefaultValue", StringUtils.fromString(optionSettingMember.getDefaultValue()));
                        }
                        if (optionSettingMember.getDescription() != null) {
                            request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".OptionSettings.OptionSetting." + optionSettingsListIndex + ".Description", StringUtils.fromString(optionSettingMember.getDescription()));
                        }
                        if (optionSettingMember.getApplyType() != null) {
                            request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".OptionSettings.OptionSetting." + optionSettingsListIndex + ".ApplyType", StringUtils.fromString(optionSettingMember.getApplyType()));
                        }
                        if (optionSettingMember.getDataType() != null) {
                            request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".OptionSettings.OptionSetting." + optionSettingsListIndex + ".DataType", StringUtils.fromString(optionSettingMember.getDataType()));
                        }
                        if (optionSettingMember.getAllowedValues() != null) {
                            request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".OptionSettings.OptionSetting." + optionSettingsListIndex + ".AllowedValues", StringUtils.fromString(optionSettingMember.getAllowedValues()));
                        }
                        if (optionSettingMember.isModifiable() != null) {
                            request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".OptionSettings.OptionSetting." + optionSettingsListIndex + ".IsModifiable", StringUtils.fromBoolean(optionSettingMember.isModifiable()));
                        }
                        if (optionSettingMember.isCollection() != null) {
                            request.addParameter("OptionsToInclude.OptionConfiguration." + optionsToIncludeListIndex + ".OptionSettings.OptionSetting." + optionSettingsListIndex + ".IsCollection", StringUtils.fromBoolean(optionSettingMember.isCollection()));
                        }
                    }

                    optionSettingsListIndex++;
                }
            }

            optionsToIncludeListIndex++;
        }

        java.util.List<String> optionsToRemoveList = modifyOptionGroupRequest.getOptionsToRemove();
        int optionsToRemoveListIndex = 1;

        for (String optionsToRemoveListValue : optionsToRemoveList) {
            if (optionsToRemoveListValue != null) {
                request.addParameter("OptionsToRemove.member." + optionsToRemoveListIndex, StringUtils.fromString(optionsToRemoveListValue));
            }

            optionsToRemoveListIndex++;
        }
        if (modifyOptionGroupRequest.isApplyImmediately() != null) {
            request.addParameter("ApplyImmediately", StringUtils.fromBoolean(modifyOptionGroupRequest.isApplyImmediately()));
        }

        return request;
    }
}


text:
#pragma once

namespace Shakara
{
	enum class TokenizeError : uint8_t;

	enum class TokenType : uint8_t;

	struct Token;

	/**
	 * A simple Tokenizer implementation for
	 * the language.
	 */
	class Tokenizer
	{
	public:
		/**
		 * Simply iterates through each character
		 * in the passed in stream, generating
		 * tokens along the way.
		 *
		 * The tokens vector should be passed in,
		 * and once the function is over, will be
		 * filled with individual tokens from the
		 * file.
		 *
		 * Returns a TokenizeError enum for errors
		 * encountered in parsing.
		 */
		TokenizeError Tokenize(
			std::istream&       stream,
			std::vector<Token>& tokens
		);

	private:
		/**
		 * Sets a Token struct up based on the value
		 * passed in.
		 *
		 * Takes in a pointer to allocated memory for
		 * one token.
		 */
		void _SetTokenFromValue(Token* token, const std::string& value);

		/**
		 * Tries to make a unary operator from the current
		 * token, the last token, and the last character
		 * moved through.
		 *
		 * Returns true if a unary was found and changed,
		 * or false otherwise.
		 */
		bool _MakeUnary(
			Token& current,
			const Token& last,
			const char lastChar
		);

		/**
		 * Grab a token type from the current value.
		 *
		 * Takes in a pointer to allocated memory
		 * for one token.
		 *
		 * Returns true if a type is found.
		 */
		bool _DetermineTokenTypeFromValue(TokenType* type, const std::string& value);

		/**
		 * Whether a character is a single token,
		 * such as equal or minus.
		 */
		bool _IsSingleCharacterToken(char character);

	};
}


text:
var gulp = require('gulp')
var concat = require('gulp-concat')
var uglify = require('gulp-uglify')
var watch = require('gulp-watch')
var sourcemaps = require('gulp-sourcemaps')

gulp.task('scripts', function () {
  gulp.src(['./app_client/**/*.js', '!./app_client/**/*.test.js', '!./app_client/app.min.js'])
		.pipe(sourcemaps.init())
		.pipe(concat('./app.min.js'))
		.pipe(uglify({mangle: true}))
		.pipe(sourcemaps.write('./'))
		.pipe(gulp.dest('public/js/'))
})

gulp.task('ng-templates', function () {
	gulp.src(['./app_client/**/*.html'])
		.pipe(gulp.dest('public/'))
})

gulp.task('watch', () => {
  watch(['./app_client/**/*.js', '!./app_client/**/*.test.js', '!./app_client/app.min.js'], function () {
    gulp.start('scripts')
  })
  watch(['./app_client/**/*.html'], function () {
  	gulp.start('ng-templates')
  })
})

gulp.task('default', ['ng-templates', 'scripts', 'watch'])


text:
/**
 * @since 2019-07-29 12:37
 * @author vivaxy
 */
import { Provider } from './lib/redux.js';
import Counter from './components/Counter.js';
import RenderCount from './components/RenderCount.js';
import { reducer, initialState } from './reducer.js';

const { React } = window;

export default function App() {
  return React.createElement(
    Provider,
    {
      reducer,
      initialState,
    },
    [
      React.createElement(Counter),
      React.createElement('br'),
      React.createElement(RenderCount),
    ],
  );
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2022 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  tools:context=".ConfigurationActivity">

  <TableLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:stretchColumns="1"
      android:layout_marginTop="32dp"
      android:measureWithLargestChild="true"
      android:paddingLeft="24dp"
      android:paddingRight="12dp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintBottom_toBottomOf="parent">
      <TableRow
        android:layout_weight="1"
        android:gravity="center_vertical" >
        <TextView
          android:text="@string/center_x" />
        <com.google.android.material.slider.Slider
          android:id="@+id/periodic_vignette_center_x_slider"
          android:valueFrom="0.0"
          android:value="0.5"
          android:valueTo="1.0"
          android:layout_gravity="right"/>
      </TableRow>
      <TableRow
        android:layout_weight="1"
        android:gravity="center_vertical" >
        <TextView
          android:text="@string/center_y" />
        <com.google.android.material.slider.Slider
          android:id="@+id/periodic_vignette_center_y_slider"
          android:valueFrom="0.0"
          android:value="0.5"
          android:valueTo="1.0"
          android:layout_gravity="right"/>
      </TableRow>
      <TableRow
        android:layout_weight="1"
        android:gravity="center_vertical" >
        <TextView
          android:text="@string/radius_range" />
        <com.google.android.material.slider.RangeSlider
          android:id="@+id/periodic_vignette_radius_range_slider"
          android:valueFrom="0.0"
          android:valueTo="1.414"
          android:layout_gravity="right"/>
      </TableRow>
    </TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout>


text:
package org.codehaus.mojo.build;

import org.apache.maven.scm.log.ScmLogger;
import org.codehaus.plexus.util.cli.StreamConsumer;

public class GitRevParseConsumer
implements StreamConsumer
{
  private ScmLogger logger;

    // private Map properties = new HashMap();

    private StringBuffer commandOutput = new StringBuffer();

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

    public GitRevParseConsumer(ScmLogger logger) {
    this.logger = logger;
    }

    // ----------------------------------------------------------------------
    // StreamConsumer Implementation
    // ----------------------------------------------------------------------

    public void consumeLine(String line) {
	commandOutput.append(line);
    }

    /**
     * The raw output from the command.
     *
     * @return the raw output from the command
     */
    public String getCommandOutput() {
	return commandOutput.toString();
    }

}


text:
'use strict';
var grunt = require('grunt');
var assert = require('assert');
var sfdcAuth = require('../../tasks/sfdc-auth');

describe('validation', function() {
  var warnMessages;
  var gruntWarn;
  beforeEach(function(){
    warnMessages = [];
    gruntWarn = grunt.fail.warn;
    grunt.fail.warn = function(message){
      warnMessages.push(message);
    };
  });
  afterEach(function(){
    grunt.fail.warn = gruntWarn;
  });
  it('should fail if options is empty', function(){

    var options = {};
    sfdcAuth.parseAuth(options)
    assert.equal('username/password error',warnMessages[0]);
  });

  it('should pass if user and pass are set', function(){
    var options = {
      user:'user',
      pass:'pass'
    };
    sfdcAuth.parseAuth(options)
    assert.equal(0,warnMessages.length);
  });

  it('should pass if sessionid and serverurl are set', function(){
    var options = {
      sessionid:'sessionid',
      serverurl:'serverurl'
    };
    sfdcAuth.parseAuth(options)
    assert.equal(0,warnMessages.length);
  });
});

describe('configuration', function() {
  it('should set sessionid and serverurl from sessionConfig', function(){
    var options = {
      sessionConfig: {accessToken: '123', instanceUrl: 'abc'}
    };
    sfdcAuth.parseAuth(options)
    assert.equal('123',options.sessionid);
    assert.equal('abc',options.serverurl);
  });

  it('should set values from environment variables', function(){
    var options = {
      useEnv: true
    };
    process.env.SFUSER = 'user';
    process.env.SFPASS = 'pass';
    process.env.SFTOKEN = 'token';
    process.env.SFSESSIONID = 'sessionid';
    process.env.SFSERVERURL = 'serverurl';
    sfdcAuth.parseAuth(options)
    assert.equal('user',options.user);
    assert.equal('passtoken',options.pass);
    assert.equal('token',options.token);
    assert.equal('sessionid',options.sessionid);
    assert.equal('serverurl',options.serverurl);
  });
})


text:
import _reduce from 'lodash/reduce';
import _filter from 'lodash/filter';
import constants from '../constants';
import arrayToHash from '../../../utils/func/arrayToHash';

const initialState = {};

/**
 * List of the show episodes group by season and episode number
 *
 * **Actions listened**:
 *
 *  * `FETCH_SHOW_EPISODES`
 *  * `FETCH_MANY_EPISODES`
 *  * `FETCH_LATEST_EPISODE`
 *  * `FETCH_EPISODE_BY_CODE`
 *  * `FETCH_EPISODE`
 *  * `MARK_MANY_EPISODE_AS_WATCHED`
 *  * `UNMARK_MANY_EPISODE_AS_WATCHED`
 *  * `MARK_EPISODE_AS_WATCHED`
 *  * `UNMARK_EPISODE_AS_WATCHED`
 *  * `ADD_SHOW`
 *  * `REMOVE_SHOW`
 *
 * @alias module:Shows.episodes
 * @category reducers
 *
 * @example
 * // get reducer
 * BetaSeries.getReducer('shows', 'episodes').showsEpisodes;
 *
 * // state example
 * {
 *   '3215': {            // episode ID
 *     id: 3215,          // episode ID
 *     ...episode,        // episode element
 *   },
 *   ...,
 * }
 *
 * @param {Object} state
 * @param {Object} action
 *
 * @returns {Object}
 */
export default function showEpisodesReducer(state = initialState, action) {
  switch (action.type) {
    case constants.FETCH_SHOW_EPISODES:
    case constants.FETCH_MANY_EPISODES:
      return {
        ...state,
        ...arrayToHash(action.payload.episodes)
      };

    case constants.FETCH_LATEST_EPISODE:
    case constants.FETCH_EPISODE_BY_CODE:
    case constants.FETCH_EPISODE:
    case constants.MARK_EPISODE_AS_WATCHED:
    case constants.RATE_EPISODE:
      return {
        ...state,
        ...arrayToHash([action.payload.episode])
      };

    case constants.FETCH_EPISODES_LIST:
      return {
        ...state,
        ...arrayToHash(
          _reduce(
            action.payload.shows,
            (sum, show) => [...sum, ...show.unseen],
            []
          )
        )
      };

    case constants.MARK_MANY_EPISODE_AS_WATCHED:
    case constants.UNMARK_MANY_EPISODE_AS_WATCHED: {
      const episodeIds = action.payload.episodeIds;

      const nextEpisodes = episodeIds.reduce(
        (sum, episodeId) => {
          if (!Object.prototype.hasOwnProperty.call(state, episodeId)) {
            return sum;
          }

          return {
            ...sum,
            [episodeId]: {
              ...state[episodeId],
              user: {
                ...state[episodeId].user,
                seen: action.payload.seen
              }
            }
          };
        },
        {}
      );

      return {
        ...state,
        ...nextEpisodes
      };
    }

    case constants.UNMARK_EPISODE_AS_WATCHED: {
      const episodeId = action.payload.episodeId;
      if (!Object.prototype.hasOwnProperty.call(state, episodeId)) {
        return state;
      }

      return {
        ...state,
        [episodeId]: {
          ...state[episodeId],
          user: {
            ...state[episodeId].user,
            seen: action.payload.seen
          }
        }
      };
    }

    case constants.MARK_EPISODE_AS_DOWNLOADED:
    case constants.UNMARK_EPISODE_AS_DOWNLOADED: {
      const episodeId = action.payload.episodeId;
      if (!Object.prototype.hasOwnProperty.call(state, episodeId)) {
        return state;
      }

      return {
        ...state,
        [episodeId]: {
          ...state[episodeId],
          user: {
            ...state[episodeId].user,
            downloaded: action.payload.downloaded
          }
        }
      };
    }

    case constants.ADD_SHOW:
    case constants.REMOVE_SHOW: {
      const episodes = _filter(
        state,
        episode => episode.show.id === action.payload.showId
      );

      if (Object.keys(episodes).length === 0) {
        return state;
      }

      return {
        ...state,
        ...arrayToHash(
          episodes.map(episode => {
            const user = episode.user || {};
            return {
              ...episode,
              user: {
                ...user,
                seen: false
              },
              show: {
                ...episode.show,
                in_account: action.type === constants.ADD_SHOW
              }
            };
          })
        )
      };
    }

    default:
      return state;
  }
}


text:
enum { debug = 0 };

int affinity_set(int cpu);
#ifndef __WIN__
#define threadid_t pthread_t
typedef void *(*thread_entry_t) (void *);
#else
#define threadid_t HANDLE
typedef DWORD WINAPI(*thread_entry_t) (LPVOID);
#endif

threadid_t getself();
threadid_t create_thread(thread_entry_t, void *arg);

#ifdef __WIN__

#define TLS __declspec(thread)

#define mr_print(flag, x, ...) \
do \
{ \
    if (flag) \
    { \
        printf(x, __VA_ARGS__); \
    } \
}while(0)

#define dprintf(x, ...) mr_print(debug, x, __VA_ARGS__)

#define  __attribute__(x)
#define metis_barrier() __asm volatile ("mfence": : :"memory")
extern char *optarg;
extern DWORD gFileSize;
int getopt(int argc, char *const argv[], const char *optstring);
int getFileMap(TCHAR * filename, char **data);
void closeFileMap();

#else

#define TLS __thread

#define metis_barrier() __asm__ __volatile__("mfence": : :"memory")
#define mr_print(flag, x...) \
do \
{ \
    if (flag) \
    { \
        printf(x); \
    } \
}while(0)
#define dprintf(x...) mr_print(debug, x)
#endif
#endif


text:
<!doctype html>

    <meta charset="utf-8">

    <title>Class 2 ~ HTML/CSS ~ Girl Develop It</title>

    <meta name="description" content="This is curriculum for the GDI RDU intro to web series. It was developed from the official Girl Develop It Core HTML/CSS curriculum">
    <meta name="author" content="Girl Develop It">

    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

    <link rel="stylesheet" href="css/reveal.css">
    <link rel="stylesheet" href="css/theme/simple.css" id="theme">
    <link rel="stylesheet" href="css/custom.css">

    <link rel="stylesheet" href="lib/css/light.css">

    <link rel="stylesheet" href="plugin/accessibility-helper/css/accessibility-helper.css">

    <link rel="stylesheet" href="css/print/pdf.css" type="text/css" media="print">
    <link rel="icon" type="image/x-icon" href="favicon.ico" />

Intro to HTML/CSS

Part 2

Quiz Part 1

Which tag is used to create a link to another page?

<p>

<link>

<a>

<schnauzers>

Answer: <a>

Quiz Part 2

What are the two tags that nest directly within the <html> tags?

Answer: <head> and <body>

Quiz Part 3

What is it called when you have a 'tag' + 'content' + 'closing tag'?

Answer: An HTML Element

Let's Review

Photo credit:  Ginable cc

Anatomy of a website

Your Content

            + HTML: Structure

            + CSS: Presentation

            = Your Website

A website is a way to present your content to the world, using HTML and CSS to present that content & make it look good.

CSS: What is it?

CSS = Cascading Style Sheets

CSS is a "style sheet language" that lets you style the elements on your page.

CSS is works in conjunction with HTML, but is not HTML itself.

            And now we arrive at CSS. CSS gives us style!

CSS: What can it do?

All color, text, position, and size

            So what can CSS do? A lot actually! CSS controls color, text, position (where and how things appear) and size. CSS can also do some pretty amazing things with animation, but that's a topic for another class. Let's just CSS is pretty darn powerful.

CSS: What does it look like?

The CSS Rule

The CSS Rule

selector {
  property: value;
}

A block of CSS code is a rule.

The rule starts with a selector.

It has sets of properties and values.

A property-value pair is a declaration.

Connecting CSS to HTML

3 ways

"Inline"

"Embedded"

"External"

Connecting CSS to HTML: Inline

<p style="color:red">Some text.</p>

Uses the HTML attribute style.

Difficult to use in large projects

Not preferred.

            Inlineing your CSS works by adding the HTML attribute "style" and then assigning it a property and value, in this intance, we're saying that we want the text to have the color red. This gets really unweidly, and it can be hard to keep track of all of these rules on a larger project. This method isn't preferred.

Connecting CSS to HTML: Embedded

<head>
  <style type="text/css">
    p {
      color: blue;
      font-size: 12px;
    }
  </style>
</head>

Inside <head> element.

Uses <style> tag.

Can only be used in one html file

Useful if you write HTML email newsletters!

            Another way to get HTML & CSS associated with each other is by embedding styles in the head element. Within the head, you can add the style tag, and add styles in there. The downside is that, if you do it this way, that css can only be used in that singular file. If you had another page called puppies.html, you'd either have to copy &past this CSS over there, or start from scratch. It's not terribly useful if you have a multipage site. HOWEVER! Embedded CSS is the bread and butter of email newsletters. For instance, here's an HTML newsletter that I write every week that uses Embedded CSS, but it is only one page, so it's a perfect usecase.

Connecting CSS to HTML: Linked

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

Shared resource for several pages.

Reduced file size & bandwidth

Easy to maintain in larger projects.

Preferred! 💯

            So if the first two methods are suboptimal for most cases, what do we do? We link! By linking to the CSS file, we enable pages to use that CSS on their page, meaning we don't have to repeat, retype, or remember that CSS. It also reduces your filesize, and keeps all of your style rules tucked in to a nice neat place. So all you do is add the link text in the header like so.

Let's develop it

In the same folder, create a new file called style.css

Add a link to the file in the head of your HTML file

Add the CSS rule below to the CSS file:

body {
  background-color: yellow;
}

OK, so if you haven't already created a style.css file, do that now! Then, let's go in to your index.html file and get it linked up! Finally, add this CSS rule below.

CSS Syntax

Declarations: Property and value of style you plan to use on HTML element.

Declarations end with a semicolon

Declaration groups are surrounded by curly brackets.

selector {
  property: value;
  property: value;
  property: value;
}

CSS Syntax is important, so let's take a look. The CSS sytax begins with the selector, or the thing you are selecting to be styled. Then we add curly braces, we then say what property we'd like to style, then a colon, and then what we want that style to be.

Selector: Element

p {
  property: value;
}

Selects all paragraph elements.

img {
  property: value;
}

Selects all image elements.

CSS Color Values

Your browser can accept colors in many different ways:

Color name (ex. red)

Hexadecimal value (ex. #FF0000)

RGB value (ex. rgb(255, 0, 0))

              The 17 standard colors are:
              aqua,
              black,
              blue,
              fuchsia,
              gray,
              grey,
              green,
              lime,
              maroon,
              navy,
              olive,
              purple,
              red,
              silver,
              teal,
              white,
              and yellow.

            Color is so important in the web, not only because, hey, we like things to look nice, but because it can convey meaning, and help users navigate a site. If you're in branding, colors and color matching are really important to an effective brand strategy. There's a few ways to tell the browser what color you want something to be. There's Color name, so just sayin "red, white, orange", there's a Hexadecimal value, which is a six character code that corresponds to the various aspects of color in it, there is also RGB values, for red green blue. You can find these values through a number of

Property: Color

The color property changes the color of the text.

p {
  color: red;
  color: #ff0000;
  color: rgb(255, 0, 0);
}

I have to say, this was one of those things I forgot all the time when I started. I always wanted to say "text color" or "font color" but nope, it's just color! the color property makes your text colorful.

Property: Background-color

The background-color property changes the color of the background.

p {
  background-color: black;
  background-color: #000000;
  background-color: rgb(0,0,0);
}

Background color does what it says on the tin! It sets the background color for the element.

Let's develop it

Add some rules to your css file

Change the font color and background color of different types of elements

Try selecting links, paragraphs, and lists

Property Values

Each property can have one or more comma separated values.

p{
  color: white;
  background-color: red;
  font-family: Arial, sans-serif;
}

Sometimes, you'll want to have more than one value asigned to a property. When this happens, just separate them with a comma. So here you see that font-family is set to Arial, and then a sans-serif font is set as the fallback, in case Arial wasn't available. We're going to talk about font-family next

Property: Font-family

The font-family property defines which font is used.

p {
  font-family: "Times New Roman";
  font-family: serif;
  font-family: "Arial", sans-serif;
}

Specific font name

Generic name

Comma-separated list

            Font familes decide what fonts get used, and they're assigned in a comma separated list. Offering a fall back font gives your fonts a chance to fail. With something like Arial, it's a pretty safe bet, but if you get in to some fancier web fonts that may not display perfectly on every browser or every machine, it's important to offer a fallback so that users see _something_.

Property: Font-size

The font-size property specifies the size of the font.

p {
  font-size: 12px;
  font-size: 1.5em;
}

Pixels

"em"

Percentage

            Anyone want to guess at what font-size does? Yep, tells you how big the font should be. There's a few ways to do this. You can set it in pixels, which is pretty frequently used. You can also set it as "em"s. I'm just going to read the W3C's definition of ems, because they're smart folks and they have a good one: To allow users to resize the text (in the browser menu), many developers use em instead of pixels.

The em size unit is recommended by the W3C.

1em is equal to the current font size. The default text size in browsers is 16px. So, the default size of 1em is 16px.

Property: Fonts (shorthand)

p {
  font-style: italic;
  font-weight: bold;
  font-size: 10px;
  font-family: sans-serif;
}

          OR

p {
  font: italic bold 10px sans-serif;
}

You can also save yourself some space by using shorthand properties. For example, you can set font style, font weight, font size and font family all on one line.

Let's develop it

Change the fonts of your page

Try changing the font sizes and styles for different elements

Selector: Position

p em {
  color: yellow;
}

Selects all em elements that are within a paragraph

<p>This is <em>important.</em></p>

The associated HTML.

            Let's say you want to select all of the "em" tags in side a paragraph. You can do that with a CSS rule. All you need to do is paragraph, then em, your curly braces, and then your properties.

Selector: Position

Position selectors are more specific

They look for elements inside other elements

We seperate nested elements with a space

Selector: Position

So this code:

ul li a strong{
  color: purple;
}

Means "find a strong tag inside a link inside a list item in an unordered list"

<ul>
  <li><a href="programs.html">Our <strong>program</strong></a></li>
</ul>

Let's develop it

In your CSS file, try a position selector

Remember, you need to look for an element inside another element

Reusing code

As a general coding principle, Don't Repeat Yourself.

To reuse CSS, we use IDs and classes.

Photo credit:  Yo Mostro cc

            CSS enables us to work more efficiently by not repeating ourselves. We're able to set up classes and ID's to help us apply the same rules to different parts of our code. And since we've linked our CSS files, we can access those classes & ID's everywhere.

IDs vs. Classes

ID -- Should only apply to one element on a webpage, i.e., a webpage only has one footer.

            The "#" is how you tell CSS "this is an id."

Class -- Lots of elements can have the same class, i.e., There can be many warnings on one webpage.

            The "." is how you tell CSS "this is a class name."

OK, so, classes vs. ID. Id can only apply to one single element on your page. It cannot be reused. Thing if "Id" as individual, a single identiity.

Class, however, can be used for multiple elements. You can make all of your paragraphs have a class of "pink" if you'd like them to have a pink background. ID's are identified with the # and then a name, and classes use the  .  and then a name.

Selector: ID

#footer {
  property: value;
}

Selects all elements with an id of "footer".

<p id="footer">Copyright 2011</p>

The associated HTML.

Selector: Class

.warning {
  color: red;
}

Selects all elements with a class of "warning".

<p class="warning">Run away!</p>

The associated HTML.

Let's develop it

Add an ID and class to a your HTML

Add CSS rules to target these elements

Cascading

Styles "cascade" down until changed

p{
  color:blue;
  font-family: 'Helvetica';
}
.red {
  color: red;
}
#special {
  font-family: Arial;
}

<p>Paragraph</p>
<p class ="red">Paragraph</p>
<p class = "red" id ="special">Paragraph</p>

Cascading priority

Your browser assigns different priorities to CSS depending on the type of selector.

Important! - Most Important

Inline CSS

ID

Class

Element - Least Important

            This is one of the more challenging concepts in CSS, priority. Sometimes, you'll find that more than 1 CSS rule will have selectors for the same element. So how does CSS decide what rule to go with? In general, there's a kind of super power called "Important" that will always win, but like all superpowers, you've got to be careful. Let's look at this more deeply.

Cascading priority

Your browser also assigns priority based on the specificity of the selection. More specific selectors have higher priority.

.main .sale .clearance p{ //Most specific
  color: red;
}
.header .title p{
  color: green;
}
.footer p{ //Least specific
  color: blue;
}

The more specific you get, the higher the priority the rule has. So each of these rules is selecting a paragraph. The first is selecting paragraphs with the classes of main, sale, and clearance. That's pretty specific. Paragraphs with the classes of header and title are less specific, and this last paragraph with the class of footer is the least specific.

Cascading priority

The tie-breaker is position. Rules lower in the file overwrite rules higher in the file

a{
  background-color: yellow;
}
a{
  background-color: teal;
}
a{ //This rule wins
  background-color: black;
}

So what's up with this? If you've got three CSS rules for the a tag (so your links) Which ones wins? This is where the cascade of cascading style sheets comes in-the rule at the BOTTOM of the style sheet (the bottom of the cascade) wins. So in this example, we'd expect our links to come out black, rather than yellow or teal. If we removed that last rule, they'd be teal, because that's lower in the cascade.

CSS Properties

Many CSS properties have self-explanatory names:

background-color

font-family

font-size

color

width

height

Comprehensive list of all CSS properties

            There are many CSS properties, but by and large, their names are self explanatory. If you want a complete, and exhaustive, list of ALL the possible CSS properties, the Mozilla Developer Network provides a great reference. Let's take a look here.

Questions?

          HTML/CSS ~ Girl Develop It


text:
<?php

namespace Zilf\Console\Presets;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;

class React extends Preset
{
    /**
     * Install the preset.
     *
     * @return void
     */
    public static function install()
    {
        static::ensureComponentDirectoryExists();
        static::updatePackages();
        static::updateWebpackConfiguration();
        static::updateBootstrapping();
        static::updateComponent();
        static::removeNodeModules();
    }

    /**
     * Update the given package array.
     *
     * @param  array  $packages
     * @return array
     */
    protected static function updatePackageArray(array $packages)
    {
        return [
            '@babel/preset-react' => '^7.0.0',
            'react' => '^16.2.0',
            'react-dom' => '^16.2.0',
        ] + Arr::except($packages, ['vue', 'vue-template-compiler']);
    }

    /**
     * Update the Webpack configuration.
     *
     * @return void
     */
    protected static function updateWebpackConfiguration()
    {
        copy(__DIR__.'/react-stubs/webpack.mix.js', base_path('webpack.mix.js'));
    }

    /**
     * Update the example component.
     *
     * @return void
     */
    protected static function updateComponent()
    {
        (new Filesystem)->delete(
            resource_path('js/components/ExampleComponent.vue')
        );

        copy(
            __DIR__.'/react-stubs/Example.js',
            resource_path('js/components/Example.js')
        );
    }

    /**
     * Update the bootstrapping files.
     *
     * @return void
     */
    protected static function updateBootstrapping()
    {
        copy(__DIR__.'/react-stubs/app.js', resource_path('js/app.js'));
    }
}


text: assert(Number.MIN_VALUE === 5e-324);


text:
@implementation ZKQueryResult

- (id)initFromXmlNode:(zkElement *)node {
	self = [super init];
	int i = 0;
	size = [[[node childElement:@"size"] stringValue] intValue];
	NSString * strDone = [[node childElement:@"done"] stringValue];
	done = [strDone isEqualToString:@"true"];
	if (done == NO)
		queryLocator = [[[node childElement:@"queryLocator"] stringValue] copy];

	NSArray * nodes = [node childElements:@"records"];
	NSMutableArray * recArray = [NSMutableArray arrayWithCapacity:[nodes count]];
	ZKSObject * o;
	for (i = 0; i < [nodes count]; i++)
	{
		zkElement * n = [nodes objectAtIndex:i];
		NSString *xsiNil = [n attributeValue:@"nil" ns:NS_URI_XSI];
		if (xsiNil != nil && [xsiNil isEqualToString:@"true"])
			continue;
		o = [[ZKSObject alloc] initFromXmlNode:n];
		[recArray addObject:o];
		[o release];
	}
	records = [recArray retain];
	return self;
}

- (id)initWithRecords:(NSArray *)r size:(int)s done:(BOOL)d queryLocator:(NSString *)ql {
	self = [super init];
	records = [r retain];
	done = d;
	size = s;
	queryLocator = [ql retain];
	return self;
}

- (id)copyWithZone:(NSZone *)zone {
	return [[ZKQueryResult alloc] initWithRecords:records size:size done:done queryLocator:queryLocator];
}

- (void)dealloc {
	[queryLocator release];
	[records release];
	[super dealloc];
}

- (int)size {
	return size;
}

- (BOOL)done {
	return done;
}

- (NSString *)queryLocator {
	return queryLocator;
}

- (NSArray *)records {
	return records;
}

@end


text:
var Goal = function () {
	var self = this;

	this.title = ko.observable("");
	this.description = ko.observable("");
	this.state = ko.observable(0);
	this.user = new User();
}


text:
[![Build Status](https://github.com/intellij-purescript/intellij-purescript/workflows/Gradle%20Check/badge.svg)](https://github.com/intellij-purescript/intellij-purescript/actions)
[![Publish Status](https://github.com/intellij-purescript/intellij-purescript/workflows/Publish/badge.svg)](https://github.com/intellij-purescript/intellij-purescript/actions)
[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)

![example](.README/ex1.png)

## Community

Visit discord http://purescript.org/chat and join the editors channel to ask for
help or to pair on issues and improve the plugin together,

### Dev

1. clone the repo
2. /gradlew runIde
    > starts a Intellij instance with the plugin installed-