text:
package com.qihoo360.replugin.component.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;

import com.qihoo360.loader2.MP;
import com.qihoo360.replugin.RePlugin;
import com.qihoo360.replugin.RePluginInternal;
import com.qihoo360.replugin.component.ComponentList;
import com.qihoo360.replugin.helper.LogDebug;
import com.qihoo360.replugin.model.PluginInfo;

import static com.qihoo360.replugin.helper.LogDebug.LOG;

/**
 * 根据需要来Inject一些Activity的特性,使其更像一个App中的Activity
 *
 * @author RePlugin Team
 */

public class ActivityInjector {

    public static final String TAG = "activity-injector";

    /**
     * 填充一些必要的东西到Activity中
     *
     * @param activity     Activity对象
     * @param plugin       插件名
     * @param realActivity 真实的(非坑位的)Activity名字
     * @return 是否Inject成功
     */
    public static boolean inject(Activity activity, String plugin, String realActivity) {
        // 根据传进的参数来获取ActivityInfo
        PluginInfo pi = MP.getPlugin(plugin, false);
        if (pi == null) {
            return false;
        }
        ComponentList cl = RePlugin.fetchComponentList(plugin);
        if (cl == null) {
            return false;
        }

        ActivityInfo ai = cl.getActivity(realActivity);
        return ai != null && inject(activity, ai, pi.getFrameworkVersion());
    }

    private static boolean inject(Activity activity, ActivityInfo ai, int frameworkVer) {
        // 可根据插件Activity的描述(android:label、android:icon)来设置Task在"最近应用程序"中的显示
        // 注意:框架版本需 >= 4,否则仍沿用Application的Label和Icon
        if (frameworkVer >= 4) {
            injectTaskDescription(activity, ai);
        }
        return true;
    }

    /**
     * 可根据插件Activity的描述(android:label、android:icon)来设置Task在"最近应用程序"中的显示

     * 注意:Android 4.x及以下暂不支持

     * Author: Jiongxuan Zhang
     */
    private static void injectTaskDescription(Activity activity, ActivityInfo ai) {
        // Android 4.x及以下暂不支持
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return;
        }

        if (activity == null || ai == null) {
            return;
        }

        if (LOG) {
            LogDebug.d(TAG, "activity = " + activity);
            LogDebug.d(TAG, "ai = " + ai);
        }

        // 获取 activity label
        String label = getLabel(activity, ai);
        // 如果获取 label 失败(可能性极小),则不修改 TaskDescription
        if (TextUtils.isEmpty(label)) {
            return;
        }

        // 获取 ICON
        Bitmap bitmap = getIcon(activity, ai);

        // FIXME color的透明度需要在Theme中的colorPrimary中获取,先不实现
        ActivityManager.TaskDescription td;
        if (bitmap != null) {
            td = new ActivityManager.TaskDescription(label, bitmap);
        } else {
            td = new ActivityManager.TaskDescription(label);
        }

        if (LOG) {
            LogDebug.d(TAG, "td = " + td);
        }

        activity.setTaskDescription(td);
    }

    /**
     * 获取 activity 的 label 属性
     */
    private static String getLabel(Activity activity, ActivityInfo ai) {
        String label;
        Resources res = activity.getResources();

        // 获取 Activity label(如有)
        label = getLabelById(res, ai.labelRes);

        // 获取插件 Application Label(如有)
        if (TextUtils.isEmpty(label)) {
            label = getLabelById(res, ai.applicationInfo.labelRes);
        }

        // 获取宿主 App label
        if (TextUtils.isEmpty(label)) {
            Context appContext = RePluginInternal.getAppContext();
            Resources appResource = appContext.getResources();
            ApplicationInfo appInfo = appContext.getApplicationInfo();
            label = getLabelById(appResource, appInfo.labelRes);
        }

        if (LOG) {
            LogDebug.d(TAG, "label = " + label);
        }
        return label;
    }

    private static String getLabelById(Resources res, int id) {
        if (id == 0) {
            return null;
        }
        try {
            return res.getString(id);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取 activity 的 icon 属性
     */
    private static Bitmap getIcon(Activity activity, ActivityInfo ai) {
        Drawable iconDrawable;
        Resources res = activity.getResources();

        // 获取 Activity icon
        iconDrawable = getIconById(res, ai.icon);

        // 获取插件 Application Icon
        if (iconDrawable == null) {
            iconDrawable = getIconById(res, ai.applicationInfo.icon);
        }

        // 获取 App(Host) Icon
        if (iconDrawable == null) {
            Context appContext = RePluginInternal.getAppContext();
            Resources appResource = appContext.getResources();
            ApplicationInfo appInfo = appContext.getApplicationInfo();
            iconDrawable = getIconById(appResource, appInfo.icon);
        }

        Bitmap bitmap = null;
        if (iconDrawable instanceof BitmapDrawable) {
            bitmap = ((BitmapDrawable) iconDrawable).getBitmap();
        }

        if (LOG) {
            LogDebug.d(TAG, "bitmap = " + bitmap);
        }
        return bitmap;
    }

    private static Drawable getIconById(Resources res, int id) {
        if (id == 0) {
            return null;
        }
        try {
            return res.getDrawable(id);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}


text:
#ifndef SIDECAR_GUI_CONFIGEDITOR_MAINWINDOW_H // -*- C++ -*-
#define SIDECAR_GUI_CONFIGEDITOR_MAINWINDOW_H

#include "GUI/MainWindowBase.h"

#include "App.h"

namespace Ui {
class MainWindow;
}

namespace SideCar {
namespace GUI {
namespace ConfigEditor {

class TreeModel;

class MainWindow : public MainWindowBase {
    Q_OBJECT
    using Super = MainWindowBase;

public:
    /** Constructor.
     */
    MainWindow();

    /** Obtain the App object singleton.

        \return App object
    */
    App* getApp() const { return App::GetApp(); }

private:
    Ui::MainWindow* gui_;
    TreeModel* model_;
};

} // end namespace ConfigEditor
} // end namespace GUI
} // end namespace SideCar

/** \file
 */

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php
/*
*   Bind common core class functions to standalone functions
*/
namespace APDL {
    function setvar($var, $val) {
        APDL::Setvar($var, $val, false);
    }

    function sysvar($var) {
        return APDL::Sysvar($var, false);
    }

    function log($message, $level = Log::L_DEBUG, $errorcode = 0) {
        Log::log($message, $level, $errorcode);
    }

    function set_codetracker($s) {
        APDL::$CTRACK = $s;
    }

    function set_logging($l) {
        APDL::$LOGLEVEL = $l;
    }

    function apdl_die() {
        APDL::die_on_fatal();
    }

    function dump_log_to_session() {
        Log::dump_to_session();
    }

    function runtime() {
        return APDL::runtime();
    }

    function internal_url($path) {
        return ROUTING::internal_url($path);
    }

    function webpath($localpath, $protocol = "http") {
        return HTTP::webpath($localpath, $protocol);
    }

    function db_connect($conn, $name = "default", $die_on_fault = true) {
        CONNECTION_MANAGER::connect($conn, $name, $die_on_fault);
    }

    function db_get_conn($name) {
        return CONNECTION_MANAGER::get_conn($name);
    }

    function db_set_active($name) {
        return CONNECTION_MANAGER::set_active($name);
    }

    function db_get_active() {
        return CONNECTION_MANAGER::get_active();
    }

    function register_encoder($name, $class) {
        $encoders = APDL::Sysvar("__encoders", APDL_INTERNALCALL);
        if (!is_array($encoders)) {
            $encoders = array();
        }
        $encoders[$name] = new $class;
        APDL::Setvar("__encoders", $encoders, APDL_INTERNALCALL);
        log("Encoder $class registered", L_INFO);
    }

    function get_encoder($name) {
        $encoders = sysvar("__encoders");
        if (!isset($encoders[$name]) || !is_object($encoders[$name])) {
            log("Requesting invalid encoder!", L_FATAL);
        }
        return $encoders[$name];
    }

    function load_module($mod, $mbv = 0) {
        MODULESTORE::load_module($mod, $mbv);
    }

}


text:
package com.joy.http;

/**
 * Created by Daisw on 2017/5/25.
 */

public class JoyError extends Exception {

    /**
     * 错误类型:区别于statusCode,用来标识当前错误的类型(接口定义的错误、HTTP错误)。
     */
    public static final int TYPE_NONE = 0;
    public static final int TYPE_HTTP = 1;
    public static final int TYPE_SERVER_DEFINED = 2;
    private int mType = TYPE_NONE;

    /**
     * 状态码:HTTP状态码(4xx、5xx等);服务器定义的状态码用来标识Token失效、参数错误等。
     * 需要用type来区分。
     */
    private int mStatusCode;

    public JoyError() {
        super();
    }

    public JoyError(int type, int statusCode, String message) {
        super(message);
        mType = type;
        mStatusCode = statusCode;
    }

    public JoyError(int type, int statusCode) {
        this(type, statusCode, "");
    }

    public JoyError(int type, int statusCode, Throwable cause) {
        super(cause);
        mType = type;
        mStatusCode = statusCode;
    }

    public JoyError(String message) {
        super(message);
    }

    public JoyError(String message, Throwable cause) {
        super(message, cause);
    }

    public JoyError(Throwable cause) {
        super(cause);
    }

    public int getType() {
        return mType;
    }

    public int getStatusCode() {
        return mStatusCode;
    }

    public boolean isHttpError() {
        return mType == TYPE_HTTP;
    }

    public boolean isServerDefinedError() {
        return mType == TYPE_SERVER_DEFINED;
    }

    private boolean isCancelCaused;

    public void setCancelCaused(boolean cancelCaused) {
        isCancelCaused = cancelCaused;
    }

    public boolean isCancelCaused() {
        return isCancelCaused;
    }

    @Override
    public String toString() {
        return "JoyError{" +
                "type=" + mType +
                ", statusCode=" + mStatusCode +
                ", msg=" + getMessage() +
                ", isCancelCaused=" + isCancelCaused +
                '}';
    }
}


text:
"""
Image Output
"""
import cv2
from core.component import Component
from components.log_server import LogLevel

class ImgOutput(Component):
    """
    Class for ImgOutput
    """
    def __init__(self, options):
        super(ImgOutput, self).__init__(options)
        self.input_observer = ImgOutput.InputObserver(self)
        self.__file_path = ""
        self.file_path = self.properties['file_path']

    @property
    def file_path(self):
        """
        getter of file_path
        """
        return self.__file_path

    @file_path.setter
    def file_path(self, value):
        self.__file_path = value

    @staticmethod
    def get_parameters():
        """
        return all parameters of the component
        """
        for key, value in ImgOutput.__dict__.items():
            if isinstance(value, property):
                print(key)

    class InputObserver(Component.InputObserver):
        """
        Class for observers
        """
        def update(self, observable, package):
            self.outer.log_line('save file')
            cv2.imwrite(self.outer.file_path, package['data'])
            self.outer.log_line('saved file', LogLevel.SUCCESS)
            self.outer.send({'status': 'stopped'})


text:
<?php

namespace AppBundle\Manager;
use AppBundle\Manager\BaseManager;

/**
 * Description of EpreuveManager
 *
 * @author Giraud
 */
class EpreuveManager extends BaseManager
{
    public function getEntityName()
    {
        return 'AppBundle:Epreuve';
    }
}


text:
package main

import (
	"flag"
	"fmt"
	"log"

	"github.com/brnstz/routine/wikimg"
)

var (
	// Print a blank line with the given 256 ANSI color
	fmtSpec = "\x1b[30;48;5;%dm%-80s\x1b[0m\n"
)

func main() {
	var max int

	flag.IntVar(&max, "max", 100, "maximum number of images to retrieve")
	flag.Parse()

	// Create a new image puller with our max
	p := wikimg.NewPuller(max)

	// Loop to retrieve more images
	for {
		imgURL, err := p.Next()

		if err == wikimg.EndOfResults {
			// Break from loop when end of results is reached
			break

		} else if err != nil {
			// Log error and continue getting URLs
			log.Println(err)
			continue
		}

		// Everybody gets a goroutine!
		go func() {
			// Get the first color in this image
			color, _, err := p.FirstColor(imgURL)
			if err != nil {
				log.Println(err)
				return
			}

			// Print color to the terminal
			fmt.Printf(fmtSpec, color, "")
		}()
	}
}


text:
package reaktor.scct.report

import java.io.File
import xml.NodeSeq
import reaktor.scct.IO

class HtmlReportWriter(outputDir: File) {

  def write(fileName: String, nodes: NodeSeq) {
    write(fileName, nodes.toString)
  }
  def write(fileName: String, content: String) {
    write(fileName, content.getBytes("utf-8"))
  }
  def write(fileName: String, bytes: Array[Byte]) {
    val file = new File(outputDir, fileName)
    val parent = file.getParentFile
    if (!parent.exists) parent.mkdirs
    IO.write(file, bytes)
  }
}


text:
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, evil:true */
/*global window, document */

/**
 * Check for missing dependencies
 */
window.setTimeout(function () {
    "use strict";

    var key, missingDeps = "";
    var deps = { "Mustache": window.Mustache, "jQuery": window.$, "RequireJS": window.require };

    for (key in deps) {
        if (deps.hasOwnProperty(key) && !deps[key]) {
            missingDeps += "
" + key + "
";
        }
    }

    if (missingDeps.length > 0) {
        var str = "
Missing libraries
" +
                  "
Oops! One or more required libraries could not be found.
" +
                  "
" + missingDeps + "
" +
                  "
If you're running from a local copy of the Brackets source, please make sure submodules are updated by running:
" +
                  "
git submodule update --init
" +
                  "
If you're still having problems, please contact us via one of the channels mentioned at the bottom of the README.
" +
                  "
Reload Brackets
";

        document.write(str);
    }
}, 1000);


text:
package androidx.core.view;

import android.view.View;
import android.view.Window;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;

/**
 * Helper for accessing features in {@link Window}.
 */
public final class WindowCompat {
    /**
     * Flag for enabling the Action Bar.
     * This is enabled by default for some devices. The Action Bar
     * replaces the title bar and provides an alternate location
     * for an on-screen menu button on some devices.
     */
    public static final int FEATURE_ACTION_BAR = 8;

    /**
     * Flag for requesting an Action Bar that overlays window content.
     * Normally an Action Bar will sit in the space above window content, but if this
     * feature is requested along with {@link #FEATURE_ACTION_BAR} it will be layered over
     * the window content itself. This is useful if you would like your app to have more control
     * over how the Action Bar is displayed, such as letting application content scroll beneath
     * an Action Bar with a transparent background or otherwise displaying a transparent/translucent
     * Action Bar over application content.
     *
     *
This mode is especially useful with {@link View#SYSTEM_UI_FLAG_FULLSCREEN
     * View.SYSTEM_UI_FLAG_FULLSCREEN}, which allows you to seamlessly hide the
     * action bar in conjunction with other screen decorations.
     *
     *
As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}, when an
     * ActionBar is in this mode it will adjust the insets provided to
     * {@link View#fitSystemWindows(android.graphics.Rect) View.fitSystemWindows(Rect)}
     * to include the content covered by the action bar, so you can do layout within
     * that space.
     */
    public static final int FEATURE_ACTION_BAR_OVERLAY = 9;

    /**
     * Flag for specifying the behavior of action modes when an Action Bar is not present.
     * If overlay is enabled, the action mode UI will be allowed to cover existing window content.
     */
    public static final int FEATURE_ACTION_MODE_OVERLAY = 10;

    private WindowCompat() {}

    /**
     * Finds a view that was identified by the {@code android:id} XML attribute
     * that was processed in {@link android.app.Activity#onCreate}, or throws an
     * IllegalArgumentException if the ID is invalid, or there is no matching view in the hierarchy.
     *

     * Note: In most cases -- depending on compiler support --
     * the resulting view is automatically cast to the target class type. If
     * the target class type is unconstrained, an explicit cast may be
     * necessary.
     *
     * @param id the ID to search for
     * @return a view with given ID
     * @see ViewCompat#requireViewById(View, int)
     * @see Window#findViewById(int)
     */
    @SuppressWarnings("TypeParameterUnusedInFormals")
    @NonNull
    public static <T extends View> T requireViewById(@NonNull Window window, @IdRes int id) {
        // TODO: use and link to Window#requireViewById() directly, once available
        T view = window.findViewById(id);
        if (view == null) {
            throw new IllegalArgumentException("ID does not reference a View inside this Window");
        }
        return view;
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;

namespace Soomla.Profile
{
	public class GetLeaderboardsFailedEvent : BaseSocialActionEvent
	{
		public readonly string ErrorDescription;

		public GetLeaderboardsFailedEvent(Provider provider, string errorDescription, string payload) : base(provider, payload) {
			this.ErrorDescription = errorDescription;
		}
	}
}


text:
/*
 * =====================================================================================
 *
 *       Filename:  TGM_GetOpt.h
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  04/17/2012 12:24:18 AM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Jiantao Wu (),
 *        Company:
 *
 * =====================================================================================
 */
#ifndef  TGM_GETOPT_H
#define  TGM_GETOPT_H

#include <stdio.h>
#include "TGM_Types.h"

// an object hold the options parsed from command line arguments
typedef struct TGM_Option
{
    const char* name;    // name of this option, following a '-' character in the command line

    const char* value;   // a pointer points to the value of the option in the argv array

    TGM_Bool isFound;    // boolean variable to indicate that if we fount this option or not

}TGM_Option;

#ifdef __cplusplus
extern "C" {
#endif	// __cplusplus

// get the options from command line arguemnts
int TGM_GetOpt(TGM_Option opts[], int argc, const char* argv[]);

#ifdef __cplusplus
}
#endif	// __cplusplus

#endif  /*TGM_GETOPT_H*/


text:
from nose.tools import eq_, ok_, raises
import pods
import os
import re
import sys

if sys.version_info >= (3, 0):
    from urllib.error import HTTPError, URLError
else:
    from urllib2 import URLError as HTTPError
    from urllib2 import URLError

# details of a test page
test_url = "http://www.bbc.co.uk/"
store_directory = "tmp"
save_name = "bbc_website.html"
title = "<title data-rh=\"true\">BBC - Home</title>"

# details of a non existent page
fake_url = "http://pandemonium.sinclair.spectrum.absolute.blast.google.gobsmackazedare.co.uk/index.html"

bogus_file = "http://www.bbc.co.uk/bogus_file.html"

def test_downloard_url():
    """util_tests: Test downloading of a URL."""

    pods.util.download_url(
        test_url, save_name=save_name, store_directory=store_directory
    )
    filename = os.path.join(store_directory, save_name)

    ok_(os.path.isfile(filename), "File does not exist in suggested location.")
    file = open(filename, "r")

    found_title = False
    for line in file:
        if re.search(title, line):
            found_title = True
    ok_(
        found_title,
        "Could not find " + title + " in " + filename + " downloaded from " + test_url,
    )

@raises(URLError, ValueError)
def test_graceful_failure_fake_url():
    """util_tests: Test graceful failure of a fake url."""
    pods.util.download_url(fake_url)

@raises(HTTPError, ValueError)
def test_graceful_failure_bogus_file():
    """util_tests: Test graceful failure of a bogus file."""
    pods.util.download_url(bogus_file)

import filecmp
import unittest

class UtilTests(unittest.TestCase):
    def test_download_url(self):
        """util_tests: Test the download url"""
        filename = "util.py"
        download_name = "tmp.py"
        # Download the file to current directory
        pods.util.download_url(
            "https://raw.githubusercontent.com/sods/ods/master/pods/" + filename,
            dir_name=".",
            save_name=download_name,
        )
        # Get path of original module
        path = os.path.dirname(pods.__file__)
        # Compare files
        self.assertTrue(filecmp.cmp(os.path.join(path, filename), download_name))


text:
package net

import (
	"context"
	"runtime"
	"syscall"
)

func probeIPv4Stack() bool {
	s, err := socketFunc(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
	switch err {
	case syscall.EAFNOSUPPORT, syscall.EPROTONOSUPPORT:
		return false
	case nil:
		closeFunc(s)
	}
	return true
}

// Should we try to use the IPv4 socket interface if we're
// only dealing with IPv4 sockets?  As long as the host system
// understands IPv6, it's okay to pass IPv4 addresses to the IPv6
// interface. That simplifies our code and is most general.
// Unfortunately, we need to run on kernels built without IPv6
// support too. So probe the kernel to figure it out.
//
// probeIPv6Stack probes both basic IPv6 capability and IPv6 IPv4-
// mapping capability which is controlled by IPV6_V6ONLY socket
// option and/or kernel state "net.inet6.ip6.v6only".
// It returns two boolean values. If the first boolean value is
// true, kernel supports basic IPv6 functionality. If the second
// boolean value is true, kernel supports IPv6 IPv4-mapping.
func probeIPv6Stack() (supportsIPv6, supportsIPv4map bool) {
	var probes = []struct {
		laddr TCPAddr
		value int
	}{
		// IPv6 communication capability
		{laddr: TCPAddr{IP: ParseIP("::1")}, value: 1},
		// IPv4-mapped IPv6 address communication capability
		{laddr: TCPAddr{IP: IPv4(127, 0, 0, 1)}, value: 0},
	}
	var supps [2]bool
	switch runtime.GOOS {
	case "dragonfly", "openbsd":
		// Some released versions of DragonFly BSD pretend to
		// accept IPV6_V6ONLY=0 successfully, but the state
		// still stays IPV6_V6ONLY=1. Eventually DragonFly BSD
		// stops pretending, but the transition period would
		// cause unpredictable behavior and we need to avoid
		// it.
		//
		// OpenBSD also doesn't support IPV6_V6ONLY=0 but it
		// never pretends to accept IPV6_V6OLY=0. It always
		// returns an error and we don't need to probe the
		// capability.
		probes = probes[:1]
	}

	for i := range probes {
		s, err := socketFunc(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
		if err != nil {
			continue
		}
		defer closeFunc(s)
		syscall.SetsockoptInt(s, syscall.IPPROTO_IPV6, syscall.IPV6_V6ONLY, probes[i].value)
		sa, err := probes[i].laddr.sockaddr(syscall.AF_INET6)
		if err != nil {
			continue
		}
		if err := syscall.Bind(s, sa); err != nil {
			continue
		}
		supps[i] = true
	}

	return supps[0], supps[1]
}

// favoriteAddrFamily returns the appropriate address family to
// the given net, laddr, raddr and mode. At first it figures
// address family out from the net. If mode indicates "listen"
// and laddr is a wildcard, it assumes that the user wants to
// make a passive connection with a wildcard address family, both
// AF_INET and AF_INET6, and a wildcard address like following:
//
//	1. A wild-wild listen, "tcp" + ""
//	If the platform supports both IPv6 and IPv6 IPv4-mapping
//	capabilities, or does not support IPv4, we assume that
//	the user wants to listen on both IPv4 and IPv6 wildcard
//	addresses over an AF_INET6 socket with IPV6_V6ONLY=0.
//	Otherwise we prefer an IPv4 wildcard address listen over
//	an AF_INET socket.
//
//	2. A wild-ipv4wild listen, "tcp" + "0.0.0.0"
//	Same as 1.
//
//	3. A wild-ipv6wild listen, "tcp" + "[::]"
//	Almost same as 1 but we prefer an IPv6 wildcard address
//	listen over an AF_INET6 socket with IPV6_V6ONLY=0 when
//	the platform supports IPv6 capability but not IPv6 IPv4-
//	mapping capability.
//
//	4. A ipv4-ipv4wild listen, "tcp4" + "" or "0.0.0.0"
//	We use an IPv4 (AF_INET) wildcard address listen.
//
//	5. A ipv6-ipv6wild listen, "tcp6" + "" or "[::]"
//	We use an IPv6 (AF_INET6, IPV6_V6ONLY=1) wildcard address
//	listen.
//
// Otherwise guess: if the addresses are IPv4 then returns AF_INET,
// or else returns AF_INET6.  It also returns a boolean value what
// designates IPV6_V6ONLY option.
//
// Note that OpenBSD allows neither "net.inet6.ip6.v6only=1" change
// nor IPPROTO_IPV6 level IPV6_V6ONLY socket option setting.
func favoriteAddrFamily(net string, laddr, raddr sockaddr, mode string) (family int, ipv6only bool) {
	switch net[len(net)-1] {
	case '4':
		return syscall.AF_INET, false
	case '6':
		return syscall.AF_INET6, true
	}

	if mode == "listen" && (laddr == nil || laddr.isWildcard()) {
		if supportsIPv4map || !supportsIPv4 {
			return syscall.AF_INET6, false
		}
		if laddr == nil {
			return syscall.AF_INET, false
		}
		return laddr.family(), false
	}

	if (laddr == nil || laddr.family() == syscall.AF_INET) &&
		(raddr == nil || raddr.family() == syscall.AF_INET) {
		return syscall.AF_INET, false
	}
	return syscall.AF_INET6, false
}

// Internet sockets (TCP, UDP, IP)
func internetSocket(ctx context.Context, net string, laddr, raddr sockaddr, sotype, proto int, mode string) (fd *netFD, err error) {
	if (runtime.GOOS == "windows" || runtime.GOOS == "openbsd" || runtime.GOOS == "nacl") && mode == "dial" && raddr.isWildcard() {
		raddr = raddr.toLocal(net)
	}
	family, ipv6only := favoriteAddrFamily(net, laddr, raddr, mode)
	return socket(ctx, net, family, sotype, proto, ipv6only, laddr, raddr)
}

func ipToSockaddr(family int, ip IP, port int, zone string) (syscall.Sockaddr, error) {
	switch family {
	case syscall.AF_INET:
		if len(ip) == 0 {
			ip = IPv4zero
		}
		ip4 := ip.To4()
		if ip4 == nil {
			return nil, &AddrError{Err: "non-IPv4 address", Addr: ip.String()}
		}
		sa := &syscall.SockaddrInet4{Port: port}
		copy(sa.Addr[:], ip4)
		return sa, nil
	case syscall.AF_INET6:
		// In general, an IP wildcard address, which is either
		// "0.0.0.0" or "::", means the entire IP addressing
		// space. For some historical reason, it is used to
		// specify "any available address" on some operations
		// of IP node.
		//
		// When the IP node supports IPv4-mapped IPv6 address,
		// we allow an listener to listen to the wildcard
		// address of both IP addressing spaces by specifying
		// IPv6 wildcard address.
		if len(ip) == 0 || ip.Equal(IPv4zero) {
			ip = IPv6zero
		}
		// We accept any IPv6 address including IPv4-mapped
		// IPv6 address.
		ip6 := ip.To16()
		if ip6 == nil {
			return nil, &AddrError{Err: "non-IPv6 address", Addr: ip.String()}
		}
		sa := &syscall.SockaddrInet6{Port: port, ZoneId: uint32(zoneToInt(zone))}
		copy(sa.Addr[:], ip6)
		return sa, nil
	}
	return nil, &AddrError{Err: "invalid address family", Addr: ip.String()}
}


text:
require 'chefspec'
require 'chefspec/berkshelf'

describe 'nsupdate::default' do
  let(:chef_run) { ChefSpec::Runner.new.converge 'nsupdate' }

  it 'installs dnsutils' do
    expect(chef_run).to install_package('dnsutils')
  end
end


text:
require 'cdo/hip_chat'

class FeatureModeManager

  # A map from mode symbol to gatekeeper and dcdo settings. The gatekeeper settings are
  # broken down into gatekeeper_general_settings (which apply to all tutorials) and
  # gatekeeper_hoc_tutorial_settings (which apply to high-scale HOC tutorials only).
  MODE_SETTINGS_MAP = {
    normal: {
        gatekeeper_general_settings: {
          puzzle_rating: true,
          hint_view_request: true,
          postMilestone: true,
          shareEnabled: true,
          slogging: true
        },
        gatekeeper_hoc_tutorial_settings: {
          postMilestone: true,
          shareEnabled: true,
        },
        dcdo_settings: {
          hoc_activity_sample_weight: 1,
          public_proxy_max_age: 3.minutes.to_i,
          public_max_age: 6.minutes.to_i,
        }
    },
    scale: {
      gatekeeper_general_settings: {
        puzzle_rating: false,
        hint_view_request: false,
        postMilestone: true,
        shareEnabled: true,
        slogging: false
      },
      gatekeeper_hoc_tutorial_settings: {
        postMilestone: false,
        shareEnabled: true,
      },
      dcdo_settings: {
        hoc_activity_sample_weight: 10,
        public_proxy_max_age: 4.hours.to_i,
        public_max_age: 8.hours.to_i,
      }
    },
    emergency: {
      gatekeeper_general_settings: {
        puzzle_rating: false,
        hint_view_request: false,
        postMilestone: false,
        shareEnabled: false,
        slogging: false
      },
      gatekeeper_hoc_tutorial_settings: {
        postMilestone: false,
        shareEnabled: false,
      },
      dcdo_settings: {
        hoc_activity_sample_weight: 10,
        public_proxy_max_age: 24.hours.to_i,
        public_max_age: 48.hours.to_i,
      }
    }
  }.with_indifferent_access

  # An array of supported feature mode names.
  MODES = MODE_SETTINGS_MAP.keys

  # Updates the feature mode to the given mode.
  def self.set_mode(mode, gatekeeper, dcdo, hoc_script_names)
    settings = MODE_SETTINGS_MAP[mode]
    raise "Invalid mode '#{mode}'" if settings.nil?

    settings[:dcdo_settings].each do |key, value|
      dcdo.set(key, value)
    end

    settings[:gatekeeper_general_settings].each do |feature, value|
      gatekeeper.set(feature,  value: value)
    end

    settings[:gatekeeper_hoc_tutorial_settings].each do |feature, value|
      hoc_script_names.each do |script_name|
        gatekeeper.set(feature,  where: {script_name: script_name}, value: value)
      end
    end

    HipChat.log "Set scale feature mode for environment #{Rails.env} to #{mode}"
  end

  # Returns the matching mode if the dcdo and gatekeeper settings match
  # a predefined mode for all of the specified HOC script names, or nil otherwise.
  def self.get_mode(gatekeeper, dcdo, hoc_script_names)
    MODES.detect do |mode|
      dcdo_matches_mode?(dcdo, mode) &&
        gatekeeper_general_settings_match_mode?(gatekeeper, mode) &&
        gatekeeper_hoc_tutorials_match_mode?(gatekeeper, mode, hoc_script_names)
    end
  end

  # Returns true if the feature mode manager allows the `feature` in `mode` for hoc tutorial
  # `script`, falling through to the value from the Gatekeeper if the manager doesn't
  # specify a value.  (If script is nil, only considers general settings.)
  def self.allows(gatekeeper, mode, feature, script)
    # Use the value from the mode settings map, if defined.
    settings = MODE_SETTINGS_MAP[mode]
    if settings
      allowed = settings[:gatekeeper_hoc_tutorial_settings][feature] if script
      allowed = settings[:gatekeeper_general_settings][feature] if allowed.nil?
      return allowed unless allowed.nil?
    end

    # Otherwise use the value from the Gatekeeper.
    gatekeeper.allows(feature, where: (script ? {script_name: script} : {}))
  end

  def self.dcdo_matches_mode?(dcdo, mode)
    expected_settings = MODE_SETTINGS_MAP[mode][:dcdo_settings]
    expected_settings.all? do |key, expected_value|
      expected_value == dcdo.get(key, nil)
    end
  end

  def self.gatekeeper_general_settings_match_mode?(gatekeeper, mode)
    expected_settings = MODE_SETTINGS_MAP[mode][:gatekeeper_general_settings]
    expected_settings.all? do |feature, expected_value|
      expected_value == gatekeeper.allows(feature)
    end
  end

  def self.gatekeeper_hoc_tutorials_match_mode?(gatekeeper, mode, hoc_script_names)
    expected_settings = MODE_SETTINGS_MAP[mode][:gatekeeper_hoc_tutorial_settings]
    expected_settings.all? do |feature, expected_value|
      hoc_script_names.all? do |script|
        expected_value == gatekeeper.allows(feature, where: {script_name: script})
      end
    end
  end

end


text:
"""Tests for the Optimization module."""
import doctest
import collections
import functools
import math
import unittest

from arxpy.bitvector.operation import Concat, BvComp

from arxpy.primitives.primitives import BvFunction, Cipher

from arxpy.differential.difference import XorDiff, RXDiff
from arxpy.differential.characteristic import (
    BvCharacteristic, SingleKeyCh, RelatedKeyCh
)

import arxpy.smt.search_differential
from arxpy.smt.search_differential import (
    SearchCh, SearchSkCh, SearchRkCh, DerMode, ChSearchMode, SkChSearchMode, RkChSearchMode, _get_smart_print
)

from arxpy.differential.tests.test_characteristic import (
    MyFunction, Cipher1, Cipher2
)

VERBOSE_LEVEL = 0
# 0: quiet
# 1: basic info
# 2: + ssa, model
# 3: + hrepr
# 4: + full hrepr

ChOption = collections.namedtuple('ChOptions', ['der_mode', 'search_mode'])
SkChOption = collections.namedtuple('SingleKeyOptions', ['der_mode', 'search_mode'])
RkChOption = collections.namedtuple('RelatedKeyOptions', ['key_der_mode', 'enc_der_mode',
                                                          'search_mode', 'initial_ew', 'initial_kw'])

CH_OPTIONS = [
    ChOption(DerMode.ProbabilityOne, ChSearchMode.Optimal),
    ChOption(DerMode.XDCA_Approx, ChSearchMode.FirstCh),
    ChOption(DerMode.Default, ChSearchMode.Optimal),
    ChOption(DerMode.Default, ChSearchMode.OptimalDifferential),
]

SKCH_OPTIONS = [
    SkChOption(DerMode.ProbabilityOne, SkChSearchMode.Optimal),
    SkChOption(DerMode.XDCA_Approx, SkChSearchMode.FirstCh),
    SkChOption(DerMode.Default, SkChSearchMode.Optimal),
    SkChOption(DerMode.Default, SkChSearchMode.OptimalDifferential),
]

RKCH_OPTIONS = [
    RkChOption(DerMode.ProbabilityOne, DerMode.ProbabilityOne, RkChSearchMode.OptimalMinSum, 0, 0),
    RkChOption(DerMode.ProbabilityOne, DerMode.ProbabilityOne, RkChSearchMode.OptimalMinSumDifferential, 0, 0),
    RkChOption(DerMode.Default, DerMode.Default, RkChSearchMode.FirstMinSum, 0, 0),
    RkChOption(DerMode.ProbabilityOne, DerMode.Default, RkChSearchMode.FirstValidKeyMinEnc, 0, 0),
    RkChOption(DerMode.Default, DerMode.Default, RkChSearchMode.OptimalFixEncMinKey, 1, 0),
]

def test_search_ch_skch(bvf_cipher, diff_type, initial_weight, solver_name, rounds, der_mode, search_mode, check,
                        verbose_level, filename):
    smart_print = _get_smart_print(filename)

    if rounds is not None:
        bvf_cipher.set_rounds(rounds)

    if issubclass(bvf_cipher, BvFunction):
        num_inputs = len(bvf_cipher.input_widths)
        input_diff_names = ["dp" + str(i) for i in range(num_inputs)]
        ch = BvCharacteristic(bvf_cipher, diff_type, input_diff_names)
    else:
        assert issubclass(bvf_cipher, Cipher)
        ch = SingleKeyCh(bvf_cipher, diff_type)

    if verbose_level >= 1:
        str_rounds = "" if rounds is None else "{} rounds".format(rounds)
        smart_print(str_rounds, bvf_cipher.__name__, diff_type.__name__, type(ch).__name__)
        if verbose_level >= 2:
            smart_print("Characteristic:")
            smart_print(ch)

    if issubclass(bvf_cipher, BvFunction):
        problem = SearchCh(ch, der_mode=der_mode)
    else:
        problem = SearchSkCh(ch, der_mode=der_mode)

    if verbose_level >= 1:
        smart_print(type(problem).__name__, der_mode, search_mode, solver_name,
                    "size:", problem.formula_size())
        if verbose_level >= 2:
            smart_print(problem.hrepr(verbose_level >= 3))

    sol = problem.solve(initial_weight,
                        solver_name=solver_name,
                        search_mode=search_mode,
                        check=check,
                        verbose_level=verbose_level,
                        filename=filename)

    if verbose_level >= 1:
        if sol is None:
            smart_print("\nUnsatisfiable")
        else:
            smart_print("\nSolution:")
            smart_print(sol)
            if verbose_level >= 2:
                if isinstance(sol, collections.abc.Sequence):
                    # for search_mode TopDifferentials
                    smart_print(sol[0].vrepr())
                else:
                    smart_print(sol.vrepr())
        smart_print()

    return sol

def test_search_related_key_ch(cipher, diff_type, initial_ew, initial_kw, solver_name,
                               rounds, key_der_mode, enc_der_mode, allow_zero_enc_input_diff,
                               search_mode, check, verbose_level, filename):
    # assert search_mode != RkChSearchMode.AllValid

    smart_print = _get_smart_print(filename)

    if rounds is not None:
        cipher.set_rounds(rounds)

    ch = RelatedKeyCh(cipher, diff_type)

    if verbose_level >= 1:
        smart_print(rounds, "round(s)", cipher.__name__, diff_type.__name__, type(ch).__name__)
        if verbose_level >= 2:
            smart_print("Characteristic:")
            smart_print(ch)

    problem = SearchRkCh(rkch=ch, key_der_mode=key_der_mode, enc_der_mode=enc_der_mode,
                         allow_zero_enc_input_diff=allow_zero_enc_input_diff)

    if verbose_level >= 1:
        smart_print(type(problem).__name__, "key/enc mode:", key_der_mode, enc_der_mode,
                    search_mode, solver_name, "size:", problem.formula_size())
        if verbose_level >= 2:
            smart_print(problem.hrepr(verbose_level >= 3))

    sol = problem.solve(
        initial_ew=initial_ew,
        initial_kw=initial_kw,
        solver_name=solver_name,
        search_mode=search_mode,
        check=check,
        verbose_level=verbose_level,
        filename=filename)

    if verbose_level >= 1:
        if sol is None:
            smart_print("\nUnsatisfiable")
        else:
            smart_print("\nSolution:")
            smart_print(sol)
            if verbose_level >= 2:
                smart_print(sol.vrepr())
        smart_print()

    return sol

class TestSMT(unittest.TestCase):
    """Tests of the SMT classes."""

    def test_SearchCh(self):
        for diff_type in [XorDiff, RXDiff]:
            for bv_function in [MyFunction]:
                for option in CH_OPTIONS:
                    btor_ch_found = test_search_ch_skch(
                        bvf_cipher=bv_function,
                        diff_type=diff_type,
                        initial_weight=0,
                        solver_name="btor",
                        rounds=None,
                        der_mode=option.der_mode,
                        search_mode=option.search_mode,
                        check=True,
                        verbose_level=VERBOSE_LEVEL,
                        filename=None
                    )

                    if btor_ch_found is not None:
                        btor_weight = int(btor_ch_found.ch_weight)
                        btor_id = [value.val for var, value in btor_ch_found.input_diff]
                        self.assertFalse(BvComp(functools.reduce(Concat, btor_id), 0))
                    else:
                        btor_weight = math.inf

                    if diff_type == XorDiff:
                        self.assertEqual(0, btor_weight)
                    elif diff_type == RXDiff:
                        if option.der_mode == DerMode.ProbabilityOne:
                            self.assertEqual(math.inf, btor_weight)
                        else:
                            self.assertLessEqual(1, btor_weight)
                            self.assertLessEqual(btor_weight, 3)

                    yices_ch_found = test_search_ch_skch(
                        bvf_cipher=bv_function,
                        diff_type=diff_type,
                        initial_weight=0,
                        solver_name="yices",
                        rounds=None,
                        der_mode=option.der_mode,
                        search_mode=option.search_mode,
                        check=True,
                        verbose_level=1 if VERBOSE_LEVEL >= 2 else 0,
                        filename=None
                    )

                    if yices_ch_found is not None:
                        yices_weight = int(yices_ch_found.ch_weight)
                        yices_id = [value.val for var, value in yices_ch_found.input_diff]
                        self.assertFalse(BvComp(functools.reduce(Concat, yices_id), 0))
                    else:
                        yices_weight = math.inf

                    self.assertEqual(btor_weight, yices_weight)

    def test_SearchSkCh(self):
        diff_type = XorDiff

        for cipher in [Cipher1, Cipher2]:
            cipher.set_rounds(1)
            for option in SKCH_OPTIONS:
                btor_ch_found = test_search_ch_skch(
                    bvf_cipher=cipher,
                    diff_type=diff_type,
                    initial_weight=0,
                    solver_name="btor",
                    rounds=1,
                    der_mode=option.der_mode,
                    search_mode=option.search_mode,
                    check=True,
                    verbose_level=VERBOSE_LEVEL,
                    filename=None
                )

                if btor_ch_found is not None:
                    btor_weight = int(btor_ch_found.ch_weight)
                    btor_id = [value.val for var, value in btor_ch_found.input_diff]
                    self.assertFalse(BvComp(functools.reduce(Concat, btor_id), 0))
                else:
                    btor_weight = math.inf

                self.assertEqual(0, btor_weight)

                yices_ch_found = test_search_ch_skch(
                    bvf_cipher=cipher,
                    diff_type=diff_type,
                    initial_weight=0,
                    solver_name="yices",
                    rounds=1,
                    der_mode=option.der_mode,
                    search_mode=option.search_mode,
                    check=True,
                    verbose_level=1 if VERBOSE_LEVEL >= 2 else 0,
                    filename=None
                )

                if yices_ch_found is not None:
                    yices_weight = int(yices_ch_found.ch_weight)
                    yices_id = [value.val for var, value in yices_ch_found.input_diff]
                    self.assertFalse(BvComp(functools.reduce(Concat, yices_id), 0))
                else:
                    yices_weight = math.inf

                self.assertEqual(btor_weight, yices_weight)

    def test_SearchRkCh(self):
        for diff_type in [XorDiff, RXDiff]:
            for cipher in [Cipher1, Cipher2]:
                if diff_type == RXDiff and cipher == Cipher2:
                    continue

                cipher.set_rounds(1)
                for option in RKCH_OPTIONS:
                    if diff_type == RXDiff and option.enc_der_mode == RkChSearchMode.OptimalFixEncMinKey:
                        continue

                    btor_rkch_found = test_search_related_key_ch(
                        cipher=cipher,
                        diff_type=diff_type,
                        initial_ew=option.initial_ew,
                        initial_kw=option.initial_kw,
                        solver_name="btor",
                        rounds=1,
                        key_der_mode=option.key_der_mode,
                        enc_der_mode=option.enc_der_mode,
                        allow_zero_enc_input_diff=True,
                        search_mode=option.search_mode,
                        check=True,
                        verbose_level=VERBOSE_LEVEL,
                        filename=None
                    )

                    if btor_rkch_found is not None:
                        btor_weight = [
                            int(btor_rkch_found.key_ch_found.ch_weight),
                            int(btor_rkch_found.enc_ch_found.ch_weight)
                        ]
                        btor_id = [value.val for var, value in btor_rkch_found.key_ch_found.input_diff]
                        self.assertFalse(BvComp(functools.reduce(Concat, btor_id), 0))
                    else:
                        btor_weight = [math.inf, math.inf]

                    if diff_type == XorDiff:
                        self.assertEqual([option.initial_kw, option.initial_ew], btor_weight)
                    elif diff_type == RXDiff:
                        if option.enc_der_mode == DerMode.ProbabilityOne:
                            self.assertEqual([math.inf, math.inf], btor_weight)
                        elif option.search_mode in [RkChSearchMode.FirstMinSum, RkChSearchMode.FirstValidKeyMinEnc]:
                            self.assertEqual([0, 1], btor_weight)

                    yices_rkch_found = test_search_related_key_ch(
                        cipher=cipher,
                        diff_type=diff_type,
                        initial_ew=option.initial_ew,
                        initial_kw=option.initial_kw,
                        solver_name="yices",
                        rounds=1,
                        key_der_mode=option.key_der_mode,
                        enc_der_mode=option.enc_der_mode,
                        allow_zero_enc_input_diff=True,
                        search_mode=option.search_mode,
                        check=True,
                        verbose_level=1 if VERBOSE_LEVEL >= 2 else 0,
                        filename=None
                    )

                    if yices_rkch_found is not None:
                        yices_weight = [
                            int(yices_rkch_found.key_ch_found.ch_weight),
                            int(yices_rkch_found.enc_ch_found.ch_weight)
                        ]
                        yices_id = [value.val for var, value in yices_rkch_found.key_ch_found.input_diff]
                        self.assertFalse(BvComp(functools.reduce(Concat, yices_id), 0))
                    else:
                        yices_weight = [math.inf, math.inf]

                    if option.search_mode in [RkChSearchMode.FirstValidKeyMinEnc, RkChSearchMode.OptimalValidKeyMinEnc]:
                        # ignore key weights
                        self.assertEqual(btor_weight[1], yices_weight[1])
                    else:
                        self.assertEqual(btor_weight, yices_weight)

def load_tests(loader, tests, ignore):
    """Add doctests."""
    tests.addTests(doctest.DocTestSuite(arxpy.smt.search_differential))
    return tests


text:
<!DOCTYPE html>

      <title>ASB Reffing Calculator</title>

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

Contributors

Github Link

Placeholder

Contributors

Redew (lead development)

sirDonovan (lead development)

elevator music (testing)

Gale (testing)

Frosty (testing)

Its_A_Random (testing)

akela (math formulas + testing)

ZhengTann (testing)

#capasb (for being supportive + having various testers)

        Input

         BAP
            <input type="text" class="bap" placeholder="BAP" size="5" /> (combo?) <input type="checkbox" class="combo" /> STAB? <input type="checkbox" class="stabBonus" size="5"/>

            Crit Stage <input type="radio" name="critHold" value="0">0</input> <input type="radio" name="critHold" value="1">1</input> <input type="radio" name="critHold" value="2">2</input> <input type="radio" name="critHold" value="3">3</input>

            Attack Rank <input type="text" class="ATR" placeholder="Attack Rank" size="7"/>

            Ability Effects
            <form class="abilityEffectAddSub">
                <input type="radio" name="addSubAbility" value="add">Add</input>
                        <input type="radio" name="addSubAbility" value="subtract">Subtract</input>
                    </form> <input type="text" class="abilityEffectModifier" placeholder="Damage modifier" />

            Field Effects
            <form class="fieldEffectAddSub">
                        <input type="radio" name="addSubField" value="add">Add</input>
                        <input type="radio" name="addSubField" value="subtract">Subtract</input>
                    </form>
                    <input type="text" class="fieldEffectModifier" placeholder="Damage modifier" />

            Item Effect One
            <form class="itemEffectOneAddSub">
                        <input type="radio" name="addSubItemOne" value="add">Add</input>
                        <input type="radio" name="addSubItemOne" value="subtract">Subtract</input>
                    </form>
                    <input type="text" class="itemEffectModifierOne" placeholder="Damage modifier" />

            Defense Rank <input type="text" class="DRB" placeholder="Defense Rank" size="8" />

            Burn Effect? <input type="checkbox" class="burnEffect" />

            Type Effectiveness
            <form class="typeEffectiveness">
                        <input type="radio" name="effect" value="8">8x</input>
                        <input type="radio" name="effect" value="4">4x</input>
                        <input type="radio" name="effect" value="2">2x</input>
                        <input type="radio" name="effect" value="1">1x</input>
                        <input type="radio" name="effect" value="1/2">1/2x</input>
                        <input type="radio" name="effect" value="1/4">1/4x</input>
                        <input type="radio" name="effect" value="1/8">1/8x</input>
                        <input type="radio" name="effect" value="0">0x</input>
                    </form>

            Attacker's Attack Stage Boosts/Decrease

            <input type="text" class="attackStageBoosts" placeholder="Attack Stage Boosts" />

            Attacker's Defense Stage Boosts/Decrease

            <input type="text" class="defenseStageBoosts" placeholder="Defense Stage Boosts" />

            Item Effect Two
            <form class="itemEffectTwoAddSub">
                        <input type="radio" name="addSubItemTwo" value="add">Add</input>
                        <input type="radio" name="addSubItemTwo" value="subtract">Subtract</input>
                    </form>
                    <input type="text" class="itemEffectModifierTwo" placeholder="Damage modifier" />

            <input type="button" class="calcButton" value="Calculate" /> <input type="button" class="resetButton" value="Reset Fields" /> <input type="button" class="rngButton" value="RNG" />

        Output

            RNG Roll
            <input class="rngBox" type="text" placeholder="RNG Roll" size="5"/>
            Crit Roll
            <input class="critBox" type="text" placeholder="Crit Roll" size="5"/>


text:
<?php defined('BX_DOL') or die('hack attempt');

bx_import('BxDolPrivacy');

class BxMessengerConfig extends BxBaseModGeneralConfig
{
    function __construct($aModule)
	{
		parent::__construct($aModule);

	    $this->CNF = array(
            // module icon
            'ICON' => 'comments-o col-green3',

            // database tables
            'TABLE_ENTRIES' => $aModule['db_prefix'] . 'lots',
            'TABLE_NEW_MESSAGES' => $aModule['db_prefix'] . 'unread_jots',
            'TABLE_MESSAGES' => $aModule['db_prefix'] . 'jots',
            'TABLE_TYPES' => $aModule['db_prefix'] . 'lots_types',
            'TABLE_USERS_INFO' => $aModule['db_prefix'] . 'users_info',
            'TABLE_LIVE_COMMENTS' => $aModule['db_prefix'] . 'lcomments',
            'TABLE_JOR_REACTIONS' => $aModule['db_prefix'] . 'jot_reactions',
            'TABLE_JVC' => $aModule['db_prefix'] . 'jvc',
            'TABLE_PUBLIC_JVC' => $aModule['db_prefix'] . 'public_jvc',
            'TABLE_JVCT' => $aModule['db_prefix'] . 'jvc_track',
            'TABLE_LOT_SETTINGS' => $aModule['db_prefix'] . 'lots_settings',
            'TABLE_LOT_ATTACHMENTS' => $aModule['db_prefix'] . 'attachments',
            'TABLE_CMTS_OBJECTS' => 'sys_objects_cmts',
            'TABLE_ENTRIES_FULLTEXT' => 'search_title',
            'TABLE_ENTRIES_COMMENTS_FULLTEXT' => 'search_fields',

            // database fields

            // fields of system table sys_objects_cmts
            'FIELD_COBJ_ID' => 'ID',
            'FIELD_COBJ_MODULE' => 'Module',

            // live comments table fields
            'FIELD_LCMTS_ID' => 'lcmt_id',
            'FIELD_LCMTS_PARENT_ID' => 'lcmt_parent_id',
            'FIELD_LCMTS_SYS_ID' => 'lcmt_system_id',
            'FIELD_LCMTS_VPARENT_ID' => 'lcmt_vparent_id',
            'FIELD_LCMTS_OBJECT_ID' => 'lcmt_object_id',
            'FIELD_LCMTS_AUTHOR' => 'lcmt_author_id',
            'FIELD_LCMTS_LEVEL' => 'lcmt_level',
            'FIELD_LCMTS_TEXT' => 'lcmt_text',
            'FIELD_LCMTS_DATE' => 'lcmt_time',
            'FIELD_LCMTS_REPLIES' => 'lcmt_replies',

            // main lot table fields
            'FIELD_ID' => 'id',
            'FIELD_AUTHOR' => 'author',
            'FIELD_ADDED' => 'created',
            'FIELD_UPDATED' => 'updated',
            'FIELD_PARTICIPANTS' => 'participants',
            'FIELD_TITLE' => 'title',
            'FIELD_URL' => 'url',
            'FIELD_TYPE' => 'type',
            'FIELD_CLASS' => 'class',
            'FIELD_VISIBILITY' => 'visibility',

            // storage tale
            'FIELD_ST_ID' => 'id',
            'FIELD_ST_AUTHOR' => 'profile_id',
            'FIELD_ST_REMOTE' => 'remote_id',
            'FIELD_ST_NAME' => 'file_name',
            'FIELD_ST_ADDED' => 'added',
            'FIELD_ST_JOT' => 'jot_id',
            'FIELD_ST_TYPE' => 'mime_type',
            'FIELD_ST_EXT' => 'ext',

            // messages/jots table fields
            'FIELD_MESSAGE_ID' => 'id',
            'FIELD_MESSAGE' => 'message',
            'FIELD_MESSAGE_FK' => 'lot_id',
            'FIELD_MESSAGE_AUTHOR' => 'user_id',
            'FIELD_MESSAGE_ADDED' => 'created',
            'FIELD_MESSAGE_AT_TYPE' => 'attachment_type',
            'FIELD_MESSAGE_AT' => 'attachment',
            'FIELD_MESSAGE_LAST_EDIT' => 'last_edit',
            'FIELD_MESSAGE_EDIT_BY' => 'edit_by',
            'FIELD_MESSAGE_TRASH' => 'trash',
            'FIELD_MESSAGE_VIDEOC' => 'vc',

            // lots types table fields
            'FIELD_TYPE_ID' => 'id',
            'FIELD_TYPE_NAME' => 'name',
            'FIELD_TYPE_LINKED' => 'show_link', // means use link in title

            // new messages table
            'FIELD_NEW_LOT' => 'lot_id',
            'FIELD_NEW_JOT' => 'first_jot_id',
            'FIELD_NEW_UNREAD' => 'unread_count',
            'FIELD_NEW_PROFILE' => 'user_id',

            // users info fields
            'FIELD_INFO_LOT_ID' => 'lot_id',
            'FIELD_INFO_USER_ID' => 'user_id',
            'FIELD_INFO_STAR' => 'star',
            'FIELD_INFO_PARAMS' => 'params', // means use link in title

             // jot reactions fields
            'FIELD_REACT_JOT_ID' => 'jot_id',
            'FIELD_REACT_NATIVE' => 'native',
            'FIELD_REACT_EMOJI_ID' => 'emoji_id',
            'FIELD_REACT_PROFILE_ID' => 'user_id',
            'FIELD_REACT_ADDED' => 'added',

            // jitsi video conference fields
            'FJVC_ID' => 'id',
            'FJVC_LOT_ID' => 'lot_id',
            'FJVC_ROOM' => 'room',
            'FJVC_NUMBER' => 'number',
            'FJVC_ACTIVE' => 'active',

            // jitsi video conference tracking fields
            'FJVCT_ID' => 'id',
            'FJVCT_FK' => 'jvc_id',
            'FJVCT_AUTHOR_ID' => 'author_id',
            'FJVCT_START' => 'start',
            'FJVCT_END' => 'end',
            'FJVCT_PART' => 'participants',
            'FJVCT_JOINED' => 'joined',

            // jitsi public video conference fields
            'FPJVC_ID' => 'id',
            'FPJVC_ROOM' => 'room',
            'FPJVC_PARTS' => 'participants',
            'FPJVC_STATUS' => 'active',
            'FPJVC_CREATED' => 'created',

            // messenger lot settings
            'FLS_ID' => 'lot_id',
            'FLS_ACTIONS' => 'actions',
            'FLS_SETTINGS' => 'settings',
            'FLS_ICON' => 'icon',

            // messenger lots attachments
            'FLAT_NAME' => 'name',
            'FLAT_SERVICE' => 'service',

            // page URIs
            'URL_HOME' => BX_DOL_URL_ROOT . 'page.php?i=messenger',
            'URL_REPOST' => 'archive/',
            'URL_TEMPLATE' => BX_DOL_URL_ROOT . 'page.php?{link}',

            // some params
            'STAR_BACKGROUND_COLOR' => '#f5a623',
            'FILES_UPLOADER' => 'messenger_uploader_',
            'BELL_ICON_ON' => 'bell',
            'STAR_ICON' => 'star',
            'BELL_ICON_OFF' => 'bell-slash',
            'PARAM_FRIENDS_NUM_BY_DEFAULT' => 10,
            'PARAM_NTFS_INTERVAL' => 1, /* INTERVAL IN HOURS*/
            'PARAM_MESSAGES_INTERVAL' => 1, /* INTERVAL IN MINUTE*/
            'PARAM_SEARCH_DEFAULT_USERS' => (int)getParam($aModule['db_prefix'] . 'max_drop_down_select'),
            'PARAM_MAX_HISTORY_MESSAGES' => 50,
            'PARAM_DEFAULT_TALK_FILES_NUM' => 20,
            'PARAM_MAX_JOT_NTFS_MESSAGE_LENGTH' => 50,
            'PARAM_PUSH_NOTIFICATIONS_DEFAULT_SYMBOLS_NUM' => 190,
            'JOT-PREVIEW-TEXT-LENGTH' => 500,
            'PARAM_PRIVATE' => TRUE,
            'PARAM_PUBLIC' => FALSE,
            'PARAM_ICONS_NUMBER' => 3,
            'PARAM_MODULE_TYPES' => array(
                                            'bx_groups' => BX_IM_TYPE_GROUPS,
                                            'bx_events' => BX_IM_TYPE_EVENTS,
                                            'bx_spaces' => BX_IM_TYPE_GROUPS
                                        ),
            'IMPLODE_GROUPS' => array(
                                            BX_ATT_GROUPS_ATTACH => array(
                                                BX_ATT_TYPE_FILES, BX_ATT_TYPE_FILES_UPLOADING, BX_ATT_TYPE_GIPHY, BX_ATT_TYPE_REPOST, BX_ATT_TYPE_CUSTOM
                                            ),
                                        ),
            'URL_IDENT_PARAMS' => array('i','r','id','profile_id'),
            'TITLE_CONSTANTS' => array('opponent'),

             // GIPHY
             'GIPHY' => array(
                 'api_key' => getParam($aModule['db_prefix'] . 'giphy_key'),
                 'type' => getParam($aModule['db_prefix'] . 'giphy_type'),
                 'rating' => getParam($aModule['db_prefix'] . 'giphy_content_rating'),
                 'limit' => (int)getParam($aModule['db_prefix'] . 'giphy_limit'),
                 'gifs' => 'https://api.giphy.com/v1/gifs/',
                 'stickers' => 'https://api.giphy.com/v1/stickers/',
                 'search' => 'search',
                 'trending' => 'trending'
             ),

            // Jitsi
            'JITSI' => array(
                'LIB-LINK' => 'external_api.js'
            ),

            // Emoji Plugin
            'EMOJI' => array(
                'path' => 'js/emoji-mart/',
                'css' => 'emoji-mart.css',
                'js' => 'emoji-mart.js',
            ),

             // objects
            'OBJECT_STORAGE' => 'bx_messenger_files',
            'OBJECT_IMAGES_TRANSCODER_GALLERY' => 'bx_messenger_photos_resized',
            'OBJECT_IMAGES_TRANSCODER_PREVIEW' => 'bx_messenger_preview',
            'OBJECT_IMAGES_TRANSCODER_ICON' => 'bx_messenger_icon',
            'OBJECT_MP3_TRANSCODER' => 'bx_messenger_mp3',
            'OBJECT_VIDEOS_TRANSCODERS' => array(
                                                    'poster' => 'bx_messenger_videos_poster',
                                                    'mp4' => 'bx_messenger_videos_mp4',
                                                    'mp4_hd' => 'bx_messenger_videos_mp4_hd',
                                                    'webm' => 'bx_messenger_videos_webm',
                                                ),
            'OBJECT_VIEWS' => 'bx_messenger_lots',
            'OBJECT_FORM_ENTRY' => 'bx_messenger_lots',
            'OBJECT_FORM_ENTRY_DISPLAY_VIEW' => 'bx_messenger_lots',
            'OBJECT_MENU_ACTIONS_VIEW_ENTRY' => 'bx_messenger_view', // actions menu on view entry page
            'OBJECT_MENU_ACTIONS_MY_ENTRIES' => 'bx_messenger_my', // actions menu on my entries page
            'OBJECT_MENU_ACTIONS_TALK_MENU' => 'bx_messenger_lot_menu',
            'OBJECT_MENU_SUBMENU' => '', // main module submenu
            'OBJECT_MENU_MANAGE_TOOLS' => 'bx_messenger_menu_manage_tools', //manage menu in content administration tools
            'OBJECT_GRID' => 'bx_messenger',
            'OBJECT_UPLOADERS' => array(),

            // available lot options
            'LOT_OPTIONS' => array(
                'msg',
                'giphy',
                'files',
                'video_rec',
                'smiles'
            ),
            'SEARCH-CRITERIA' => array('titles', 'participants', 'content'),
            //options
            'MAX_SEND_SYMBOLS'	=> (int)getParam($aModule['db_prefix'] . 'max_symbols_number'),
            'MAX_PREV_JOTS_SYMBOLS' => (int)getParam($aModule['db_prefix'] . 'max_symbols_brief_jot'),
            'MAX_JOTS_BY_DEFAULT' => (int)getParam($aModule['db_prefix'] . 'max_jot_number_default'),
            'MAX_JOTS_LOAD_HISTORY' => (int)getParam($aModule['db_prefix'] . 'max_jot_number_in_history'),
            'MAX_LOTS_NUMBER' => (int)getParam($aModule['db_prefix'] . 'max_lots_number'),
            'IS_PUSH_ENABLED' => getParam($aModule['db_prefix'] . 'is_push_enabled') == 'on',
            'PUSH_APP_ID' => getParam('sys_push_app_id') ? getParam('sys_push_app_id') : getParam($aModule['db_prefix'] . 'push_app_id'),
            'PUSH_REST_API' => getParam('sys_push_rest_api') ? getParam('sys_push_rest_api') : getParam($aModule['db_prefix'] . 'push_rest_api'),
            'PUSH_SAFARI_WEB_ID' => getParam('sys_push_safari_id') ? getParam('sys_push_safari_id') : getParam($aModule['db_prefix'] . 'push_safari_id'),
            'PUSH_SHORT_NAME' => getParam('sys_push_short_name') ? getParam('sys_push_short_name') : getParam($aModule['db_prefix'] . 'push_short_name'),
            'SERVER_URL' => getParam($aModule['db_prefix'] . 'server_url'),
            'MAX_FILES_TO_UPLOAD' => (int)getParam($aModule['db_prefix'] . 'max_files_send'),
            'MAX_VIDEO_LENGTH'	=> (int)getParam($aModule['db_prefix'] . 'max_video_length_minutes'),
            'MAX_NTFS_NUMBER'	=> (int)getParam($aModule['db_prefix'] . 'max_ntfs_number'),
            'MAX_VIEWS_PARTS_NUMBER' => (int)getParam($aModule['db_prefix'] . 'max_parts_views'),
            'ALLOW_TO_REMOVE_MESSAGE' => getParam($aModule['db_prefix'] . 'allow_to_remove_messages') == 'on',
            'ALLOW_TO_MODERATE_MESSAGE_FOR_AUTHORS' => getParam($aModule['db_prefix'] . 'allow_to_moderate_messages') == 'on',
            'REMOVE_MESSAGE_IMMEDIATELY' => getParam($aModule['db_prefix'] . 'remove_messages_immediately') == 'on',
            'USE_EMBEDLY' => getParam($aModule['db_prefix'] . 'use_embedly') == 'on',
            'USE_MENTIONS' => getParam($aModule['db_prefix'] . 'enable_mentions') == 'on',
            'EMOJI_SET' => getParam($aModule['db_prefix'] . 'emoji_set'),
            'REACTIONS_SIZE' => (int)getParam($aModule['db_prefix'] . 'reactions_size'),
            'EMOJI_PREVIEW' => getParam($aModule['db_prefix'] . 'show_emoji_preview') == 'on',
            'ENABLE-JITSI' => getParam($aModule['db_prefix'] . 'jitsi_enable') == 'on',
            'JITSI-SERVER' => getParam($aModule['db_prefix'] . 'jitsi_server'),
            'JITSI-CHAT' => getParam($aModule['db_prefix'] . 'jitsi_chat') == 'on',
            'JITSI-CHAT-SYNC' => getParam($aModule['db_prefix'] . 'jitsi_sync') == 'on',
            'JITSI-HIDDEN-INFO' => getParam($aModule['db_prefix'] . 'jitsi_hide_info') == 'on',
            'JITSI-ONLY-FOR-PRIVATE' => getParam($aModule['db_prefix'] . 'jitsi_only_for_private') == 'on',
            'JITSI-ENABLE-WATERMARK' => getParam($aModule['db_prefix'] . 'jitsi_enable_watermark') == 'on',
            'JITSI-WATERMARK-URL' => getParam($aModule['db_prefix'] . 'jitsi_watermark_link'),
            'JITSI-SUPPORT-LINK' => getParam($aModule['db_prefix'] . 'jitsi_support_url'),
            'DISABLE-PROFILE-PRIVACY' => getParam($aModule['db_prefix'] . 'disable_contact_privacy') == 'on',
            'CONTACT-JOIN-ORGANIZATION' => getParam($aModule['db_prefix'] . 'enable_joined_organizations') == 'on',
            'SHOW-FRIENDS' => getParam($aModule['db_prefix'] . 'show_friends') == 'on',
            'CHECK-CONTENT-FOR-TOXIC' => getParam($aModule['db_prefix'] . 'check_toxic') == 'on',
            'TIME-FROM-NOW' => getParam($aModule['db_prefix'] . 'time_in_history') == 'on',
            'DONT-SHOW-DESC' => getParam($aModule['db_prefix'] . 'dont_show_search_desc') == 'on',
            'USE-UNIQUE-MODE' => getParam($aModule['db_prefix'] . 'use_unique_mode') == 'on',
            'USE-FRIENDS-ONLY-MODE' => getParam($aModule['db_prefix'] . 'connect_friends_only') == 'on',
            'SEARCH-CRITERIA-SELECTED' => getParam($aModule['db_prefix'] . 'search_criteria'),
            'JWT' => array(
              'app_id' => getParam($aModule['db_prefix'] . 'jwt_app_id'),
              'secret' => getParam($aModule['db_prefix'] . 'jwt_app_secret'),
            ),
            'JOT-JWT' =>  trim(getParam($aModule['db_prefix'] . 'jot_server_jwt')),
            'JSMain' => 'oMessenger'
        );

		$this->_aObjects = array(
            'alert' => $this->_sName
		);
	}

	/**
	* Returns type of the talk
	*@param string $sModule module uri, if messenger block was added to a special page of any module
	*@return int type
	*/
	public function getTalkType($sModule = ''){
		return $sModule && isset($this->CNF['PARAM_MODULE_TYPES'][$sModule]) ? $this->CNF['PARAM_MODULE_TYPES'][$sModule] : BX_IM_TYPE_PUBLIC;
	}

	/**
	* Checks if the posted link is reporst link
	*@param string $sUrl internal post url
	*@return array, string url and int post id
	*/
	public function isJotLink($sUrl){
		$aResult = array();
		$sJotPattern = '/^'. preg_replace(array('/\./', '/\//', '/\?/'), array('\.', '\/', '\?'), $this->getRepostUrl()) . '(\d+)/i';
		if (preg_match($sJotPattern, $sUrl, $aMatches) && intval($aMatches[1]))
			$aResult = array('url' => $aMatches[0], 'id' => $aMatches[1]);

		return $aResult;
	}

	public function getBaseUri()
    {
        $sLink = parent::getBaseUri();
        if(strncmp($sLink, BX_DOL_URL_ROOT, strlen(BX_DOL_URL_ROOT)) !== 0)
            $sLink = BX_DOL_URL_ROOT . $sLink;

        return $sLink;
    }

    public function getRepostUrl($iJotId = 0)
    {
        return $this->getBaseUri() . $this->CNF['URL_REPOST'] . ( $iJotId ? $iJotId : '');
    }

    /**
	* Converts text link to url (wraps text url to )
	*@param string $sText url
	*@param string $sAttrs special attributes for the link
	*@param boolean $bHtmlSpecialChars convert link to special html chars
	*@return string url
	*/
	public function bx_linkify($sText, $sAttrs = '', $bHtmlSpecialChars = false){
		if ($bHtmlSpecialChars)
			$sText = htmlspecialchars($sText, ENT_NOQUOTES, 'UTF-8');

		$sRe = "@(((https?://)|(www\.))[^\"<\s]+)(?![^<>]*>|[^\"]*?<\/a)@";
		preg_match_all($sRe, $sText, $aMatches, PREG_OFFSET_CAPTURE);

		$aMatches = $aMatches[0];
		if ($i = count($aMatches))
			$bAddNofollow = getParam('sys_add_nofollow') == 'on';

		while ($i--)
		{
			$sUrl = $aMatches[$i][0];
			if (!preg_match('@^https?://@', $sUrl))
				$sUrl = 'http://'.$sUrl;

			if (strncmp(BX_DOL_URL_ROOT, $sUrl, strlen(BX_DOL_URL_ROOT)) !== 0) {
				$sAttrs .= ' target="_blank" ';
				if ($bAddNofollow)
					$sAttrs .= ' rel="nofollow" ';
			}

			if ($this -> isJotLink($sUrl))
				$sReplacement = "{$aMatches[$i][0]}";
			else
			{
				$oEmbed = BxDolEmbed::getObjectInstance();
				if($oEmbed && $this -> CNF['USE_EMBEDLY'])
					$sReplacement = $oEmbed->getLinkHTML($sUrl, $aMatches[$i][0]);
				else
					$sReplacement = "{$aMatches[$i][0]}";
			}

			$sText = substr_replace($sText, $sReplacement, $aMatches[$i][1], strlen($aMatches[$i][0]));
		}

		$mail_pattern = "/([\w.]+@[a-zA-Z_-]+?(?:\.[a-zA-Z]{2,6}))(?![^<>]*>|[^\"]*?<\/a)/";
		$sText = preg_replace($mail_pattern, '$1', $sText);

		return $sText;
	}

	/**
	* Remove repost links from the message
	*@param string $sMessage message
	*@param int iJotId jot Id
	*@return string message
	*/
	public function cleanRepostLinks($sMessage, $iJotId)
	{
		$sArchiveUrl = $this->getRepostUrl($iJotId);
		return str_replace($sArchiveUrl, '', $sMessage);
	}

	/**
	* Builds from server environment valid Url handle for lot
	*@return string url
	*/
    public function getPageIdent($sPageLink = '')
    {
       $sPageUrl = $sPageLink ? $sPageLink : $_SERVER['REQUEST_URI'];
       $sPageUrl = BxDolPermalinks::getInstance()->unpermalink(ltrim($sPageUrl, '/'));
       return $sPageUrl ? parse_url($sPageUrl, PHP_URL_QUERY) : 'index.php';
    }

    public function getPageLink($sUrl){
        if ($sUrl === 'index.php')
            return BX_DOL_URL_ROOT;

	    return BxDolPermalinks::getInstance()->permalink(str_replace('{link}', $sUrl, $this->CNF['URL_TEMPLATE']));
    }

    public function isOneSignalEnabled(){
	    return $this->CNF['IS_PUSH_ENABLED'] && $this->CNF['PUSH_APP_ID'] && $this->CNF['PUSH_REST_API'];
    }

    public function getGiphyGifs($sAction = 'trending', $sValue = '', $iStart = 0){
        $oGiphy = &$this->CNF['GIPHY'];
	    $aParams = array(
            'api_key' => $oGiphy['api_key'],
            'offset' => $iStart,
            'limit' => (int)$oGiphy['limit'],
            'rating' => $oGiphy['rating']
        );

        $sUrl = $oGiphy[$oGiphy['type']];
        if ($sAction === 'search' && $sValue){
            $aParams['q'] = $sValue;
            $aParams['lang'] = bx_lang_name();
            $aParams['random_id'] = time();
        }

        $sAction = $sAction ? $sAction : 'trending';
        $sAction = isset($oGiphy[$sAction]) ? $oGiphy[$sAction] : $sAction;
        return bx_file_get_contents("{$sUrl}{$sAction}", $aParams);
    }

    public function getRoomId($mixedLotId = '', $mixedAuthor = ''){
        return 'UNA' . md5(BX_DOL_URL_ROOT . $mixedLotId . $mixedAuthor . BX_DOL_SECRET);
    }

    public function isJitsiAllowed($iType){
        if (!$this->CNF['ENABLE-JITSI'])
	        return false;

	    if ($this->CNF['JITSI-ONLY-FOR-PRIVATE'] && ($iType == BX_IM_TYPE_PUBLIC || $iType == BX_IM_TYPE_SETS))
	        return false;

	    return $this->isAllowedAction(BX_MSG_ACTION_CREATE_VC) === true;
    }

    public function getValidUrl($sUrl, $sType = 'domain'){
        if (!$sUrl || !($aUrl = parse_url($sUrl)))
            return '';

        $sDomain = isset($aUrl['host']) ? $aUrl['host'] : (isset($aUrl['path']) ? $aUrl['path'] : $sUrl);
        $sDomain = str_replace(["www."], [''], $sDomain);

        return $sType === 'domain' ? $sDomain : "https://{$sDomain}";
    }

    public function isAllowedAction($sAction = BX_MSG_ACTION_SEND_MESSAGE, $iProfileId = 0){
        if (!$iProfileId)
            $iProfileId = bx_get_logged_profile_id();

        $aProfileMembership = BxDolAcl::getInstance()->getMemberMembershipInfo($iProfileId);
        if (isset($aProfileMembership['status']) && $aProfileMembership['status'] !== 'active')
            return false;

        if ($sAction && ($sMembershipAction = str_replace('_', ' ', $sAction))){
           $aCheck = checkActionModule($iProfileId, $sMembershipAction, $this->getName(), true);
           if ($aCheck[CHECK_ACTION_RESULT] !== CHECK_ACTION_RESULT_ALLOWED)
                return $aCheck[CHECK_ACTION_MESSAGE];
        }

        return true;
    }

    function generateJWTToken($iProfileId, $aUserParams = array(), $aTokenParams = array()){
        $oProfileInfo = BxDolProfile::getInstance( $iProfileId );
        if (!$iProfileId || (empty($aUserParams) && empty($aTokenParams)))
            return false;

        // Encode Header to Base64Url String
        $sHeader = json_encode(['alg' => 'HS256', 'typ' => 'JWT']);
        $sHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($sHeader));

        // Create token payload as a JSON string
        $sPayload = json_encode( array_merge(array('context' => $aUserParams), $aTokenParams));
        $sPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($sPayload));

        // Create Signature Hash
        $sSignature = hash_hmac('sha256', $sHeader . "." . $sPayload, $this->CNF['JOT-JWT'], true);
        $sSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($sSignature));

        return "{$sHeader}.{$sPayload}.{$sSignature}";
    }

    public function isValidToUpload($sFileName){
        if (!$sFileName)
            return false;

        $sBaseName = basename($sFileName);
        if (strcmp($sBaseName, $sFileName) !== 0)
            return false;

        $sRequestPath = realpath(BX_DIRECTORY_PATH_TMP . $sFileName);
	    $sValidRootPath = realpath(BX_DIRECTORY_PATH_TMP);

	    return $sRequestPath !== false && strcmp(substr($sRequestPath, 0, strlen($sValidRootPath)), $sValidRootPath) === 0;
    }

    public function isSearchCriteria($sSelected){
        $aItems = $this->CNF['SEARCH-CRITERIA-SELECTED'] ? explode(',', $this->CNF['SEARCH-CRITERIA-SELECTED']) : array();
        if (empty($aItems))
            return false;

        return in_array($sSelected, $aItems);
    }

    public function replaceConstant($sTitle, $aMarkers){
        foreach($this->CNF['TITLE_CONSTANTS'] as &$sItem){
            if (isset($aMarkers[$sItem]))
                $sTitle = str_replace('{' . $sItem . '}', $aMarkers[$sItem], $sTitle);
        }

        return $sTitle;
    }
}

/** @} */


text:
layout: page
title: Galloway - Sandoval Wedding
date: 2016-05-24
author: Deborah Mayo
tags: weekly links, java
status: published
summary: Aliquam sit amet ante ut massa imperdiet feugiat.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 12/18/2017
  endDate: 12/22/2017
  ctyhocn: GUEONHX
  groupCode: GSW
published: true
---
Nulla a dapibus nibh, non gravida arcu. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut pretium lectus mi. Duis sed risus vitae felis rutrum placerat. Donec in interdum nibh. Integer congue dignissim sapien, et efficitur urna dapibus eget. Donec luctus a diam eget posuere. Ut elementum vehicula magna vitae lobortis. Praesent fringilla risus velit, ullamcorper ultrices orci tincidunt in. Curabitur sed tellus at quam faucibus bibendum. Sed viverra lectus ac ligula lobortis, eu laoreet sem tempus. Phasellus mollis porttitor mauris, in efficitur dolor sollicitudin eu.
Suspendisse potenti. In hac habitasse platea dictumst. Vestibulum varius mollis scelerisque. Sed bibendum et neque eu convallis. Nunc suscipit porttitor ipsum, sed laoreet ipsum finibus venenatis. Proin euismod venenatis lacus. Phasellus sed mattis sem. Sed id nunc lorem.

1 Mauris a libero a nunc faucibus vehicula vel sed tellus
1 Quisque interdum neque in quam congue placerat
1 Nunc a neque sit amet metus ornare volutpat
1 Aenean lobortis leo non rhoncus viverra.

Ut in orci eget ipsum luctus eleifend nec id augue. Curabitur et pellentesque sem. Praesent velit tortor, auctor non sapien et, faucibus fermentum arcu. Phasellus ac dignissim lorem. Sed nulla purus, hendrerit nec massa id, volutpat sodales velit. Praesent rutrum at tortor eu blandit. Cras fermentum quis erat vel ultrices. Vestibulum faucibus magna ac justo gravida, ac venenatis velit sagittis. Sed ut urna dolor. Etiam ultrices risus pretium porttitor faucibus. Mauris cursus consequat ligula. Ut eu luctus erat, et consectetur arcu. Fusce eu sodales orci. Sed ut orci quis ex convallis consequat. Duis quam sem, convallis feugiat volutpat non, porta eget turpis.


text:
package com.facebook.buck.testutil;

import com.facebook.buck.graph.MutableDirectedGraph;
import com.facebook.buck.rules.ActionGraph;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.google.common.collect.ImmutableList;

public class RuleMap {

  /** Utility class: do not instantiate. */
  private RuleMap() {}

  public static ActionGraph createGraphFromBuildRules(BuildRuleResolver params) {
    Iterable<BuildRule> rules = params.getBuildRules();
    return createGraphFromBuildRules(rules);
  }

  public static ActionGraph createGraphFromSingleRule(BuildRule buildRule) {
    return createGraphFromBuildRules(ImmutableList.of(buildRule));
  }

  private static ActionGraph createGraphFromBuildRules(Iterable<BuildRule> rules) {
    MutableDirectedGraph<BuildRule> graph = new MutableDirectedGraph<BuildRule>();
    for (BuildRule rule : rules) {
      graph.addNode(rule);
      for (BuildRule dep : rule.getDeps()) {
        graph.addEdge(rule, dep);
      }
    }
    return new ActionGraph(graph);
  }

}


text:
/**
 * Created by loomisdf on 4/11/2016.
 */
public enum ErrorResult {
    SUCCESS,
    FAIL
}


text:
import json

from tempest.common import service_client

class NetworksClientJSON(service_client.ServiceClient):

    def list_networks(self):
        resp, body = self.get("os-networks")
        body = json.loads(body)
        self.expected_success(200, resp.status)
        return service_client.ResponseBodyList(resp, body['networks'])

    def show_network(self, network_id):
        resp, body = self.get("os-networks/%s" % str(network_id))
        body = json.loads(body)
        self.expected_success(200, resp.status)
        return service_client.ResponseBody(resp, body['network'])


text:
class ChangeGiftCardExpDateToString < ActiveRecord::Migration
  def change
  	change_column :gift_cards, :expiration_date, :string
  end
end


text:
namespace content {

namespace {

const int kBufferSize = 1024;
const char kTestData1[] = "Hello";
const char kTestData2[] = "Here it is data.";

const GURL kStreamURL("blob://stream");

}  // namespace

class StreamURLRequestJobTest : public testing::Test {
 public:
  // A simple ProtocolHandler implementation to create StreamURLRequestJob.
  class MockProtocolHandler :
      public net::URLRequestJobFactory::ProtocolHandler {
   public:
    MockProtocolHandler(StreamRegistry* registry) : registry_(registry) {}

    // net::URLRequestJobFactory::ProtocolHandler override.
    virtual net::URLRequestJob* MaybeCreateJob(
        net::URLRequest* request,
        net::NetworkDelegate* network_delegate) const OVERRIDE {
      scoped_refptr<Stream> stream = registry_->GetStream(request->url());
      if (stream.get())
        return new StreamURLRequestJob(request, network_delegate, stream);
      return NULL;
    }

   private:
    StreamRegistry* registry_;
  };

  StreamURLRequestJobTest() {}

  virtual void SetUp() {
    registry_.reset(new StreamRegistry());

    url_request_job_factory_.SetProtocolHandler(
        "blob", new MockProtocolHandler(registry_.get()));
    url_request_context_.set_job_factory(&url_request_job_factory_);
  }

  virtual void TearDown() {
  }

  void TestSuccessRequest(const GURL& url,
                          const std::string& expected_response) {
    TestRequest("GET", url, net::HttpRequestHeaders(), 200, expected_response);
  }

  void TestRequest(const std::string& method,
                   const GURL& url,
                   const net::HttpRequestHeaders& extra_headers,
                   int expected_status_code,
                   const std::string& expected_response) {
    net::TestDelegate delegate;
    request_ = url_request_context_.CreateRequest(
        url, net::DEFAULT_PRIORITY, &delegate);
    request_->set_method(method);
    if (!extra_headers.IsEmpty())
      request_->SetExtraRequestHeaders(extra_headers);
    request_->Start();

    base::MessageLoop::current()->RunUntilIdle();

    // Verify response.
    EXPECT_TRUE(request_->status().is_success());
    ASSERT_TRUE(request_->response_headers());
    EXPECT_EQ(expected_status_code,
              request_->response_headers()->response_code());
    EXPECT_EQ(expected_response, delegate.data_received());
  }

 protected:
  base::MessageLoopForIO message_loop_;
  scoped_ptr<StreamRegistry> registry_;

  net::URLRequestContext url_request_context_;
  net::URLRequestJobFactoryImpl url_request_job_factory_;
  scoped_ptr<net::URLRequest> request_;
};

TEST_F(StreamURLRequestJobTest, TestGetSimpleDataRequest) {
  scoped_refptr<Stream> stream(
      new Stream(registry_.get(), NULL, kStreamURL));

  scoped_refptr<net::StringIOBuffer> buffer(
      new net::StringIOBuffer(kTestData1));

  stream->AddData(buffer, buffer->size());
  stream->Finalize();

  TestSuccessRequest(kStreamURL, kTestData1);
}

TEST_F(StreamURLRequestJobTest, TestGetLargeStreamRequest) {
  scoped_refptr<Stream> stream(
      new Stream(registry_.get(), NULL, kStreamURL));

  std::string large_data;
  large_data.reserve(kBufferSize * 5);
  for (int i = 0; i < kBufferSize * 5; ++i)
    large_data.append(1, static_cast<char>(i % 256));

  scoped_refptr<net::StringIOBuffer> buffer(
      new net::StringIOBuffer(large_data));

  stream->AddData(buffer, buffer->size());
  stream->Finalize();
  TestSuccessRequest(kStreamURL, large_data);
}

TEST_F(StreamURLRequestJobTest, TestGetNonExistentStreamRequest) {
  net::TestDelegate delegate;
  request_ = url_request_context_.CreateRequest(
      kStreamURL, net::DEFAULT_PRIORITY, &delegate);
  request_->set_method("GET");
  request_->Start();

  base::MessageLoop::current()->RunUntilIdle();

  // Verify response.
  EXPECT_FALSE(request_->status().is_success());
}

TEST_F(StreamURLRequestJobTest, TestRangeDataRequest) {
  scoped_refptr<Stream> stream(
      new Stream(registry_.get(), NULL, kStreamURL));

  scoped_refptr<net::StringIOBuffer> buffer(
      new net::StringIOBuffer(kTestData2));

  stream->AddData(buffer, buffer->size());
  stream->Finalize();

  net::HttpRequestHeaders extra_headers;
  extra_headers.SetHeader(net::HttpRequestHeaders::kRange,
                          net::HttpByteRange::Bounded(0, 3).GetHeaderValue());
  TestRequest("GET", kStreamURL, extra_headers,
              200, std::string(kTestData2, 4));
}

TEST_F(StreamURLRequestJobTest, TestInvalidRangeDataRequest) {
  scoped_refptr<Stream> stream(
      new Stream(registry_.get(), NULL, kStreamURL));

  scoped_refptr<net::StringIOBuffer> buffer(
      new net::StringIOBuffer(kTestData2));

  stream->AddData(buffer, buffer->size());
  stream->Finalize();

  net::HttpRequestHeaders extra_headers;
  extra_headers.SetHeader(net::HttpRequestHeaders::kRange,
                          net::HttpByteRange::Bounded(1, 3).GetHeaderValue());
  TestRequest("GET", kStreamURL, extra_headers, 405, std::string());
}

}  // namespace content


text:
using System.Web.Mvc;
using TeachersDiary.Clients.Mvc.Controllers.Abstracts;

namespace TeachersDiary.Clients.Mvc.Controllers
{
    public class LandingController : NonAuthorizeController
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}


text:
namespace {

// Set managed auth token for Android managed accounts.
constexpr char kManagedAuthToken[] = "managed-auth-token";
// Set unmanaged auth token for other Android unmanaged accounts.
constexpr char kUnmanagedAuthToken[] = "unmanaged-auth-token";
constexpr char kWellKnownConsumerName[] = "test@gmail.com";
constexpr char kFakeUserName[] = "test@example.com";
constexpr char kFakeGaiaId[] = "1234567890";

std::unique_ptr<KeyedService> CreateCertificateProviderService(
    content::BrowserContext* context) {
  return std::make_unique<chromeos::CertificateProviderService>();
}

}  // namespace

namespace arc {

// Waits for the "arc.enabled" preference value from true to false.
class ArcPlayStoreDisabledWaiter : public ArcSessionManager::Observer {
 public:
  ArcPlayStoreDisabledWaiter() { ArcSessionManager::Get()->AddObserver(this); }

  ~ArcPlayStoreDisabledWaiter() override {
    ArcSessionManager::Get()->RemoveObserver(this);
  }

  void Wait() {
    base::RunLoop run_loop;
    base::AutoReset<base::RunLoop*> reset(&run_loop_, &run_loop);
    run_loop.Run();
  }

 private:
  // ArcSessionManager::Observer override:
  void OnArcPlayStoreEnabledChanged(bool enabled) override {
    if (!enabled) {
      DCHECK(run_loop_);
      run_loop_->Quit();
    }
  }

  base::RunLoop* run_loop_ = nullptr;

  DISALLOW_COPY_AND_ASSIGN(ArcPlayStoreDisabledWaiter);
};

class ArcSessionManagerTest : public MixinBasedInProcessBrowserTest {
 protected:
  ArcSessionManagerTest() = default;
  ~ArcSessionManagerTest() override = default;

  // MixinBasedInProcessBrowserTest:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    MixinBasedInProcessBrowserTest::SetUpCommandLine(command_line);
    arc::SetArcAvailableCommandLineForTesting(command_line);
  }

  void SetUpOnMainThread() override {
    MixinBasedInProcessBrowserTest::SetUpOnMainThread();
    user_manager_enabler_ = std::make_unique<user_manager::ScopedUserManager>(
        std::make_unique<chromeos::FakeChromeUserManager>());
    // Init ArcSessionManager for testing.
    ArcServiceLauncher::Get()->ResetForTesting();
    ArcSessionManager::SetUiEnabledForTesting(false);
    ArcSessionManager::EnableCheckAndroidManagementForTesting(true);
    ArcSessionManager::Get()->SetArcSessionRunnerForTesting(
        std::make_unique<ArcSessionRunner>(
            base::BindRepeating(FakeArcSession::Create)));

    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
    EXPECT_TRUE(ExpandPropertyFilesForTesting(ArcSessionManager::Get(),
                                              temp_dir_.GetPath()));

    chromeos::ProfileHelper::SetAlwaysReturnPrimaryUserForTesting(true);

    const AccountId account_id(
        AccountId::FromUserEmailGaiaId(kFakeUserName, kFakeGaiaId));
    GetFakeUserManager()->AddUser(account_id);
    GetFakeUserManager()->LoginUser(account_id);

    // Create test profile.
    TestingProfile::Builder profile_builder;
    profile_builder.SetPath(temp_dir_.GetPath().AppendASCII("TestArcProfile"));
    profile_builder.SetProfileName(kFakeUserName);
    profile_ = IdentityTestEnvironmentProfileAdaptor::
        CreateProfileForIdentityTestEnvironment(profile_builder);

    identity_test_environment_adaptor_ =
        std::make_unique<IdentityTestEnvironmentProfileAdaptor>(profile_.get());

    // Seed account info properly.
    identity_test_env()->MakeUnconsentedPrimaryAccountAvailable(kFakeUserName);

    profile()->GetPrefs()->SetBoolean(prefs::kArcSignedIn, true);
    profile()->GetPrefs()->SetBoolean(prefs::kArcTermsAccepted, true);

    // TestingProfile is not interpreted as a primary profile. Inject factory so
    // that the instance of CertificateProviderService for the profile can be
    // created.
    chromeos::CertificateProviderServiceFactory::GetInstance()
        ->SetTestingFactory(
            profile(), base::BindRepeating(&CreateCertificateProviderService));

    // Set up ARC for test profile.
    // Currently, ArcSessionManager is singleton and set up with the original
    // Profile instance. This re-initializes the ArcServiceLauncher by
    // overwriting Profile with profile().
    // TODO(hidehiko): This way several ArcService instances created with
    // the original Profile instance on Browser creatuion are kept in the
    // ArcServiceManager. For proper overwriting, those should be removed.
    ArcServiceLauncher::Get()->OnPrimaryUserProfilePrepared(profile());
  }

  void TearDownOnMainThread() override {
    // Explicitly removing the user is required; otherwise ProfileHelper keeps
    // a dangling pointer to the User.
    // TODO(nya): Consider removing all users from ProfileHelper in the
    // destructor of FakeChromeUserManager.
    const AccountId account_id(
        AccountId::FromUserEmailGaiaId(kFakeUserName, kFakeGaiaId));
    GetFakeUserManager()->RemoveUserFromList(account_id);
    // Since ArcServiceLauncher is (re-)set up with profile() in
    // SetUpOnMainThread() it is necessary to Shutdown() before the profile()
    // is destroyed. ArcServiceLauncher::Shutdown() will be called again on
    // fixture destruction (because it is initialized with the original Profile
    // instance in fixture, once), but it should be no op.
    // TODO(hidehiko): Think about a way to test the code cleanly.
    ArcServiceLauncher::Get()->Shutdown();
    identity_test_environment_adaptor_.reset();
    profile_.reset();
    base::RunLoop().RunUntilIdle();
    user_manager_enabler_.reset();
    chromeos::ProfileHelper::SetAlwaysReturnPrimaryUserForTesting(false);
    MixinBasedInProcessBrowserTest::TearDownOnMainThread();
  }

  chromeos::FakeChromeUserManager* GetFakeUserManager() const {
    return static_cast<chromeos::FakeChromeUserManager*>(
        user_manager::UserManager::Get());
  }

  void EnableArc() {
    PrefService* const prefs = profile()->GetPrefs();
    prefs->SetBoolean(prefs::kArcEnabled, true);
    base::RunLoop().RunUntilIdle();
  }

  void set_profile_name(const std::string& username) {
    profile_->set_profile_name(username);
  }

  Profile* profile() { return profile_.get(); }

  signin::IdentityTestEnvironment* identity_test_env() {
    return identity_test_environment_adaptor_->identity_test_env();
  }

  signin::IdentityManager* identity_manager() {
    return identity_test_env()->identity_manager();
  }

 private:
  chromeos::LocalPolicyTestServerMixin local_policy_mixin_{&mixin_host_};
  std::unique_ptr<user_manager::ScopedUserManager> user_manager_enabler_;
  std::unique_ptr<IdentityTestEnvironmentProfileAdaptor>
      identity_test_environment_adaptor_;
  base::ScopedTempDir temp_dir_;
  std::unique_ptr<TestingProfile> profile_;

  DISALLOW_COPY_AND_ASSIGN(ArcSessionManagerTest);
};

IN_PROC_BROWSER_TEST_F(ArcSessionManagerTest, ConsumerAccount) {
  EnableArc();
  identity_test_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      identity_manager()->GetPrimaryAccountId(
          signin::ConsentLevel::kNotRequired),
      kUnmanagedAuthToken, base::Time::Max());
  ASSERT_EQ(ArcSessionManager::State::ACTIVE,
            ArcSessionManager::Get()->state());
}

IN_PROC_BROWSER_TEST_F(ArcSessionManagerTest, WellKnownConsumerAccount) {
  set_profile_name(kWellKnownConsumerName);
  EnableArc();
  ASSERT_EQ(ArcSessionManager::State::ACTIVE,
            ArcSessionManager::Get()->state());
}

IN_PROC_BROWSER_TEST_F(ArcSessionManagerTest, ManagedChromeAccount) {
  policy::ProfilePolicyConnector* const connector =
      profile()->GetProfilePolicyConnector();
  connector->OverrideIsManagedForTesting(true);

  EnableArc();
  ASSERT_EQ(ArcSessionManager::State::ACTIVE,
            ArcSessionManager::Get()->state());
}

IN_PROC_BROWSER_TEST_F(ArcSessionManagerTest, ManagedAndroidAccount) {
  EnableArc();
  identity_test_env()->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
      identity_manager()->GetPrimaryAccountId(
          signin::ConsentLevel::kNotRequired),
      kManagedAuthToken, base::Time::Max());
  ArcPlayStoreDisabledWaiter().Wait();
  EXPECT_FALSE(IsArcPlayStoreEnabledForProfile(profile()));
}

// Make sure that ARC is disabled upon entering locked fullscreen mode.
IN_PROC_BROWSER_TEST_F(ArcSessionManagerTest, ArcDisabledInLockedFullscreen) {
  EnableArc();
  ASSERT_EQ(ArcSessionManager::State::ACTIVE,
            ArcSessionManager::Get()->state());

  const int window_id = extensions::ExtensionTabUtil::GetWindowId(browser());
  const char kStateLockedFullscreen[] =
      "[%u, {\"state\": \"locked-fullscreen\"}]";

  auto function = base::MakeRefCounted<extensions::WindowsUpdateFunction>();
  scoped_refptr<const extensions::Extension> extension(
      extensions::ExtensionBuilder("Test")
          .SetID("pmgljoohajacndjcjlajcopidgnhphcl")
          .AddPermission("lockWindowFullscreenPrivate")
          .Build());
  function->set_extension(extension.get());

  extension_function_test_utils::RunFunctionAndReturnSingleResult(
      function.get(), base::StringPrintf(kStateLockedFullscreen, window_id),
      browser());

  ASSERT_EQ(ArcSessionManager::State::STOPPED,
            ArcSessionManager::Get()->state());
}

}  // namespace arc


text:
import random
import tensorflow as tf
from FCNet import FCNet

LOSS_V = 100
ENTROPY_BETA = 0.05
_EPSILON = 1e-6
L2_P = 1e-5
L2_V = 1e-2
actor_learning_rate = 1e-3
critic_learning_rate = 1e-3

class ACNet(object):

    def __init__(self, state_size, action_size):
        self.state_size = state_size
        self.action_size = action_size
        self.action_space = list(range(self.action_size))

        self.inputs = tf.placeholder(tf.float32, [None, state_size], 'inputs')
        self.actions = tf.placeholder(tf.int32, [None], 'aciton') # which action was taken
        self.a_t = tf.one_hot(self.actions, self.action_size, name='action_taken')
        self.targets = tf.placeholder(tf.float32, [None], 'disounted_reward')
        # not immediate but n step discounted
        self.R = tf.expand_dims(self.targets, axis=1)

        # build network
        self.actor = FCNet('actor')
        self.critic = FCNet('critic')
        # policy and deterministic policy
        self.P = tf.nn.softmax(self.actor(self.inputs, self.action_size))
        self.DP = tf.reduce_sum(self.P * self.a_t, axis=1, keep_dims=True)
        # choose action one step, action probability
        self.AP = tf.squeeze(self.P, axis=0)
        self.log_DP = tf.log(self.DP + _EPSILON)
        # value and advantage
        self.V = self.critic(self.inputs, 1) # value predicted
        self.A = self.R - self.V
        # loss
        self.loss_policy = -tf.reduce_sum(self.log_DP * tf.stop_gradient(self.A))
        self.loss_value = LOSS_V * tf.nn.l2_loss(self.A)
        self.loss_entropy = ENTROPY_BETA * tf.reduce_sum(self.P * tf.log(self.P + _EPSILON))

        # optimizer
        #self.actor_optimizer = tf.train.AdamOptimizer(
        #    actor_learning_rate).minimize(self.loss_policy + self.loss_entropy)
        #self.critic_optimizer = tf.train.AdamOptimizer(
        #    critic_learning_rate).minimize(self.loss_value)

        self.l2_policy = L2_P * tf.add_n(self.actor.get_regularizers())
        self.l2_value = L2_V * tf.add_n(self.critic.get_regularizers())

        self.actor_optimizer = tf.train.AdamOptimizer(
            actor_learning_rate).minimize(
            self.loss_policy + self.l2_policy + self.loss_entropy)
        self.critic_optimizer = tf.train.AdamOptimizer(
            critic_learning_rate).minimize(
            self.loss_value + self.l2_value)

        # session
        self.sess = tf.Session()
        self.init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
        self.sess.run(self.init_op)
        self.default_graph = tf.get_default_graph()
        self.default_graph.finalize()

    def predict_value(self, state):
        return self.sess.run(self.V, {self.inputs: state})

    def predict_policy(self, state):
        return self.sess.run(self.P, {self.inputs: state})

    def predict_action(self, state):
        policy = self.sess.run(self.AP, {self.inputs: state})
        return random.choices(self.action_space, policy)[0]

    def train_actor(self, states, actions, targets):
        self.sess.run(self.actor_optimizer,
                      {self.inputs: states, self.actions: actions, self.targets: targets})

    def train_critic(self, states, targets):
        self.sess.run(self.critic_optimizer,
                      {self.inputs: states, self.targets: targets})

    def get_loss(self, states, actions, targets):
        fetches = [self.loss_policy, self.loss_entropy, self.l2_policy,
                   self.loss_value, self.l2_value]
        feed_dict = {self.inputs: states, self.actions: actions, self.targets: targets}
        return self.sess.run(fetches, feed_dict)


text:
extern StackBaseDateTimeType *const StackBaseDateTimeTypeYEAR;//YYYY
extern StackBaseDateTimeType *const StackBaseDateTimeTypeDATE;//YYYY-MM-DD
extern StackBaseDateTimeType *const StackBaseDateTimeTypeTIME;//HH:MM:SS
extern StackBaseDateTimeType *const StackBaseDateTimeTypeDATETIME;//YYYY-MM-DD HH:MM:SS
extern StackBaseDateTimeType *const StackBaseDateTimeTypeTIMESTAMP;//YYYY-MM-DD HH:MM:SS

@interface StackBaseColumnTypes : NSString

@end


text:
import sys

# Offsets from the known zero position
EXTRUDER_OFFSET_Y = 0.0
EXTRUDER_OFFSET_X = 21.0

# Bed size, for making sure the print doesn't extend beyond
BED_X = 200
BED_Y = 200

INITIAL_LINES_TO_FIND_START_GCODE = 100

def findline(lst, a, b, needle):
    for i in range(a, b):
        if needle in lst[i]:
            return i
    raise ValueError("Needle %r not found" % (needle,))

def extract_param(line, key):
    parts = line.split()
    for p in parts:
        if p.startswith(key):
            return p[1:]
    raise ValueError('Key %r not found in line %r' % (key, line))

# This bit is so we don't have to change start.gcode
def replace_start_gcode(lines):
    bed_line = findline(lines, 0, INITIAL_LINES_TO_FIND_START_GCODE, "M109")
    head_line = findline(lines, 0, INITIAL_LINES_TO_FIND_START_GCODE, "M104")
    # Final temp
    bed_temp3 = extract_param(lines[bed_line], 'S')
    head_temp = extract_param(lines[head_line], 'S')
    # Initial temp
    bed_temp = '%g' % (float(bed_temp)-10,)
    # Heat extruder at this temp
    bed_temp2 = '%g' % (float(bed_temp)-5,)

    b = findline(lines, a, INITIAL_LINES_TO_FIND_START_GCODE, "end of start")
    start_gcode = open('start.gcode').read()
    start_gcode %= locals()
    return start_code.splitlines(), lines[b:]

def offset_gcode_line(line, dx, dy):
    # TODO comments
    parts = line.split()
    for i in range(len(parts)):
        if parts[i].startswith('X'):
            parts[i] = 'X%g' % (float(parts[i][1:]) + dx,)
        elif parts[i].startswith('Y'):
            parts[i] = 'Y%g' % (float(parts[i][1:]) + dy,)
    return ' '.join(parts)

def e_to_ab_line(line):
    parts = line.split()
    for i in range(len(parts)):
        if parts[i].startswith('E'):
            parts[i] = 'A%s B%s' % (parts[i][1:], parts[i][1:])
            break
    return ' '.join(parts)

def offset_movement(lines, dx, dy):
    for i in range(len(lines)):
        if lines[i].startswith('G1') or lines[i].startswith('G0'):
            lines[i] = offset_gcode_line(lines[i], dx, dy)
    return lines

def main(argv):
    # TODO arg parsing
    input_file, output_file = argv
    lines = open(input_file).read().splitlines()
    new_start, other_lines = replace_start_code(lines)
    with file(output_file, 'w') as output:
        output.write('\n'.join(new_start))
        output.write('\n')

        for line in other_lines:
            if line.startswith('G'):
                line = e_to_ab_line(line)
            output.write(line + '\n')

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))