text:
import fcntl
import os
import time
import threading

from binaryninja import PluginCommand, HighlightStandardColor, log, BackgroundTaskThread
from binaryninja.interaction import (
    get_open_filename_input,
    get_directory_name_input,
    get_choice_input,
)
import binaryninja.enums as enums

blue = HighlightStandardColor.BlueHighlightColor
black = HighlightStandardColor.BlackHighlightColor
white = HighlightStandardColor.WhiteHighlightColor
clear = HighlightStandardColor.NoHighlightColor
# renew interval
interval = 3

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class TraceVisualizer:
    __metaclass__ = Singleton

    def __init__(self, view, workspace, base=0x0, live=False):
        self.view = view
        self.workspace = workspace
        self.base = base
        # highlighted addresses
        self.highlighted = set()
        # covered basic blocks
        self.cov_bb = set()
        # comments inserted
        self.cov_comments = set()
        self.current_function = None
        self.live_update = live

    def visualize(self):
        """
        Given a Manticore workspace, or trace file, highlight the basic blocks.
        """
        if os.path.isfile(self.workspace):
            t = threading.Thread(target=self.highlight_from_file, args=(self.workspace,))
        elif os.path.isdir(self.workspace):
            t = threading.Thread(target=self.highlight_from_dir, args=(self.workspace,))
        t.start()

    def highlight_from_file(self, tracefile):
        while True:
            self.process_trace(tracefile)
            if not self.live_update:
                break
            time.sleep(interval)

    def highlight_from_dir(self, workspace_dir):
        while True:
            for f in os.listdir(workspace_dir):
                if f.endswith("trace"):
                    self.process_trace(os.path.join(workspace_dir, f))
            if not self.live_update:
                break
            time.sleep(interval)

    def process_trace(self, tracefile):
        trace_addr = set()
        with open(tracefile, "r") as f:
            for line in f:
                trace_addr.add(int(line.strip(), 0) - self.base)

            for addr in trace_addr - self.highlighted:
                self.highlight_addr(addr, blue)

    def highlight_addr(self, addr, hl):
        blocks = self.view.get_basic_blocks_at(addr)
        if blocks:
            blocks[0].set_user_highlight(hl)
            if self.live_update and blocks[0].function != self.current_function:
                self.current_function = blocks[0].function
                self.view.file.navigate(self.view.file.view, blocks[0].start)
            self.highlighted.add(addr)
            self.cov_bb.add(blocks[0].start)
            if self.live_update:
                blocks[0].function.set_auto_instr_highlight(addr, white)
                time.sleep(0.1)
                blocks[0].function.set_auto_instr_highlight(addr, clear)

    def highlight_block(self, addr, hl):
        blocks = self.view.get_basic_blocks_at(addr)
        for b in blocks:
            b.set_user_highlight(hl)

    def set_comment_at_xref(self, xref, comment):
        try:
            op = xref.function.get_lifted_il_at(xref.address).operation
        except IndexError:
            w = "ManticoreTrace: Could not lookup " + hex(xref.address)
            w += " address for function " + str(xref.function)
            log.log_warn(w)
            return
        if not (
            op == enums.LowLevelILOperation.LLIL_CALL
            or op == enums.LowLevelILOperation.LLIL_JUMP
            or op == enums.LowLevelILOperation.LLIL_JUMP_TO
            or op == enums.LowLevelILOperation.LLIL_SYSCALL
            or op == enums.LowLevelILOperation.LLIL_GOTO
        ):
            return
        self.cov_comments.add((xref.function, xref.address))
        xref.function.set_comment_at(xref.address, comment)

    def clear_stats(self):
        self.highlighted.clear()
        self.cov_bb.clear()
        for fun, addr in self.cov_comments:
            fun.set_comment_at(addr, None)

class CoverageHelper(BackgroundTaskThread):
    def __init__(self, view, tv):
        self.tv = tv
        self.view = view
        BackgroundTaskThread.__init__(self, "Calculating Coverage", True)

    def run(self):
        # function cumulative bb coverage
        # key: function address
        # values: [total basic blocks covered, xrefs to function]
        fun_cov = {f.start: [0, 0] for f in self.view.functions}
        fun_xrefs = sorted(
            [(f, self.view.get_code_refs(f.start)) for f in self.view.functions],
            key=lambda x: len(x[1]),
        )

        for f, xrefs in fun_xrefs:
            if not f.basic_blocks:
                continue
            cov = len(
                (set([b.start for b in f.basic_blocks]).intersection(self.tv.cov_bb))
            ) / float(len(set(f.basic_blocks)))
            fun_cov[f.start][0] += cov
            for xref_f in xrefs:
                fun_cov[xref_f.function.start][0] += cov
                fun_cov[xref_f.function.start][1] += 1

        for f, xrefs in fun_xrefs:
            cov = str((fun_cov[f.start][0] * 100.0) / (fun_cov[f.start][1] + 1))
            cov += "% cumulative BB coverage"
            f.set_comment(f.start, "Function Stats: \n" + cov)
            for xref in xrefs:
                self.tv.set_comment_at_xref(xref, cov)

def get_workspace():
    choice = get_choice_input("Select Trace Type", "Input", ["Trace File", "Manticore Workspace"])
    if choice == 0:
        workspace = get_open_filename_input("Trace File")
    else:
        workspace = get_directory_name_input("Workspace Directory")
    return workspace

def viz_trace(view):
    """
    Given a Manticore trace file, highlight the basic blocks.
    """
    tv = TraceVisualizer(view, None)
    if tv.workspace is None:
        tv.workspace = get_workspace()
    tv.visualize()

def viz_live_trace(view):
    """
    Given a Manticore trace file, highlight the basic blocks.
    """
    tv = TraceVisualizer(view, None, live=True)
    if tv.workspace is None:
        tv.workspace = get_workspace()
    # update due to singleton in case we are called after a clear
    tv.live_update = True
    tv.visualize()

def get_coverage(view):
    tv = TraceVisualizer(view, None, live=False)
    if tv.workspace is None:
        tv.workspace = get_workspace()
    tv.visualize()
    c = CoverageHelper(view, tv)
    c.start()

def clear_all(view):
    tv = TraceVisualizer(view, None)
    for addr in tv.highlighted:
        tv.highlight_block(addr, clear)
    tv.clear_stats()
    tv.workspace = None
    tv.live_update = False

PluginCommand.register(
    "ManticoreTrace: Highlight", "Highlight Manticore Execution Trace", viz_trace
)
PluginCommand.register(
    "ManticoreTrace: BB Coverage", "Compute cumulative BB coverage for each function ", get_coverage
)
PluginCommand.register(
    "ManticoreTrace: Live Highlight",
    "Highlight Manticore Execution Trace at Real-Time",
    viz_live_trace,
)
PluginCommand.register("ManticoreTrace: Clear", "Clear Manticore Trace Highlight", clear_all)


text:
.. _fabric-deployment:

Deploying with Fabric
=====================

`Fabric`_ is a tool for Python similar to Makefiles but with the ability
to execute commands on a remote server.  In combination with a properly
set up Python package (:ref:`larger-applications`) and a good concept for
configurations (:ref:`config`) it is very easy to deploy Flask
applications to external servers.

Before we get started, here a quick checklist of things we have to ensure
upfront:

-   Fabric 1.0 has to be installed locally.  This tutorial assumes the
    latest version of Fabric.
-   The application already has to be a package and requires a working
    `setup.py` file (:ref:`distribute-deployment`).
-   In the following example we are using `mod_wsgi` for the remote
    servers.  You can of course use your own favourite server there, but
    for this example we chose Apache + `mod_wsgi` because it's very easy
    to setup and has a simple way to reload applications without root
    access.

Creating the first Fabfile
--------------------------

A fabfile is what controls what Fabric executes.  It is named `fabfile.py`
and executed by the `fab` command.  All the functions defined in that file
will show up as `fab` subcommands.  They are executed on one or more
hosts.  These hosts can be defined either in the fabfile or on the command
line.  In this case we will add them to the fabfile.

This is a basic first example that has the ability to upload the current
sourcecode to the server and install it into a pre-existing
virtual environment::

    from fabric.api import *

    # the user to use for the remote commands
    env.user = 'appuser'
    # the servers where the commands are executed
    env.hosts = ['server1.example.com', 'server2.example.com']

    def pack():
        # create a new source distribution as tarball
        local('python setup.py sdist --formats=gztar', capture=False)

    def deploy():
        # figure out the release name and version
        dist = local('python setup.py --fullname', capture=True).strip()
        # upload the source tarball to the temporary folder on the server
        put('dist/%s.tar.gz' % dist, '/tmp/yourapplication.tar.gz')
        # create a place where we can unzip the tarball, then enter
        # that directory and unzip it
        run('mkdir /tmp/yourapplication')
        with cd('/tmp/yourapplication'):
            run('tar xzf /tmp/yourapplication.tar.gz')
            # now setup the package with our virtual environment's
            # python interpreter
            run('/var/www/yourapplication/env/bin/python setup.py install')
        # now that all is set up, delete the folder again
        run('rm -rf /tmp/yourapplication /tmp/yourapplication.tar.gz')
        # and finally touch the .wsgi file so that mod_wsgi triggers
        # a reload of the application
        run('touch /var/www/yourapplication.wsgi')

The example above is well documented and should be straightforward.  Here
a recap of the most common commands fabric provides:

-   `run` - executes a command on a remote server
-   `local` - executes a command on the local machine
-   `put` - uploads a file to the remote server
-   `cd` - changes the directory on the serverside.  This has to be used
    in combination with the `with` statement.

Running Fabfiles
----------------

Now how do you execute that fabfile?  You use the `fab` command.  To
deploy the current version of the code on the remote server you would use
this command::

    $ fab pack deploy

However this requires that our server already has the
``/var/www/yourapplication`` folder created and
``/var/www/yourapplication/env`` to be a virtual environment.  Furthermore
are we not creating the configuration or `.wsgi` file on the server.  So
how do we bootstrap a new server into our infrastructure?

This now depends on the number of servers we want to set up.  If we just
have one application server (which the majority of applications will
have), creating a command in the fabfile for this is overkill.  But
obviously you can do that.  In that case you would probably call it
`setup` or `bootstrap` and then pass the servername explicitly on the
command line::

    $ fab -H newserver.example.com bootstrap

To setup a new server you would roughly do these steps:

1.  Create the directory structure in ``/var/www``::

        $ mkdir /var/www/yourapplication
        $ cd /var/www/yourapplication
        $ virtualenv --distribute env

2.  Upload a new `application.wsgi` file to the server and the
    configuration file for the application (eg: `application.cfg`)

3.  Create a new Apache config for `yourapplication` and activate it.
    Make sure to activate watching for changes of the `.wsgi` file so
    that we can automatically reload the application by touching it.
    (See :ref:`mod_wsgi-deployment` for more information)

So now the question is, where do the `application.wsgi` and
`application.cfg` files come from?

The WSGI File
-------------

The WSGI file has to import the application and also to set an environment
variable so that the application knows where to look for the config.  This
is a short example that does exactly that::

    import os
    os.environ['YOURAPPLICATION_CONFIG'] = '/var/www/yourapplication/application.cfg'
    from yourapplication import app

The application itself then has to initialize itself like this to look for
the config at that environment variable::

    app = Flask(__name__)
    app.config.from_object('yourapplication.default_config')
    app.config.from_envvar('YOURAPPLICATION_CONFIG')

This approach is explained in detail in the :ref:`config` section of the
documentation.

The Configuration File
----------------------

Now as mentioned above, the application will find the correct
configuration file by looking up the `YOURAPPLICATION_CONFIG` environment
variable.  So we have to put the configuration in a place where the
application will able to find it.  Configuration files have the unfriendly
quality of being different on all computers, so you do not version them
usually.

A popular approach is to store configuration files for different servers
in a separate version control repository and check them out on all
servers.  Then symlink the file that is active for the server into the
location where it's expected (eg: ``/var/www/yourapplication``).

Either way, in our case here we only expect one or two servers and we can
upload them ahead of time by hand.

First Deployment
----------------

Now we can do our first deployment.  We have set up the servers so that
they have their virtual environments and activated apache configs.  Now we
can pack up the application and deploy it::

    $ fab pack deploy

Fabric will now connect to all servers and run the commands as written
down in the fabfile.  First it will execute pack so that we have our
tarball ready and then it will execute deploy and upload the source code
to all servers and install it there.  Thanks to the `setup.py` file we
will automatically pull in the required libraries into our virtual
environment.

Next Steps
----------

From that point onwards there is so much that can be done to make
deployment actually fun:

-   Create a `bootstrap` command that initializes new servers.  It could
    initialize a new virtual environment, setup apache appropriately etc.
-   Put configuration files into a separate version control repository
    and symlink the active configs into place.
-   You could also put your application code into a repository and check
    out the latest version on the server and then install.  That way you
    can also easily go back to older versions.
-   hook in testing functionality so that you can deploy to an external
    server and run the testsuite.

Working with Fabric is fun and you will notice that it's quite magical to
type ``fab deploy`` and see your application being deployed automatically
to one or more remote servers.

.. _Fabric: http://www.fabfile.org/

redpajama_set_name: RedPajamaGithub


text:
package com.intel.analytics.zoo.pipeline.api.keras.layers

import com.intel.analytics.bigdl.nn.abstractnn.AbstractModule
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.Shape
import com.intel.analytics.zoo.pipeline.api.keras.models.Sequential
import com.intel.analytics.zoo.pipeline.api.keras.serializer.ModuleSerializationTest

class MaxoutDenseSpec extends KerasBaseSpec {

  def weightConverter(data: Array[Tensor[Float]]): Array[Tensor[Float]] = {
    val out = new Array[Tensor[Float]](data.length)
    out(0) = Tensor(12, 32)
    val weight = out.head.storage().array()
    var index = 0
    for (i <- 1 to 4) {
      val sliceW = data(0).select(1, i).t.clone().storage().array()
      System.arraycopy(sliceW, 0, weight, index, sliceW.size)
      index += sliceW.size
    }
    if (data.length > 1) {
      out(1) = data(1)
    }
    out
  }

  "MaxoutDense" should "be the same as Keras" in {
    val kerasCode =
      """
        |input_tensor = Input(shape=[12])
        |input = np.random.random([4, 12])
        |output_tensor = MaxoutDense(8)(input_tensor)
        |model = Model(input=input_tensor, output=output_tensor)
      """.stripMargin
    val seq = Sequential[Float]()
    val layer = MaxoutDense[Float](8, inputShape = Shape(12))
    seq.add(layer)
    checkOutputAndGrad(seq.asInstanceOf[AbstractModule[Tensor[Float], Tensor[Float], Float]],
      kerasCode, weightConverter)
  }

  "MaxoutDense without bias" should "be the same as Keras" in {
    val kerasCode =
      """
        |input_tensor = Input(shape=[12])
        |input = np.random.random([4, 12])
        |output_tensor = MaxoutDense(8, bias=False)(input_tensor)
        |model = Model(input=input_tensor, output=output_tensor)
      """.stripMargin
    val seq = Sequential[Float]()
    val layer = MaxoutDense[Float](8, bias = false, inputShape = Shape(12))
    seq.add(layer)
    checkOutputAndGrad(seq.asInstanceOf[AbstractModule[Tensor[Float], Tensor[Float], Float]],
      kerasCode, weightConverter)
  }

}

class MaxoutDenseSerialTest extends ModuleSerializationTest {
  override def test(): Unit = {
    val layer = MaxoutDense[Float](8, inputShape = Shape(12))
    layer.build(Shape(3, 12))
    val input = Tensor[Float](3, 12).rand()
    runSerializationTest(layer, input)
  }
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.search_engines;

import org.chromium.base.CalledByNative;
import org.chromium.base.ObserverList;
import org.chromium.base.ThreadUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Android wrapper of the TemplateUrlService which provides access from the Java
 * layer.
 *
 * Only usable from the UI thread as it's primary purpose is for supporting the Android
 * preferences UI.
 *
 * See chrome/browser/search_engines/template_url_service.h for more details.
 */
public class TemplateUrlService {

    /**
     * This listener will be notified when template url service is done loading.
     */
    public interface LoadListener {
        public abstract void onTemplateUrlServiceLoaded();
    }

    /**
     * Represents search engine with its index.
     */
    public static class TemplateUrl {
        private final int mIndex;
        private final String mShortName;
        private final String mKeyword;

        @CalledByNative("TemplateUrl")
        public static TemplateUrl create(int id, String shortName, String keyword) {
            return new TemplateUrl(id, shortName, keyword);
        }

        public TemplateUrl(int index, String shortName, String keyword) {
            mIndex = index;
            mShortName = shortName;
            mKeyword = keyword;
        }

        public int getIndex() {
            return mIndex;
        }

        public String getShortName() {
            return mShortName;
        }

        public String getKeyword() {
            return mKeyword;
        }
    }

    private static TemplateUrlService sService;

    public static TemplateUrlService getInstance() {
        ThreadUtils.assertOnUiThread();
        if (sService == null) {
            sService = new TemplateUrlService();
        }
        return sService;
    }

    private final long mNativeTemplateUrlServiceAndroid;
    private final ObserverList<LoadListener> mLoadListeners = new ObserverList<LoadListener>();

    private TemplateUrlService() {
        // Note that this technically leaks the native object, however, TemlateUrlService
        // is a singleton that lives forever and there's no clean shutdown of Chrome on Android
        mNativeTemplateUrlServiceAndroid = nativeInit();
    }

    public boolean isLoaded() {
        ThreadUtils.assertOnUiThread();
        return nativeIsLoaded(mNativeTemplateUrlServiceAndroid);
    }

    public void load() {
        ThreadUtils.assertOnUiThread();
        nativeLoad(mNativeTemplateUrlServiceAndroid);
    }

    /**
     * Get the collection of localized search engines.
     */
    public List<TemplateUrl> getLocalizedSearchEngines() {
        ThreadUtils.assertOnUiThread();
        int templateUrlCount = nativeGetTemplateUrlCount(mNativeTemplateUrlServiceAndroid);
        List<TemplateUrl> templateUrls = new ArrayList<TemplateUrl>(templateUrlCount);
        for (int i = 0; i < templateUrlCount; i++) {
            TemplateUrl templateUrl = nativeGetPrepopulatedTemplateUrlAt(
                    mNativeTemplateUrlServiceAndroid, i);
            if (templateUrl != null) {
                templateUrls.add(templateUrl);
            }
        }
        return templateUrls;
    }

    /**
     * Called from native when template URL service is done loading.
     */
    @CalledByNative
    private void templateUrlServiceLoaded() {
        ThreadUtils.assertOnUiThread();
        for (LoadListener listener : mLoadListeners) {
            listener.onTemplateUrlServiceLoaded();
        }
    }

    /**
     * @return The default search engine index (e.g., 0, 1, 2,...).
     */
    public int getDefaultSearchEngineIndex() {
        ThreadUtils.assertOnUiThread();
        return nativeGetDefaultSearchProvider(mNativeTemplateUrlServiceAndroid);
    }

    /**
     * @return {@link TemplateUrlService.TemplateUrl} for the default search engine.
     */
    public TemplateUrl getDefaultSearchEngineTemplateUrl() {
        if (!isLoaded()) return null;

        int defaultSearchEngineIndex = getDefaultSearchEngineIndex();
        if (defaultSearchEngineIndex == -1) return null;

        assert defaultSearchEngineIndex >= 0;
        assert defaultSearchEngineIndex < nativeGetTemplateUrlCount(
                mNativeTemplateUrlServiceAndroid);

        return nativeGetPrepopulatedTemplateUrlAt(
                mNativeTemplateUrlServiceAndroid, defaultSearchEngineIndex);
    }

    public void setSearchEngine(int selectedIndex) {
        ThreadUtils.assertOnUiThread();
        nativeSetUserSelectedDefaultSearchProvider(mNativeTemplateUrlServiceAndroid, selectedIndex);
    }

    public boolean isSearchProviderManaged() {
        return nativeIsSearchProviderManaged(mNativeTemplateUrlServiceAndroid);
    }

    /**
     * @return Whether or not the default search engine has search by image support.
     */
    public boolean isSearchByImageAvailable() {
        ThreadUtils.assertOnUiThread();
        return nativeIsSearchByImageAvailable(mNativeTemplateUrlServiceAndroid);
    }

    /**
     * @return Whether the default configured search engine is for a Google property.
     */
    public boolean isDefaultSearchEngineGoogle() {
        return nativeIsDefaultSearchEngineGoogle(mNativeTemplateUrlServiceAndroid);
    }

    /**
     * Registers a listener for the callback that indicates that the
     * TemplateURLService has loaded.
     */
    public void registerLoadListener(LoadListener listener) {
        ThreadUtils.assertOnUiThread();
        boolean added = mLoadListeners.addObserver(listener);
        assert added;
    }

    /**
     * Unregisters a listener for the callback that indicates that the
     * TemplateURLService has loaded.
     */
    public void unregisterLoadListener(LoadListener listener) {
        ThreadUtils.assertOnUiThread();
        boolean removed = mLoadListeners.removeObserver(listener);
        assert removed;
    }

    /**
     * Finds the default search engine for the default provider and returns the url query
     * {@link String} for {@code query}.
     * @param query The {@link String} that represents the text query the search url should
     *              represent.
     * @return      A {@link String} that contains the url of the default search engine with
     *              {@code query} inserted as the search parameter.
     */
    public String getUrlForSearchQuery(String query) {
        return nativeGetUrlForSearchQuery(mNativeTemplateUrlServiceAndroid, query);
    }

    /**
     * Finds the default search engine for the default provider and returns the url query
     * {@link String} for {@code query} with voice input source param set.
     * @param query The {@link String} that represents the text query the search url should
     *              represent.
     * @return      A {@link String} that contains the url of the default search engine with
     *              {@code query} inserted as the search parameter and voice input source param set.
     */
    public String getUrlForVoiceSearchQuery(String query) {
        return nativeGetUrlForVoiceSearchQuery(mNativeTemplateUrlServiceAndroid, query);
    }

    /**
     * Replaces the search terms from {@code query} in {@code url}.
     * @param query The {@link String} that represents the text query that should replace the
     *              existing query in {@code url}.
     * @param url   The {@link String} that contains the search url with another search query that
     *              will be replaced with {@code query}.
     * @return      A new version of {@code url} with the search term replaced with {@code query}.
     */
    public String replaceSearchTermsInUrl(String query, String url) {
        return nativeReplaceSearchTermsInUrl(mNativeTemplateUrlServiceAndroid, query, url);
    }

    /**
     * Finds the default search engine for the default provider and returns the url query
     * {@link String} for {@code query} with the contextual search version param set.
     * @return      A {@link String} that contains the url of the default search engine with
     *              {@code query} inserted as the search parameter and contextual search param set.
     */
    public String getUrlForContextualSearchQuery(String query) {
        return nativeGetUrlForContextualSearchQuery(mNativeTemplateUrlServiceAndroid, query);
    }

    private native long nativeInit();
    private native void nativeLoad(long nativeTemplateUrlServiceAndroid);
    private native boolean nativeIsLoaded(long nativeTemplateUrlServiceAndroid);
    private native int nativeGetTemplateUrlCount(long nativeTemplateUrlServiceAndroid);
    private native TemplateUrl nativeGetPrepopulatedTemplateUrlAt(
            long nativeTemplateUrlServiceAndroid, int i);
    private native void nativeSetUserSelectedDefaultSearchProvider(
            long nativeTemplateUrlServiceAndroid, int selectedIndex);
    private native int nativeGetDefaultSearchProvider(long nativeTemplateUrlServiceAndroid);
    private native boolean nativeIsSearchProviderManaged(long nativeTemplateUrlServiceAndroid);
    private native boolean nativeIsSearchByImageAvailable(long nativeTemplateUrlServiceAndroid);
    private native boolean nativeIsDefaultSearchEngineGoogle(long nativeTemplateUrlServiceAndroid);
    private native String nativeGetUrlForSearchQuery(long nativeTemplateUrlServiceAndroid,
            String query);
    private native String nativeGetUrlForVoiceSearchQuery(long nativeTemplateUrlServiceAndroid,
            String query);
    private native String nativeReplaceSearchTermsInUrl(long nativeTemplateUrlServiceAndroid,
            String query, String currentUrl);
    private native String nativeGetUrlForContextualSearchQuery(long nativeTemplateUrlServiceAndroid,
            String query);
}


text:
package water

import (
	"net"
	"testing"
	"time"

	"github.com/songgao/water/waterutil"
)

const BUFFERSIZE = 1522

func startRead(ch chan<- []byte, ifce *Interface) {
	go func() {
		for {
			buffer := make([]byte, BUFFERSIZE)
			n, err := ifce.Read(buffer)
			if err == nil {
				buffer = buffer[:n:n]
				ch <- buffer
			}
		}
	}()
}

func TestBroadcast(t *testing.T) {
	var (
		self = net.IPv4(10, 0, 42, 1)
		mask = net.IPv4Mask(255, 255, 255, 0)
		brd  = net.IPv4(10, 0, 42, 255)
	)

	ifce, err := NewTAP("test")
	if err != nil {
		t.Fatalf("creating TAP error: %v\n", err)
	}

	setupIfce(t, net.IPNet{IP: self, Mask: mask}, ifce.Name())
	startBroadcast(t, brd)

	dataCh := make(chan []byte, 8)
	startRead(dataCh, ifce)

	timeout := time.NewTimer(8 * time.Second).C

readFrame:
	for {
		select {
		case buffer := <-dataCh:
			ethertype := waterutil.MACEthertype(buffer)
			if ethertype != waterutil.IPv4 {
				continue readFrame
			}
			if !waterutil.IsBroadcast(waterutil.MACDestination(buffer)) {
				continue readFrame
			}
			packet := waterutil.MACPayload(buffer)
			if !waterutil.IsIPv4(packet) {
				continue readFrame
			}
			if !waterutil.IPv4Source(packet).Equal(self) {
				continue readFrame
			}
			if !waterutil.IPv4Destination(packet).Equal(brd) {
				continue readFrame
			}
			if waterutil.IPv4Protocol(packet) != waterutil.ICMP {
				continue readFrame
			}
			t.Logf("received broadcast frame: %#v\n", buffer)
			break readFrame
		case <-timeout:
			t.Fatal("Waiting for broadcast packet timeout")
		}
	}
}


text:
<?php namespace Vsch\Generators\Commands;

use Vsch\Generators\Generators\TestGenerator;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Vsch\Generators\GeneratorsServiceProvider;

class TestGeneratorCommand extends BaseGeneratorCommand {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'generate:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate a PHPUnit test class.';

    /**
     * Create a new command instance.
     *
     * @param TestGenerator $generator
     */
    public function __construct(TestGenerator $generator)
    {
        parent::__construct();

        $this->generator = $generator;
    }

    /**
     * Get the path to the file that should be generated.
     *
     * @return string
     */
    protected function getPath()
    {
       return parent::getSrcPath(self::PATH_TESTS, studly_case($this->argument('name')) . '.php');
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            array('name', InputArgument::REQUIRED, 'Name of the test to generate.'),
        );
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return $this->mergeOptions(array(
           array('path', null, InputOption::VALUE_OPTIONAL, 'Path to tests directory.', ''),
           array('template', null, InputOption::VALUE_OPTIONAL, 'Path to template.', GeneratorsServiceProvider::getTemplatePath('test.txt')),
        ));
    }

}


text:
class Tree;
class TreeDraw;
class HzSection;
class HzSections;
class SettingsInitializer;

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

class TimeSeriesDrawSettings : public acmacs::settings::v1::object
{
 public:
    using acmacs::settings::v1::object::object;

    acmacs::settings::v1::field<std::string>       begin{this, "begin", ""};
    acmacs::settings::v1::field<std::string>       end{this, "end", ""};
    acmacs::settings::v1::field<double>            label_size{this, "label_size", 8};
    acmacs::settings::v1::field<acmacs::TextStyle> label_style{this, "label_style", acmacs::TextStyle{}};
    acmacs::settings::v1::field<double>            month_year_to_timeseries_gap{this, "month_year_to_timeseries_gap", 2};
    acmacs::settings::v1::field<Color>             month_separator_color{this, "month_separator_color", BLACK};
    acmacs::settings::v1::field<double>            month_separator_width{this, "month_separator_width", 0.5};
    acmacs::settings::v1::field<double>            dash_width{this, "dash_width", 0.5};
    acmacs::settings::v1::field<double>            dash_line_width{this, "dash_line_width", 1};

    void remove_for_tree_settings();

}; // class TimeSeriesDrawSettings

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

class TimeSeriesDraw
{
 public:
    TimeSeriesDraw(acmacs::surface::Surface& aSurface, Tree& aTree, const TreeDraw& aTreeDraw, HzSections& aHzSections, TimeSeriesDrawSettings& aSettings)
        : mSurface(aSurface), mTree(aTree), mTreeDraw(aTreeDraw), mSettings(aSettings), mHzSections(aHzSections), mTreeMode(false) {}

    void prepare();
    void draw();
    void draw_color_scale(const std::map<std::string, Color, std::less<>>& aTrackedAntigenColorByMonth);

    const acmacs::Size& size() const { return mSurface.viewport().size; }
    acmacs::PointCoordinates origin_in_parent() const { return mSurface.origin_in_parent(); }

    void init_settings(const SettingsInitializer& settings_initilizer);
    acmacs::surface::Surface& surface() { return mSurface; }
    void tree_mode(bool aTreeMode) { mTreeMode = aTreeMode; }
    // void hide_hz_section_labels_in_time_series();

    std::vector<std::string> all_months() const;

 private:
    acmacs::surface::Surface& mSurface;
    Tree& mTree;
    const TreeDraw& mTreeDraw;
    TimeSeriesDrawSettings& mSettings;
    HzSections& mHzSections;
    size_t mNumberOfMonths;
    bool mTreeMode;

    void draw_labels(double month_width);
    void draw_labels_at_side(const acmacs::PointCoordinates& aOrigin, double month_width, double month_max_height);
    void draw_month_separators(double month_width);
    void draw_dashes(double month_width);
    void draw_hz_section_lines();
    void draw_hz_section_label(size_t aSectionIndex, double aY);

}; // class TimeSeriesDraw

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:


text:
using System;
using System.Collections.Generic;
using System.Threading;
using eidss.model.Core;
using eidss.model.Enums;
using eidss.model.Reports.Common;

namespace eidss.model.Reports.KZ
{
    [Serializable]
    public class DiagnosticInvestigationModel : BaseIntervalModel
    {
        public DiagnosticInvestigationModel()
        {
            RegionFilter = new RegionModel();
        }

        public DiagnosticInvestigationModel
            (string lang, DateTime startDate, DateTime endDate, long? regionId,
             string[] checkedDiagnosis, string[] checkedSpecies, string[] checkedInvestigationTypes, bool useArchive)
            : base(lang, startDate, endDate, useArchive)
        {
            CheckedInvestigationTypes = checkedInvestigationTypes;
            CheckedDiagnosis = checkedDiagnosis;
            CheckedSpecies = checkedSpecies;
            RegionFilter = new RegionModel(regionId);
        }

        [LocalizedDisplayName("strInvestionType")]
        public string[] CheckedInvestigationTypes { get; set; }

        [LocalizedDisplayName("DiagnosisName")]
        public string[] CheckedDiagnosis { get; set; }

        [LocalizedDisplayName("idfsSpeciesType")]
        public string[] CheckedSpecies { get; set; }

        public RegionModel RegionFilter { get; set; }

        public List<SelectListItemSurrogate> InvestigationTypeList
        {
            get
            {
                return FilterHelper.GetKzFilterList(Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName,
                                                    ReportFilterType.DiagnosticInvestigationType);
            }
        }

        public List<SelectListItemSurrogate> DiagnosisList
        {
            get
            {
                return FilterHelper.GetKzFilterList(Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName,
                                                    ReportFilterType.DiagnosticInvestigationDiagnosis);
            }
        }

        public List<SelectListItemSurrogate> SpeciesList
        {
            get
            {
                return FilterHelper.GetKzFilterList(Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName,
                                                    ReportFilterType.DiagnosticInvestigationSpecies);
            }
        }
    }
}


text:
package org.apereo.cas.util.serialization;

import java.util.Collection;

/**
 * This is {@link ComponentSerializationPlan} that allows modules to register objects and classes
 * they wish to let the underlying engine serialize explicitly. Most specifically, this is used by
 * ticket registry backends such as Kryo that deal with serialized data before passing the object
 * onto memcached where explicit registration is required. The plan is passed to modules that do
 * have a need to register classes explicitly, and engines and libraries such as kryo can explicitly
 * ask the executing plan for all classes that they can handle and register in their own engine.
 *
 * @author Misagh Moayyed
 * @see ComponentSerializationPlanConfigurator
 * @since 5.2.0
 */
public interface ComponentSerializationPlan {

    /**
     * Register serializable class.
     *
     * @param clazz the clazz to register
     */
    void registerSerializableClass(Class clazz);

    /**
     * Register serializable class.
     *
     * @param clazz the clazz to register
     * @param order the order in which the class will be positioned in the registry of classes
     */
    void registerSerializableClass(Class clazz, Integer order);

    /**
     * Gets registered classes.
     *
     * @return the registered classes
     */
    Collection<Class> getRegisteredClasses();
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ComparatoreStanzePerNumeroAttrezzi</title>
<meta name="date" content="2015-06-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

it.uniroma3.diadia.ambienti

Class ComparatoreStanzePerNumeroAttrezzi

java.lang.Object

it.uniroma3.diadia.ambienti.ComparatoreStanzePerNumeroAttrezzi

All Implemented Interfaces:

java.util.Comparator<Stanza>

public class ComparatoreStanzePerNumeroAttrezzi
extends java.lang.Object
implements java.util.Comparator<Stanza>

Classe per l'ordinamento esterno di oggetti stanza

Version:

0.4

Author:

Lorenzo e Stefano

See Also:

Stanza

Constructor Summary

Constructors

Constructor and Description

ComparatoreStanzePerNumeroAttrezzi()

Method Summary

Methods

Modifier and Type
Method and Description

int
compare(Stanza s1,
       Stanza s2)

Metodo che si occupa di ordinare due stanze passate come parametro per
 numero di attrezzi contenuti.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface java.util.Comparator

equals

Constructor Detail

ComparatoreStanzePerNumeroAttrezzi

public ComparatoreStanzePerNumeroAttrezzi()

Method Detail

compare

public int compare(Stanza s1,
          Stanza s2)

Metodo che si occupa di ordinare due stanze passate come parametro per
 numero di attrezzi contenuti. A parità di attrezzi ordina per nome

Specified by:

compare in interface java.util.Comparator<Stanza>

Parameters:

s1 - Prima stanza

s2 - Seconda stanza

Returns:

intero negativo se l'oggetto s1 ha meno attrezzi, intero
         positivo altrimenti

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.apache.drill.categories;

/**
 * This is a category used to mark unit tests that test Drill Parquet support.
 */
public interface ParquetTest {
  /**
   * tag for JUnit5
   */
  String TAG = "parquet-test";
}


text:
<?php

namespace Redsys\Security\Authentication;

class AuthenticationFactory
{
    /**
     * @param string $name
     * @param string $key
     * @return AuthenticationInterface
     */
    public static function create($name, $key)
    {
        $className = str_replace(" ", "", mb_convert_case(str_replace("_", " ", $name), MB_CASE_TITLE));
        if ("AuthenticationFactory" === $className) {
            throw new \UnexpectedValueException('AuthenticationFactory is not a valid Authentication Class');
        }
        $fullClassName = sprintf('%s\%s', __NAMESPACE__, $className);
        if (!class_exists($fullClassName)) {
            throw new \UnexpectedValueException(
                sprintf('Class "%s" does not exist for given name "%s"', $fullClassName, $name)
            );
        }

        return new $fullClassName($key);
    }
}


text:
using UnityEngine;
using Debug = UnityEngine.Debug;

public class Game : MonoBehaviour {

	public static Register register;
	public static bool hasStarted;

	// Use this for initialization
	private void Start () {
		register = new Register();

		// Add mods

		PreInit();
		Init();
		PostInit();
		Debug.Log("Started");
		Debug.Log("Time Elapsed: " + Time.realtimeSinceStartup + " seconds");
		hasStarted = true;
	}

	// Update is called once per frame
	/*void Update () {

	}*/

	/// <summary>
	/// PreInit is to setup any sort of files/directories or really anything that the mod developer sees fit.
	/// </summary>
	private void PreInit() {
		// Base PreInit
		RegisterBlocks();
		RegisterItems();
		UpdateBlocks();

		foreach (IMod m in register.GetMods()) {
			m.PreInit();
		}
	}

	/// <summary>
	/// Init is to initialize blocks, setup mods, etc.
	/// </summary>
	private void Init() {
		// Base Init

		foreach (IMod m in register.GetMods()) {
			m.Init();
		}
	}

	/// <summary>
	/// PostInit is to clean anything up and to test _all_ functionality to prevent errors in game.
	/// </summary>
	private void PostInit() {
		// Base PostInit

		foreach (IMod m in register.GetMods()) {
			m.PostInit();
		}
	}

	private void RegisterBlocks() {
		Block grassBlock = new Block(false) {id = 0};
		register.AddBlock(grassBlock, 0);

		Block dirtBlock = new Block(false) {id = 1};
		register.AddBlock(dirtBlock, 1);

		Block stoneBlock = new Block(false) {id = 2};
		register.AddBlock(stoneBlock, 2);

		Block woodenPlanksBlock = new Block(false) {id = 3};
		register.AddBlock(woodenPlanksBlock, 3);

		Block woodBlock = new Block(false) {id = 4};
		register.AddBlock(woodBlock, 4);

		Block coalOre = new Block(false) {id = 5};
		register.AddBlock(coalOre, 5);

		Block glassBlock = new Block(false) {
			id = 6,
			hasTransparency = true
		};
		register.AddBlock(glassBlock, 6);
	}

	private void RegisterItems()
	{
		Item grassBlock = new Item
		{
			type = ItemType.Block,
			block = register.GetBlock(0),
			id = 0
		};
		register.AddItem(grassBlock);

		Item dirtBlock = new Item
		{
			type = ItemType.Block,
			block = register.GetBlock(1),
			id = 1
		};
		register.AddItem(dirtBlock);

		Item stoneBlock = new Item
		{
			type = ItemType.Block,
			block = register.GetBlock(2),
			id = 2
		};
		register.AddItem(stoneBlock);

		Item woodenPlanksBlock = new Item
		{
			type = ItemType.Block,
			block = register.GetBlock(3),
			id = 3
		};
		register.AddItem(woodenPlanksBlock);

		Item woodBlock = new Item
		{
			type = ItemType.Block,
			block = register.GetBlock(4),
			id = 4
		};
		register.AddItem(woodBlock);

		Item coalOre = new Item
		{
			type = ItemType.Block,
			block = register.GetBlock(5),
			id = 5
		};
		register.AddItem(coalOre);

		Item glassBlock = new Item
		{
			type = ItemType.Block,
			block = register.GetBlock(6),
			id = 6
		};
		register.AddItem(glassBlock);
	}

	// Run after RegisterBlocks and RegisterItems
	private void UpdateBlocks()
	{
		Block[] blocks = register.GetBlocks();
		foreach (Block block in blocks)
		{
			block.item = register.GetItem(block.id);
			register.AddBlock(block, block.id);
		}
	}
}


text:
package com.lachesis.support.objects.vo;

import java.util.Collection;

public interface SecurityContext {
	String getPrincipal();
	String getToken();
	String getTerminalIpAddress();
	Collection<String> getRoles();
	Collection<String> getPermissions();
}


text:
namespace Slang
{
    struct ManglingContext
    {
        ManglingContext(ASTBuilder* inAstBuilder):
            astBuilder(inAstBuilder)
        {
        }
        ASTBuilder* astBuilder;
        StringBuilder sb;
    };

    void emitRaw(
        ManglingContext*    context,
        char const*         text)
    {
        context->sb.append(text);
    }

    void emit(
        ManglingContext*    context,
        UInt                value)
    {
        context->sb.append(value);
    }

    void emit(
        ManglingContext*    context,
        String const&       value)
    {
        context->sb.append(value);
    }

    void emitNameImpl(ManglingContext* context, UnownedStringSlice str)
    {
        Index length = str.getLength();

        // If the name consists of only traditional "identifer characters"
        // (`[a-zA-Z_]`), then we want to emit it more or less directly.
        //
        bool allAllowed = true;
        for (auto c : str)
        {
            if (('a' <= c) && (c <= 'z'))
                continue;
            if (('A' <= c) && (c <= 'Z'))
                continue;
            if (('0' <= c) && (c <= '9'))
                continue;
            if (c == '_')
                continue;

            allAllowed = false;
            break;
        }
        if (allAllowed)
        {
            // We prefix the string with its byte length, so that
            // decoding doesn't have to worry about finding a terminator.
            //
            // Note: in this case `length` is the same as the number of
            // code points and the number of extended grapheme clusters,
            // since the entire name is within the ASCII subset.
            //
            emit(context, length);
            context->sb.append(str);
        }
        else
        {
            // Other names that aren't pure ASCII require escaping. We
            // will use a rather simple escaping scheme where the basic
            // ASCII alphanumeric code points go through unmodified,
            // and we use `_` as a kind of escape character.
            //
            StringBuilder encoded;

            // TODO: This loop probalby ought to be over code points
            // rather than bytes.
            //
            for (auto c : str)
            {
                if (('a' <= c) && (c <= 'z') || ('A' <= c) && (c <= 'Z') ||
                    ('0' <= c) && (c <= '9'))
                {
                    encoded.append(c);
                }
                else if (c == '_')
                {
                    encoded.append("_u");
                }
                else
                {
                    // Any byte that isn't within the allowed ranges
                    // we be turned into hex, prefixed with `_` and
                    // suffixed with `x`.
                    //
                    encoded.append("_");
                    encoded.append(uint32_t((unsigned char)c), 16);
                    encoded.appendChar('x');
                }
            }

            context->sb.append("R");
            emit(context, encoded.getLength());
            context->sb.append(encoded);
        }

        // TODO: This logic does not rule out consecutive underscores,
        // even though the GLSL target does not support consecutive underscores
        // (or leading underscores, IIRC) in user identifiers.
        //
        // Realistically, that is best dealt with as a quirk of tha particular
        // target, rather than adding complexity here.
    }

    void emitName(
        ManglingContext*    context,
        Name*               name)
    {
        String str = getText(name);
        emitNameImpl(context, str.getUnownedSlice());
    }

    void emitVal(
        ManglingContext*    context,
        Val*                val);

    void emitQualifiedName(
        ManglingContext*    context,
        DeclRef<Decl>       declRef);

    void emitSimpleIntVal(
        ManglingContext*    context,
        Val*                val)
    {
        if( auto constVal = as<ConstantIntVal>(val) )
        {
            auto cVal = constVal->value;
            if(cVal >= 0 && cVal <= 9 )
            {
                emit(context, (UInt)cVal);
                return;
            }
        }

        // Fallback:
        emitVal(context, val);
    }

    void emitBaseType(
        ManglingContext*    context,
        BaseType            baseType)
    {
        switch( baseType )
        {
        case BaseType::Void:    emitRaw(context, "V");  break;
        case BaseType::Bool:    emitRaw(context, "b");  break;
        case BaseType::Int8:    emitRaw(context, "c");  break;
        case BaseType::Int16:   emitRaw(context, "s");  break;
        case BaseType::Int:     emitRaw(context, "i");  break;
        case BaseType::Int64:   emitRaw(context, "I");  break;
        case BaseType::UInt8:   emitRaw(context, "C");  break;
        case BaseType::UInt16:  emitRaw(context, "S");  break;
        case BaseType::UInt:    emitRaw(context, "u");  break;
        case BaseType::UInt64:  emitRaw(context, "U");  break;
        case BaseType::Half:    emitRaw(context, "h");  break;
        case BaseType::Float:   emitRaw(context, "f");  break;
        case BaseType::Double:  emitRaw(context, "d");  break;
        case BaseType::UIntPtr: emitRaw(context, "up");  break;
        case BaseType::IntPtr:  emitRaw(context, "ip");  break;
            break;

        default:
            SLANG_UNEXPECTED("unimplemented case in mangling");
            break;
        }
    }

    void emitType(
        ManglingContext*    context,
        Type*               type)
    {
        // TODO: actually implement this bit...

        if( auto basicType = dynamicCast<BasicExpressionType>(type) )
        {
            emitBaseType(context, basicType->baseType);
        }
        else if( auto vecType = dynamicCast<VectorExpressionType>(type) )
        {
            emitRaw(context, "v");
            emitSimpleIntVal(context, vecType->elementCount);
            emitType(context, vecType->elementType);
        }
        else if( auto matType = dynamicCast<MatrixExpressionType>(type) )
        {
            emitRaw(context, "m");
            emitSimpleIntVal(context, matType->getRowCount());
            emitRaw(context, "x");
            emitSimpleIntVal(context, matType->getColumnCount());
            emitType(context, matType->getElementType());
        }
        else if( auto namedType = dynamicCast<NamedExpressionType>(type) )
        {
            emitType(context, getType(context->astBuilder, namedType->declRef));
        }
        else if( auto declRefType = dynamicCast<DeclRefType>(type) )
        {
            emitQualifiedName(context, declRefType->declRef);
        }
        else if (auto arrType = dynamicCast<ArrayExpressionType>(type))
        {
            emitRaw(context, "a");
            emitSimpleIntVal(context, arrType->arrayLength);
            emitType(context, arrType->baseType);
        }
        else if( auto taggedUnionType = dynamicCast<TaggedUnionType>(type) )
        {
            emitRaw(context, "u");
            for( auto caseType : taggedUnionType->caseTypes )
            {
                emitType(context, caseType);
            }
            emitRaw(context, "U");
        }
        else if( auto thisType = dynamicCast<ThisType>(type) )
        {
            emitRaw(context, "t");
            emitQualifiedName(context, thisType->interfaceDeclRef);
        }
        else if (auto errorType = dynamicCast<ErrorType>(type))
        {
            emitRaw(context, "E");
        }
        else
        {
            SLANG_UNEXPECTED("unimplemented case in mangling");
        }
    }

    void emitVal(
        ManglingContext*    context,
        Val*                val)
    {
        if( auto type = dynamicCast<Type>(val) )
        {
            emitType(context, type);
        }
        else if( auto witness = dynamicCast<Witness>(val) )
        {
            // We don't emit witnesses as part of a mangled
            // name, because the way that the front-end
            // arrived at the witness is not important;
            // what matters is that the type constraint
            // was satisfied.
            //
            // TODO: make sure we can't get name collisions
            // between specializations of declarations
            // with the same numbers of generic parameters,
            // but different constraints. We might have
            // to mangle in the constraints even when
            // the whole thing is specialized...
        }
        else if( auto genericParamIntVal = dynamicCast<GenericParamIntVal>(val) )
        {
            // TODO: we shouldn't be including the names of generic parameters
            // anywhere in mangled names, since changing parameter names
            // shouldn't break binary compatibility.
            //
            // The right solution in the long term is for generic parameters
            // (both types and values) to be mangled in terms of their
            // "depth" (how many outer generics) and "index" (which
            // parameter are they at the specified depth).
            emitRaw(context, "K");
            emitName(context, genericParamIntVal->declRef.getName());
        }
        else if( auto constantIntVal = dynamicCast<ConstantIntVal>(val) )
        {
            // TODO: need to figure out what prefix/suffix is needed
            // to allow demangling later.
            emitRaw(context, "k");
            emit(context, (UInt) constantIntVal->value);
        }
        else
        {
            SLANG_UNEXPECTED("unimplemented case in mangling");
        }
    }

    void emitQualifiedName(
        ManglingContext*    context,
        DeclRef<Decl>       declRef)
    {
        auto parentDeclRef = declRef.getParent();
        auto parentGenericDeclRef = parentDeclRef.as<GenericDecl>();
        if( parentDeclRef )
        {
            emitQualifiedName(context, parentDeclRef);
        }

        // A generic declaration is kind of a pseudo-declaration
        // as far as the user is concerned; so we don't want
        // to emit its name.
        if(auto genericDeclRef = declRef.as<GenericDecl>())
        {
            return;
        }

        // Inheritance declarations don't have meaningful names,
        // and so we should emit them based on the type
        // that is doing the inheriting.
        if(auto inheritanceDeclRef = declRef.as<TypeConstraintDecl>())
        {
            emit(context, "I");
            emitType(context, getSup(context->astBuilder, inheritanceDeclRef));
            return;
        }

        // Similarly, an extension doesn't have a name worth
        // emitting, and we should base things on its target
        // type instead.
        if(auto extensionDeclRef = declRef.as<ExtensionDecl>())
        {
            // TODO: as a special case, an "unconditional" extension
            // that is in the same module as the type it extends should
            // be treated as equivalent to the type itself.
            emit(context, "X");
            emitType(context, getTargetType(context->astBuilder, extensionDeclRef));
            return;
        }

        // TODO: we should special case GenericTypeParamDecl and GenericValueParamDecl nodes
        // instead of just dumping their names here to avoid the name of a generic parameter
        // to have affect the binary signature.
        // For each generic parameter, we should assign it a unique ID (i, j), where i is the
        // nesting level of the generic, and j is the sequential order of the parameter within
        // its generic parent, and use this 2D ID to refer to such a parameter.
        emitName(context, declRef.getName());

        // Special case: accessors need some way to distinguish themselves
        // so that a getter/setter/ref-er don't all compile to the same name.
        {
            if (declRef.is<GetterDecl>())        emitRaw(context, "Ag");
            if (declRef.is<SetterDecl>())        emitRaw(context, "As");
            if (declRef.is<RefAccessorDecl>())   emitRaw(context, "Ar");
        }

        // Special case: need a way to tell prefix and postfix unary
        // operators apart.
        {
            if(declRef.getDecl()->hasModifier<PostfixModifier>()) emitRaw(context, "P");
            if(declRef.getDecl()->hasModifier<PrefixModifier>()) emitRaw(context, "p");
        }

        // Are we the "inner" declaration beneath a generic decl?
        if(parentGenericDeclRef && (parentGenericDeclRef.getDecl()->inner == declRef.getDecl()))
        {
            // There are two cases here: either we have specializations
            // in place for the parent generic declaration, or we don't.

            auto subst = findInnerMostGenericSubstitution(declRef.substitutions);
            if( subst && subst->genericDecl == parentGenericDeclRef.getDecl() )
            {
                // This is the case where we *do* have substitutions.
                emitRaw(context, "G");
                UInt genericArgCount = subst->getArgs().getCount();
                emit(context, genericArgCount);
                for (auto aa : subst->getArgs())
                {
                    emitVal(context, aa);
                }
            }
            else
            {
                // We don't have substitutions, so we will emit
                // information about the parameters of the generic here.
                emitRaw(context, "g");
                UInt genericParameterCount = 0;
                for( auto mm : getMembers(parentGenericDeclRef) )
                {
                    if(mm.is<GenericTypeParamDecl>())
                    {
                        genericParameterCount++;
                    }
                    else if(mm.is<GenericValueParamDecl>())
                    {
                        genericParameterCount++;
                    }
                    else if(mm.is<GenericTypeConstraintDecl>())
                    {
                        genericParameterCount++;
                    }
                    else
                    {
                    }
                }

                emit(context, genericParameterCount);

                OrderedDictionary<GenericTypeParamDecl*, List<Type*>> genericConstraints;
                for (auto mm : getMembers(parentGenericDeclRef))
                {
                    if (auto genericTypeParamDecl = mm.as<GenericTypeParamDecl>())
                    {
                        emitRaw(context, "T");
                    }
                    else if (auto genericValueParamDecl = mm.as<GenericValueParamDecl>())
                    {
                        emitRaw(context, "v");
                        emitType(context, getType(context->astBuilder, genericValueParamDecl));
                    }
                    else
                    {}
                }

                auto canonicalizedConstraints = getCanonicalGenericConstraints(parentGenericDeclRef);
                for (auto& constraint : canonicalizedConstraints)
                {
                    for (auto type : constraint.Value)
                    {
                        emitRaw(context, "C");
                        emitQualifiedName(context, DeclRef<Decl>(constraint.Key, nullptr));
                            emitType(context, type);
                    }
                }

            }
        }

        // If the declaration has parameters, then we need to emit
        // those parameters to distinguish it from other declarations
        // of the same name that might have different parameters.
        //
        // We'll also go ahead and emit the result type as well,
        // just for completeness.
        //
        if( auto callableDeclRef = declRef.as<CallableDecl>())
        {
            auto parameters = getParameters(callableDeclRef);
            UInt parameterCount = parameters.getCount();

            emitRaw(context, "p");
            emit(context, parameterCount);
            emitRaw(context, "p");

            for(auto paramDeclRef : parameters)
            {
                emitType(context, getType(context->astBuilder, paramDeclRef));
            }

            // Don't print result type for an initializer/constructor,
            // since it is implicit in the qualified name.
            if (!callableDeclRef.is<ConstructorDecl>())
            {
                emitType(context, getResultType(context->astBuilder, callableDeclRef));
            }
        }
    }

    void mangleName(
        ManglingContext*    context,
        DeclRef<Decl>       declRef)
    {
        // TODO: catch cases where the declaration should
        // forward to something else? E.g., what if we
        // are asked to mangle the name of a `typedef`?

        auto decl = declRef.getDecl();

        // Handle `__extern_cpp` modifier by simply emitting
        // the given name.
        if (decl->hasModifier<ExternCppModifier>())
        {
            emit(context, decl->getName()->text);
            return;
        }

        // We will start with a unique prefix to avoid
        // clashes with user-defined symbols:
        emitRaw(context, "_S");

        // Next we will add a bit of info to register
        // the *kind* of declaration we are dealing with.
        //
        // Functions will get no prefix, since we assume
        // they are a common case:
        if(as<FuncDecl>(decl))
        {}
        // Types will get a `T` prefix:
        else if(as<AggTypeDecl>(decl))
            emitRaw(context, "T");
        else if(as<TypeDefDecl>(decl))
            emitRaw(context, "T");
        // Variables will get a `V` prefix:
        //
        // TODO: probably need to pull constant-buffer
        // declarations out of this...
        else if(as<VarDeclBase>(decl))
            emitRaw(context, "V");
        else if(DeclRef<GenericDecl> genericDecl = declRef.as<GenericDecl>())
        {
            // Mark that this is a generic, so we can differentiate bewteen when
            // mangling the generic and the inner entity
            emitRaw(context, "G");

            SLANG_ASSERT(genericDecl.substitutions == nullptr);

            auto innerDecl = makeDeclRef(getInner(genericDecl));

            emitQualifiedName(context, innerDecl);
            return;
        }
        else if (as<ForwardDerivativeRequirementDecl>(decl))
            emitRaw(context, "FwdReq_");
        else if (as<BackwardDerivativeRequirementDecl>(decl))
            emitRaw(context, "BwdReq_");
        else
        {
            // TODO: handle other cases
        }

        // Now we encode the qualified name of the decl.
        emitQualifiedName(context, declRef);
    }

    String getMangledName(ASTBuilder* astBuilder, DeclRef<Decl> const& declRef)
    {
        ManglingContext context(astBuilder);
        mangleName(&context, declRef);
        return context.sb.ProduceString();
    }

    String getMangledName(ASTBuilder* astBuilder, DeclRefBase const & declRef)
    {
        return getMangledName(astBuilder,
            DeclRef<Decl>(declRef.decl, declRef.substitutions));
    }

    String getMangledName(ASTBuilder* astBuilder, Decl* decl)
    {
        return getMangledName(astBuilder, makeDeclRef(decl));
    }

    String getMangledNameForConformanceWitness(
        ASTBuilder* astBuilder,
        DeclRef<Decl> sub,
        DeclRef<Decl> sup)
    {
        ManglingContext context(astBuilder);
        emitRaw(&context, "_SW");
        emitQualifiedName(&context, sub);
        emitQualifiedName(&context, sup);
        return context.sb.ProduceString();
    }

    String getMangledNameForConformanceWitness(
        ASTBuilder* astBuilder,
        DeclRef<Decl> sub,
        Type* sup)
    {
        // The mangled form for a witness that `sub`
        // conforms to `sup` will be named:
        //
        //     {Conforms(sub,sup)} => _SW{sub}{sup}
        //
        ManglingContext context(astBuilder);
        emitRaw(&context, "_SW");
        emitQualifiedName(&context, sub);
        emitType(&context, sup);
        return context.sb.ProduceString();
    }

    String getMangledNameForConformanceWitness(
        ASTBuilder* astBuilder,
        Type* sub,
        Type* sup)
    {
        // The mangled form for a witness that `sub`
        // conforms to `sup` will be named:
        //
        //     {Conforms(sub,sup)} => _SW{sub}{sup}
        //
        ManglingContext context(astBuilder);
        emitRaw(&context, "_SW");
        emitType(&context, sub);
        emitType(&context, sup);
        return context.sb.ProduceString();
    }

    String getMangledTypeName(ASTBuilder* astBuilder, Type* type)
    {
        ManglingContext context(astBuilder);
        emitType(&context, type);
        return context.sb.ProduceString();
    }

    String getMangledNameFromNameString(const UnownedStringSlice& name)
    {
        ManglingContext context(nullptr);
        emitNameImpl(&context, name);
        return context.sb.ProduceString();
    }

    String getHashedName(const UnownedStringSlice& mangledName)
    {
        HashCode64 hash = getStableHashCode64(mangledName.begin(), mangledName.getLength());

        StringBuilder builder;
        builder << "_Sh";
        builder.append(uint64_t(hash), 16);

        return builder;
    }

}


text:
*   No changes.

## Rails 4.1.0 (April 8, 2014) ##

*   Fixed missing line and shadow on service pages(404, 422, 500).

    *Dmitry Korotkov*

*   Removed repetitive th tags. Instead of them added one th tag with a colspan attribute.

    *Sıtkı Bağdat*

*   Added the Rails maintenance policy to the guides.

    *Matias Korhonen*

Please check [4-0-stable](https://github.com/rails/rails/blob/4-0-stable/guides/CHANGELOG.md) for previous changes.


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 2.0.1
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

namespace RakNet {

using System;
using System.Runtime.InteropServices;

public class ColumnDescriptor : IDisposable {
  private HandleRef swigCPtr;
  protected bool swigCMemOwn;

  internal ColumnDescriptor(IntPtr cPtr, bool cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = new HandleRef(this, cPtr);
  }

  internal static HandleRef getCPtr(ColumnDescriptor obj) {
    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  }

  ~ColumnDescriptor() {
    Dispose();
  }

  public virtual void Dispose() {
    lock(this) {
      if (swigCPtr.Handle != IntPtr.Zero) {
        if (swigCMemOwn) {
          swigCMemOwn = false;
          RakNetPINVOKE.delete_ColumnDescriptor(swigCPtr);
        }
        swigCPtr = new HandleRef(null, IntPtr.Zero);
      }
      GC.SuppressFinalize(this);
    }
  }

  public ColumnDescriptor() : this(RakNetPINVOKE.new_ColumnDescriptor__SWIG_0(), true) {
  }

  public ColumnDescriptor(string cn, Table.ColumnType ct) : this(RakNetPINVOKE.new_ColumnDescriptor__SWIG_1(cn, (int)ct), true) {
  }

  public string columnName {
    set {
      RakNetPINVOKE.ColumnDescriptor_columnName_set(swigCPtr, value);
    }
    get {
      string ret = RakNetPINVOKE.ColumnDescriptor_columnName_get(swigCPtr);
      return ret;
    }
  }

  public Table.ColumnType columnType {
    set {
      RakNetPINVOKE.ColumnDescriptor_columnType_set(swigCPtr, (int)value);
    }
    get {
      Table.ColumnType ret = (Table.ColumnType)RakNetPINVOKE.ColumnDescriptor_columnType_get(swigCPtr);
      return ret;
    }
  }

}

}


text:
/*!
    \file    usbh_hid_parser.c
    \brief   USB host HID parser driver

    \version 2020-08-01, V3.0.0, firmware for GD32F4xx
*/

/*
    Copyright (c) 2020, GigaDevice Semiconductor Inc.

    Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors
       may be used to endorse or promote products derived from this software without
       specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/

#include "usbh_hid_parser.h"

/*!
    \brief      read a hid report item
    \param[in]  ri: pointer to report item
    \param[in]  ndx: report index
    \param[out] none
    \retval     operation status (0: fail otherwise: item value)
*/
uint32_t hid_item_read (hid_report_item *ri, uint8_t ndx)
{
    uint32_t val = 0U;
    uint32_t bofs = 0U;
    uint8_t *data = ri->data;
    uint8_t shift = ri->shift;

    /* get the logical value of the item */

    /* if this is an array, wee may need to offset ri->data.*/
    if (ri->count > 0U) {
        /* if app tries to read outside of the array. */
        if (ri->count <= ndx) {
            return(0U);
        }

        /* calculate bit offset */
        bofs = ndx * ri->size;
        bofs += shift;

        /* calculate byte offset + shift pair from bit offset. */
        data += bofs / 8U;
        shift = (uint8_t)(bofs % 8U);
    }

    /* read data bytes in little endian order */
    for (uint32_t x = 0U; x < ((ri->size & 0x7U) ? (ri->size / 8U) + 1U : (ri->size / 8U)); x++) {
        val=(uint32_t)((uint32_t)(*data) << (x * 8U));
    }

    val=(val >> shift) & ((1U << ri->size) - 1U);

    if ((val < ri->logical_min) || (val > ri->logical_max)) {
        return(0U);
    }

    /* convert logical value to physical value */
    /* see if the number is negative or not. */
    if ((ri->sign) && (val & (1U << (ri->size - 1U)))) {
        /* yes, so sign extend value to 32 bits. */
        uint32_t vs = (uint32_t)((0xffffffffU & ~((1U << (ri->size)) - 1U)) | val);

        if (1U == ri->resolution) {
            return((uint32_t)vs);
        }
        return((uint32_t)(vs * ri->resolution));
    } else {
        if (1U == ri->resolution) {
            return(val);
        }

        return (val * ri->resolution);
    }
}

/*!
    \brief      write a hid report item
    \param[in]  ri: pointer to report item
    \param[in]  value: the value to be write
    \param[in]  ndx: report index
    \param[out] none
    \retval     operation status (1: fail 0: OK)
*/
uint32_t hid_item_write(hid_report_item *ri, uint32_t value, uint8_t ndx)
{
    uint32_t mask;
    uint32_t bofs;
    uint8_t *data = ri->data;
    uint8_t shift = ri->shift;

    if ((value < ri->physical_min) || (value > ri->physical_max)) {
        return(1U);
    }

    /* if this is an array, wee may need to offset ri->data.*/
    if (ri->count > 0U) {
        /* if app tries to read outside of the array. */
        if (ri->count >= ndx) {
            return(0U);
        }

        /* calculate bit offset */
        bofs = ndx * ri->size;
        bofs += shift;

        /* calculate byte offset + shift pair from bit offset. */
        data += bofs / 8U;
        shift = (uint8_t)(bofs % 8U);
    }

    /* convert physical value to logical value. */
    if (1U != ri->resolution) {
        value = value / ri->resolution;
    }

    /* write logical value to report in little endian order. */
    mask = (1U << ri->size) - 1U;
    value = (value & mask) << shift;

    for (uint32_t x = 0U; x < ((ri->size & 0x7U) ? (ri->size / 8U) + 1U : (ri->size / 8U)); x++) {
        *(ri->data + x) = (uint8_t)((*(ri->data+x) & ~(mask>>(x* 8U))) | ((value >> (x * 8U)) & (mask >> (x * 8U))));
    }

    return 0U;
}


text:
class MiqCockpitWsWorker::Runner < MiqWorker::Runner
  BINDING_ADDRESS = ENV['BINDING_ADDRESS'] || (Rails.env.production? ? "127.0.0.1" : "0.0.0.0")

  def find_pids(cmd)
    pids = Set.new
    Sys::ProcTable.ps.each do |process_struct|
      pids << process_struct.pid if cmd =~ (process_struct.try(:cmdline) || "")
    end
    pids
  end

  def do_before_work_loop
    stop_active_cockpit_ws_processes
    start_drb_service
    start_cockpit_ws
  end

  def do_work
    check_cockpit_ws
  end

  def before_exit(_message, _exit_code)
    stop_cockpit_ws
    stop_drb_service
  end

  def check_cockpit_ws
    if cockpit_ws_alive?
      begin
        errbuf = @stderr.readpartial(1.megabyte) if @stderr && @stderr.ready?
        outbuf = @stdout.readpartial(1.megabyte) if @stdout && @stdout.ready?
      rescue EOFError
        _log.info("#{log_prefix} got EOF process exiting")
      end
      outbuf.split("\n").each { |msg| $log.info("cockpit-ws: #{msg.rstrip}") } if outbuf
      errbuf.split("\n").each { |msg| $log.error("cockpit-ws: #{msg.rstrip}") } if errbuf
    else
      _log.info("#{log_prefix} Cockpit-ws Process gone. Restarting...")
      start_cockpit_ws
    end
  end

  def start_cockpit_ws
    raise _("Cannot call start_cockpit_ws if a process already exists") if cockpit_ws_alive?
    _log.info("#{log_prefix} Starting cockpit-ws Process")
    start_cockpit_ws_process
    _log.info("#{log_prefix} Started cockpit-ws Process")
  end

  def start_cockpit_ws_process
    @pid, @stdout, @stderr = cockpit_ws_run
  rescue => err
    @stdout.close if @stdout
    @stderr.close if @stderr
    _log.error("#{log_prefix} cockpit-ws Process aborted because [#{err.message}]")
    _log.log_backtrace(err)
  end

  def stop_cockpit_ws
    if cockpit_ws_alive?
      _log.info("#{log_prefix} Shutting down cockpit-ws process...pid=#{@pid}")
      stop_cockpit_ws_process
      _log.info("#{log_prefix} Shutting down cockpit-ws process...Complete")
    end
  end

  def stop_cockpit_ws_process
    return unless @pid
    Process.kill("TERM", @pid)
    wait_on_cockpit_ws
  end

  # Waits for a cockpit-ws process to stop.  The process is expected to be
  #   in the act of shutting down, and thus it will wait 5 minutes
  #   before issuing a kill.
  def wait_on_cockpit_ws(pid)
    pid ||= @pid
    # TODO: Use Process.waitpid or one of its async variants
    begin
      Timeout.timeout(5.minutes.to_i) do
        loop do
          break unless process_alive?(pid)
          sleep 1
          heartbeat
        end
      end
    rescue Timeout::Error
      _log.info("#{log_prefix} Killing cockpit-ws process with pid=#{pid}")
      Process.kill(9, pid)
    end

    begin
      _, status = Process.waitpid2(pid)
      _log.info("#{log_prefix} cockpit-ws Process with pid=#{pid} exited with a status=#{status}")
    rescue Errno::ECHILD
      _log.info("#{log_prefix} cockpit-ws Process with pid=#{pid} exited")
    end

    reset_process_info
  end

  def reset_process_info
    @pid = @stdout = @stderr = nil
  end

  def find_cockpit_ws_processes
    find_pids(/cockpit-ws --port/)
  end

  def stop_active_cockpit_ws_processes
    find_cockpit_ws_processes.each do |pid|
      _log.info("#{log_prefix} Killing active cockpit-ws process with pid=#{pid}")
      Process.kill("TERM", pid)
      wait_on_cockpit_ws(pid)
    end
  end

  def cockpit_ws_alive?
    if process_alive?(@pid)
      true
    else
      reset_process_info
      false
    end
  end

  def process_alive?(pid)
    return false if pid.nil?
    process_struct = Sys::ProcTable.ps(:pid => pid)
    return false if process_struct.nil?
    return true if process_struct.state != "Z"

    _log.info("#{log_prefix} waiting to die")
    zombie_pid, status = Process.waitpid2(pid)
    _log.info("#{log_prefix} cockpit-ws Process with pid=#{zombie_pid} exited with a status=#{status}")
    false
  end

  def cockpit_ws_run
    _log.info("#{log_prefix} cockpit-ws process starting")

    opts = @worker_settings
    cockpit_ws = MiqCockpit::WS.new(opts)
    cockpit_ws.save_config

    require "open3"
    env = {
      "XDG_CONFIG_DIRS" => cockpit_ws.config_dir,
      "DRB_URI"         => @drb_uri
    }
    Bundler.with_clean_env do
      stdin, stdout, stderr, wait_thr = Open3.popen3(env, *cockpit_ws.command(BINDING_ADDRESS), :unsetenv_others => true)
    end
    stdin.close

    _log.info("#{log_prefix} cockpit-ws process started - pid=#{@pid}")
    return wait_thr.pid, stdout, stderr
  end

  def check_drb_service
    alive = @drb_server ? @drb_server.alive? : false
    unless alive
      start_drb_service
    end
  end

  def start_drb_service
    require 'drb'
    require 'drb/acl'

    stop_drb_service
    acl = ACL.new(%w(deny all allow 127.0.0.1/32))

    if @drb_uri
      @drb_server = DRb::DRbServer.new(@drb_uri, MiqCockpitWsWorker::Authenticator, acl)
    else
      require 'tmpdir'
      Dir::Tmpname.create("cockpit", nil) do |path|
        @drb_server = DRb::DRbServer.new("drbunix://#{path}", MiqCockpitWsWorker::Authenticator, acl)
        FileUtils.chmod(0o750, path)
      end
    end

    @drb_uri = @drb_server.uri
    _log.info("#{log_prefix} Started drb Process at #{@drb_uri}")
  end

  def stop_drb_service
    @drb_server.stop_service if @drb_server
    @drb_server = nil
    _log.info("#{log_prefix} stopped drb Process at #{@drb_uri}")
  end
end


text:
import React from 'react'
import PropTypes from 'prop-types'
import { Flex } from 'rebass/styled-components'
import { CoinBig } from '@zap/utils/coin'
import { Text } from 'components/UI'
import { CryptoSelector, CryptoValue } from 'containers/UI'
import HtlcHops from './HtlcHops'

const Htlc = ({ route, isAmountVisible = true, ...rest }) => {
  const amountExcludingFees = CoinBig(route.totalAmt)
    .minus(route.totalFees)
    .toString()
  return (
    <Flex alignItems="center" justifyContent="space-between" {...rest}>
      {isAmountVisible && (
        <Text fontWeight="normal">
          <CryptoValue value={amountExcludingFees} />
          <CryptoSelector ml={2} />
        </Text>
      )}
      <HtlcHops hops={route.hops} />
    </Flex>
  )
}

Htlc.propTypes = {
  isAmountVisible: PropTypes.bool,
  route: PropTypes.object.isRequired,
}

export default Htlc


text:
package cz.cuni.mff.odcleanstore.fusiontool.loaders.entity;

import cz.cuni.mff.odcleanstore.fusiontool.config.SparqlRestriction;
import cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException;
import cz.cuni.mff.odcleanstore.fusiontool.source.DataSource;
import cz.cuni.mff.odcleanstore.fusiontool.util.UriCollection;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Seed subjects loader which provides access to seed subjects obtained from multiple data sources.
 * @see cz.cuni.mff.odcleanstore.fusiontool.loaders.entity.SeedSubjectsLoader
 * @author Jan Michelfeit
 */
public class FederatedSeedSubjectsLoader {
    private final Collection<DataSource> dataSources;

    /**
     * Iterator wrapping access to underlying iterators for each data source.
     * At all times only one underlying iterator is opened.
     */
    private final class FederatedUriCollection implements UriCollection {
        private UriCollection currentCollection;
        private Iterator<DataSource> dataSourceIt;
        private final SparqlRestriction seedResourceRestriction;
        private String next = null;

        protected FederatedUriCollection(Collection<DataSource> dataSources, SparqlRestriction seedResourceRestriction)
                throws LDFusionToolException {
            this.dataSourceIt = dataSources.iterator();
            this.seedResourceRestriction = seedResourceRestriction;
            this.next = getNextResult();
        }

        /**
         * Returns {@code true} if the collection has more elements.
         * @return {@code true} if the collection has more elements
         */
        @Override
        public boolean hasNext() {
            return next != null;
        }

        /**
         * Returns an element from the collection and moves the iterator by one.
         * @return the current element
         * @throws cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException error
         */
        @Override
        public String next() throws LDFusionToolException {
            if (next == null) {
                throw new NoSuchElementException();
            }
            String result = next;
            next = getNextResult();
            return result;
        }

        private String getNextResult() throws LDFusionToolException {
            if (currentCollection != null && currentCollection.hasNext()) {
                return currentCollection.next();
            }
            currentCollection = getNextCollection();
            if (currentCollection == null) {
                return null; // no more data sources
            }
            // Use recursion; the loop is not infinite because we have moved by one collection
            return getNextResult();
        }

        private UriCollection getNextCollection() throws LDFusionToolException {
            if (dataSourceIt == null) {
                throw new NoSuchElementException();
            }
            if (dataSourceIt.hasNext()) {
                DataSource source = dataSourceIt.next();
                SeedSubjectsLoader loader = new SeedSubjectsLoader(source);
                return loader.getTripleSubjectsCollection(seedResourceRestriction);
            } else {
                return null;
            }
        }

        @Override
        public void close() throws IOException {
            if (currentCollection != null) {
                currentCollection.close();
                currentCollection = null;
            }
            next = null;
            dataSourceIt = null;
        }

        /**
         * Does nothing.
         */
        @Override
        public void add(String node) {
            // do nothing
        }
    }

    /**
     * Creates a new instance for the given data sources.
     * @param dataSources initialized RDF data sources
     */
    public FederatedSeedSubjectsLoader(Collection<DataSource> dataSources) {
        this.dataSources = dataSources;
    }

    /**
     * Returns iterator over all subjects of relevant triples in all data sources.
     * Returned values may not be distinct.
     * @param seedResourceRestriction SPARQL restriction on URI resources which are initially loaded and processed
     *      or null to iterate all subjects
     * @return collection of subjects of relevant triples
     * @throws cz.cuni.mff.odcleanstore.fusiontool.exceptions.LDFusionToolException query error
     */
    public UriCollection getTripleSubjectsCollection(SparqlRestriction seedResourceRestriction) throws LDFusionToolException {
        return new FederatedUriCollection(dataSources, seedResourceRestriction);
    }
}


text:
<?php namespace korchasa\Telegram\Structs;

use korchasa\Telegram\Structs\User;
use korchasa\Telegram\Unstructured;

class Message
{
    /** @var integer */
    public $message_id;
    /** @var User */
    public $from;
    /** @var integer */
    public $date;
    /** @var string */
    public $text = '';
    /** @var Location */
    public $location;
    /** @var Message */
    public $reply_to_message;
    /** @var Chat */
    public $chat;

    public function __construct(Unstructured $std = null)
    {
        if ($std) {
            $this->message_id = $std->scalar('message_id');
            $this->from = $std->object('from', User::class);
            $this->date = $std->scalar('date');
            $this->text = $std->scalar('text');
            $this->location = $std->object('location', Location::class);
            $this->reply_to_message = $std->object('reply_to_message', Message::class);
            $this->chat = $std->object('chat', Chat::class);
        }
    }

    public function startWith($needles)
    {
        foreach ((array) $needles as $needle) {
            if ($needle != '' && strpos($this->text, $needle) === 0) {
                return true;
            }
        }

        return false;
    }

    public function contains($needles)
    {
        foreach ((array) $needles as $needle) {
            if ($needle != '' && strpos($this->text, $needle) !== false) {
                return true;
            }
        }

        return false;
    }
}


text:
@interface RWTInteractionController ()

@property (weak, nonatomic) IBOutlet UIImageView *facebook;

@end

@implementation RWTInteractionController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    self.facebook.userInteractionEnabled = YES;
    [self.facebook addGestureRecognizer:pan];
}

- (void)handlePan:(UIPanGestureRecognizer *)pan {
    if (pan.state == UIGestureRecognizerStateBegan) {
        [self.facebook pop_removeAllAnimations];
    }
    else if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint point = [pan locationInView:self.view];
        self.facebook.center = point;
    }
    else {
        CGRect bounds = self.view.bounds;
        // middle of the view controller
        CGPoint center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));

        POPSpringAnimation *spring = [POPSpringAnimation animationWithPropertyNamed:kPOPViewCenter];
        spring.toValue = [NSValue valueWithCGPoint:center];
        spring.springBounciness = 20;
        spring.springSpeed = 20;

        [self.facebook pop_addAnimation:spring forKey:@"spring"];
    }
}

@end


text: Created in {{ "now" | date: '%Y' }} by {{ site.data.sidebar.contact.name }}. Powered by Jekyll based on a theme originally designed by Xiaoying Riley


text:
package cmd

import (
	"context"
	"fmt"
	"github.com/mpppk/gitany"
	"github.com/mpppk/hlb/hlblib"
	"io/ioutil"
	"net/url"
	"os"

	"time"

	"github.com/AlecAivazis/survey"
	"github.com/briandowns/spinner"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"gopkg.in/yaml.v2"
)

// add-serviceCmd represents the add-service command
var addServiceCmd = &cobra.Command{
	Use:   "add-service",
	Short: "Add service",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		ctx := context.Background()

		var config hlblib.Config
		err := viper.Unmarshal(&config)
		hlblib.PanicIfErrorExist(err)

		if len(args) < 2 {
			panic("invalid args")
		}

		serviceType := args[0]
		serviceUrl := args[1]

		parsedUrl, err := url.Parse(serviceUrl)
		hlblib.PanicIfErrorExist(err)

		serviceConfig, ok := config.FindServiceConfig(parsedUrl.Host)
		if ok {
			if serviceConfig.Token != "" {
				msg := "token for " + parsedUrl.Host + " is already exist.\n"
				msg += "Are you sure to over write token?"

				replaceOAuthToken := false
				prompt := &survey.Confirm{
					Message: msg,
				}
				survey.AskOne(prompt, &replaceOAuthToken, nil)

				if !replaceOAuthToken {
					os.Exit(0)
				}

			}
		} else {
			serviceConfig = &gitany.ServiceConfig{
				Host:     parsedUrl.Host,
				Type:     serviceType,
				Token:    "",
				Protocol: parsedUrl.Scheme,
			}
		}

		username, password := gitany.PromptUserAndPassword(serviceType)

		s := spinner.New(spinner.CharSets[14], 100*time.Millisecond) // Build our new spinner
		s.Start()                                                    // Start the spinner
		token, err := gitany.CreateToken(ctx, serviceConfig, username, password)
		hlblib.PanicIfErrorExist(err)
		serviceConfig.Token = token
		s.Stop()
		if !ok {
			fmt.Println("Add new service:", parsedUrl.Host)
			config.Services = append(config.Services, serviceConfig)
		} else {
			fmt.Println("Update service:", parsedUrl.Host)
		}

		f, err := yaml.Marshal(config)
		configFilePath, err := hlblib.GetConfigFilePath()
		hlblib.PanicIfErrorExist(err)
		ioutil.WriteFile(configFilePath, f, 0666)
	},
}

func init() {
	RootCmd.AddCommand(addServiceCmd)
}


text:
<?php

include '../../../bootstrap.php';

use App\Helpers\ExerciseConfig\Compilation\Tree\MergeTree;
use App\Helpers\ExerciseConfig\Compilation\Tree\Node;
use App\Helpers\ExerciseConfig\Compilation\Tree\PortNode;
use App\Helpers\ExerciseConfig\Pipeline\Box\CustomBox;
use App\Helpers\ExerciseConfig\VariablesTable;
use Tester\Assert;

class TestMergeTree extends Tester\TestCase
{

    public function testInputNodes()
    {
        $tree = new MergeTree();
        Assert::count(0, $tree->getInputNodes());

        $node1 = new PortNode(new CustomBox());
        $tree->addInputNode($node1);
        Assert::count(1, $tree->getInputNodes());
        Assert::contains($node1, $tree->getInputNodes());

        $node2 = new PortNode(new CustomBox());
        $tree->addInputNode($node2);
        Assert::count(2, $tree->getInputNodes());
        Assert::contains($node2, $tree->getInputNodes());

        $node3 = new PortNode(new CustomBox());
        $node4 = new PortNode(new CustomBox());
        $tree->setInputNodes([$node3, $node4]);
        Assert::count(2, $tree->getInputNodes());
        Assert::contains($node3, $tree->getInputNodes());
        Assert::contains($node4, $tree->getInputNodes());
    }

    public function testOutputNodes()
    {
        $tree = new MergeTree();
        Assert::count(0, $tree->getOutputNodes());

        $node1 = new PortNode(new CustomBox());
        $tree->addOutputNode($node1);
        Assert::count(1, $tree->getOutputNodes());
        Assert::contains($node1, $tree->getOutputNodes());

        $node2 = new PortNode(new CustomBox());
        $tree->addOutputNode($node2);
        Assert::count(2, $tree->getOutputNodes());
        Assert::contains($node2, $tree->getOutputNodes());

        $node3 = new PortNode(new CustomBox());
        $node4 = new PortNode(new CustomBox());
        $tree->setOutputNodes([$node3, $node4]);
        Assert::count(2, $tree->getOutputNodes());
        Assert::contains($node3, $tree->getOutputNodes());
        Assert::contains($node4, $tree->getOutputNodes());
    }

    public function testOtherNodes()
    {
        $tree = new MergeTree();
        Assert::count(0, $tree->getOtherNodes());

        $node1 = new PortNode(new CustomBox());
        $tree->addOtherNode($node1);
        Assert::count(1, $tree->getOtherNodes());
        Assert::contains($node1, $tree->getOtherNodes());

        $node2 = new PortNode(new CustomBox());
        $tree->addOtherNode($node2);
        Assert::count(2, $tree->getOtherNodes());
        Assert::contains($node2, $tree->getOtherNodes());

        $node3 = new PortNode(new CustomBox());
        $node4 = new PortNode(new CustomBox());
        $tree->setOtherNodes([$node3, $node4]);
        Assert::count(2, $tree->getOtherNodes());
        Assert::contains($node3, $tree->getOtherNodes());
        Assert::contains($node4, $tree->getOtherNodes());
    }

    public function testAllNodes()
    {
        $tree = new MergeTree();
        Assert::count(0, $tree->getAllNodes());

        $node1 = new PortNode(new CustomBox());
        $node2 = new PortNode(new CustomBox());
        $node3 = new PortNode(new CustomBox());
        $tree->addInputNode($node1);
        $tree->addOutputNode($node2);
        $tree->addOtherNode($node3);

        Assert::count(3, $tree->getAllNodes());
        Assert::contains($node1, $tree->getAllNodes());
        Assert::contains($node2, $tree->getAllNodes());
        Assert::contains($node3, $tree->getAllNodes());
    }

}

# Testing methods run
$testCase = new TestMergeTree();
$testCase->run();


text:
package com.chaquo.java;

import com.chaquo.python.*;
import java.util.*;
import org.junit.*;
import org.junit.runners.*;

import static com.chaquo.python.PyObject.fromJava;
import static java.util.Map.Entry;
import static org.junit.Assert.*;

@SuppressWarnings({"SuspiciousMethodCalls"})
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MapTest extends ContainerTest {

    private Map<PyObject, PyObject> emptyMap = mod.callAttr("new_map").asMap();
    private Map<PyObject, PyObject> strIntMap =
        mod.callAttr("new_map", "a", 1, "b", 2).asMap();
    private Map<PyObject, PyObject> strIntMapRO =
        mod.callAttr("new_map_ro", "a", 1, "b", 2).asMap();
    private Map<PyObject, PyObject> nullKeyMap =
        mod.callAttr("new_map", null, "null", 1, "one").asMap();
    private Map<PyObject, PyObject> nullValueMap =
        mod.callAttr("new_map", "null", null, "one", 1).asMap();

    @Test
    public void ctor_unsupported() {
        expectUnsupported("int", "__contains__");
        fromJava(42).asMap();
    }

    @Test
    public void entrySet() {
        Set<Entry<PyObject, PyObject>> es = strIntMap.entrySet();
        assertEquals(2, es.size());

        Map<String, Integer> expected = new HashMap<>();
        expected.put("a", 1);
        expected.put("b", 2);
        for (Entry<PyObject, PyObject> entry : strIntMap.entrySet()) {
            assertEquals(expected.remove(entry.getKey().toString()).intValue(),
                         entry.getValue().toInt());
        }
        assertTrue(expected.isEmpty());
    }

    @Test
    public void entrySet_empty() {
        Set<Entry<PyObject, PyObject>> ks = emptyMap.entrySet();
        assertEquals(0, ks.size());
        Iterator<Entry<PyObject, PyObject>> i = ks.iterator();
        assertFalse(i.hasNext());

        thrown.expect(NoSuchElementException.class);
        i.next();
    }

    @Test
    public void entrySet_setValue() {
        for (Entry<PyObject, PyObject> entry : strIntMap.entrySet()) {
            if (entry.getKey().toString().equals("b")) {
                entry.setValue(fromJava(99));
            }
        }
        assertEquals(1, strIntMap.get("a").toInt());
        assertEquals(99, strIntMap.get("b").toInt());
    }

    @Test
    public void entrySet_remove() {
        Iterator<Entry<PyObject, PyObject>> i = strIntMap.entrySet().iterator();
        i.next();
        thrown.expect(UnsupportedOperationException.class);
        thrown.expectMessage("Python does not support removing from a container while " +
                              "iterating over it");
        i.remove();
    }

    // === Read methods ======================================================

    @Test
    public void size() {
        assertEquals(0, emptyMap.size());
        assertEquals(2, strIntMap.size());
    }

    @Test
    public void contains() {
        assertFalse(emptyMap.containsKey("a"));
        assertFalse(emptyMap.containsKey(null));

        assertTrue(strIntMap.containsKey("a"));
        assertTrue(strIntMap.containsKey("b"));
        assertFalse(strIntMap.containsKey("c"));
        assertFalse(strIntMap.containsKey(null));

        assertTrue(nullKeyMap.containsKey(null));
        assertFalse(nullKeyMap.containsKey("null"));
        assertTrue(nullKeyMap.containsKey(1));
        assertFalse(nullKeyMap.containsKey("one"));

        assertTrue(nullValueMap.containsKey("null"));
        assertFalse(nullValueMap.containsKey(null));
        assertTrue(nullValueMap.containsKey("one"));
        assertFalse(nullValueMap.containsKey(1));
    }

    @Test
    public void get() {
        assertNull(emptyMap.get("a"));
        assertNull(emptyMap.get(null));

        assertEquals(1, strIntMap.get("a").toInt());
        assertEquals(2, strIntMap.get("b").toInt());
        assertNull(strIntMap.get("c"));
        assertNull(strIntMap.get(null));

        assertEquals("null", nullKeyMap.get(null).toString());
        assertNull(nullKeyMap.get("null"));
        assertEquals("one", nullKeyMap.get(1).toString());
        assertNull(nullKeyMap.get("one"));

        assertNull(nullValueMap.get("null"));
        assertNull(nullValueMap.get(null));
        assertEquals(1, nullValueMap.get("one").toInt());
        assertNull(nullValueMap.get(1));
    }

    // === Modification methods ==============================================

    @Test
    public void put() {
        strIntMap.put(fromJava("a"), fromJava(101));
        assertEquals(101, strIntMap.get("a").toInt());
        assertEquals(2, strIntMap.size());

        strIntMap.put(fromJava("c"), fromJava(102));
        assertEquals(102, strIntMap.get("c").toInt());
        assertEquals(3, strIntMap.size());
    }

    @Test
    public void put_unsupported() {
        expectUnsupported("mappingproxy", "__setitem__");
        strIntMapRO.put(fromJava("a"), fromJava(101));
    }

    @Test
    public void remove() {
        assertEquals(2, strIntMap.remove("b").toInt());
        assertEquals(1, strIntMap.size());
        assertEquals(1, strIntMap.remove("a").toInt());
        assertEquals(0, strIntMap.size());
    }

    @Test
    public void remove_unsupported() {
        expectUnsupported("mappingproxy", "pop");
        strIntMapRO.remove("b");
    }

    @Test
    public void clear() {
        strIntMap.clear();
        assertEquals(0, strIntMap.size());

        emptyMap.clear();
        assertEquals(0, emptyMap.size());
    }

    @Test
    public void clear_unsupported() {
        expectUnsupported("mappingproxy", "clear");
        strIntMapRO.clear();
    }
}


text:
using FluentAssertions;
using VkNet.Model.RequestParams.Leads;
using VkNet.Tests.Infrastructure;
using Xunit;

namespace VkNet.Tests.Categories.Leads;

public class LeadsCategoryTests : CategoryBaseTest
{
	protected override string Folder => "Leads";

	[Fact]
	public void Complete()
	{
		Url = "https://api.vk.com/method/leads.complete";
		ReadCategoryJsonPath(nameof(Complete));

		var result = Api.Leads.Complete("test8f4f23fb62c5c89fbb", "bb4f37150027a9cf51", string.Empty);

		result.Should()
			.NotBeNull();

		result.Limit.Should()
			.Be(1000);

		result.DayLimit.Should()
			.Be(500);

		result.Spent.Should()
			.Be(10);

		result.Cost.Should()
			.Be("1");

		result.TestMode.Should()
			.Be(1);

		result.Success.Should()
			.Be(1);
	}

	[Fact]
	public void Start()
	{
		Url = "https://api.vk.com/method/leads.start";
		ReadCategoryJsonPath(nameof(Start));

		var result = Api.Leads.Start(new());

		result.Should()
			.NotBeNull();

		result.TestMode.Should()
			.Be(1);

		result.VkSid.Should()
			.Be("vk_sid");
	}

	[Fact]
	public void GetUsers()
	{
		Url = "https://api.vk.com/method/leads.getUsers";
		ReadCategoryJsonPath(nameof(GetUsers));

		var result = Api.Leads.GetUsers(new());

		result.Should()
			.NotBeNull();

		result.Should()
			.NotBeEmpty();
	}
}