text:
package androidx.appcompat.app;

import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
import static androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.custom.FitWindowsContentLayout;
import androidx.appcompat.test.R;
import androidx.appcompat.testutils.BaseTestActivity;
import androidx.appcompat.view.ActionMode;
import androidx.core.view.OnApplyWindowInsetsListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.test.annotation.UiThreadTest;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SdkSuppress;
import androidx.test.filters.SmallTest;
import androidx.test.rule.ActivityTestRule;

import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

@SmallTest
@RunWith(AndroidJUnit4.class)
public abstract class BaseBasicsTestCase<A extends BaseTestActivity> {
    @Rule
    public final ActivityTestRule<A> mActivityTestRule;

    protected BaseBasicsTestCase(Class<A> activityClass) {
        mActivityTestRule = new ActivityTestRule<>(activityClass);
    }

    @Test
    public void testActionBarExists() {
        assertNotNull("ActionBar is not null",
                mActivityTestRule.getActivity().getSupportActionBar());
    }

    @Ignore // b/256195085
    @Test
    public void testActionBarOverflowVisibilityListener() {
        if ("ranchu".equals(Build.HARDWARE)) {
            // Skip this test on Android TV due to a bug in Espresso's menu handling.
            return;
        }

        ActionBar actionBar = mActivityTestRule.getActivity().getSupportActionBar();
        final boolean[] madeVisible = new boolean[] {false};
        actionBar.addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() {
            @Override
            public void onMenuVisibilityChanged(boolean isVisible) {
                madeVisible[0] = isVisible;
            }
        });
        openActionBarOverflowOrOptionsMenu(getApplicationContext());
        assertTrue("OnMenuVisibilityListener should be called",
                madeVisible[0]);
    }

    @UiThreadTest
    @Test
    public void testActionBarShowHideNoOverflowVisibilityListener() {
        ActionBar actionBar = mActivityTestRule.getActivity().getSupportActionBar();
        final boolean[] receivedCallback = new boolean[] {false};
        actionBar.addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() {
            @Override
            public void onMenuVisibilityChanged(boolean isVisible) {
                receivedCallback[0] = true;
            }
        });
        actionBar.openOptionsMenu();
        actionBar.closeOptionsMenu();
        assertFalse("OnMenuVisibilityListener should not be called",
                receivedCallback[0]);
    }

    @Test
    public void testDefaultActionBarTitle() {
        assertEquals(mActivityTestRule.getActivity().getTitle(),
                mActivityTestRule.getActivity().getSupportActionBar().getTitle());
    }

    @UiThreadTest
    @Test
    public void testSetActionBarTitleByActivity() {
        final String newTitle = "hello";
        mActivityTestRule.getActivity().setTitle(newTitle);
        assertEquals("New title is set to ActionBar",
                newTitle, mActivityTestRule.getActivity().getSupportActionBar().getTitle());
    }

    @UiThreadTest
    @Test
    @SdkSuppress(minSdkVersion = 19)
    public void testSetActionBarTitleByActionBar() {
        final String newTitle = "hello";
        mActivityTestRule.getActivity().getSupportActionBar().setTitle(newTitle);
        assertEquals("New title is set to ActionBar",
                newTitle, mActivityTestRule.getActivity().getSupportActionBar().getTitle());
        assertEquals("New title is set to root view's accessibilityPaneTitle",
                newTitle,
                ViewCompat.getAccessibilityPaneTitle(
                        mActivityTestRule.getActivity().getWindow().getDecorView()));
    }

    @Test
    @SdkSuppress(minSdkVersion = 16, maxSdkVersion = 20)
    @RequiresApi(16)
    public void testFitSystemWindowsReachesContent() throws Throwable {
        final A activity = mActivityTestRule.getActivity();
        if (!canShowSystemUi(activity)) {
            // Device cannot show system UI so setSystemUiVisibility will do nothing.
            return;
        }

        final FitWindowsContentLayout content = activity.findViewById(R.id.test_content);
        assertNotNull(content);

        // Tell the window that we will handle insets
        mActivityTestRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WindowCompat.setDecorFitsSystemWindows(activity.getWindow(), false);
            }
        });

        // Wait for the next layout
        final CountDownLatch latch = new CountDownLatch(1);
        content.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                    int oldLeft, int oldTop, int oldRight, int oldBottom) {
                v.removeOnLayoutChangeListener(this);
                latch.countDown();
            }
        });
        latch.await(5, TimeUnit.SECONDS);

        assertTrue(content.getFitsSystemWindowsCalled());
    }

    @Test
    @SdkSuppress(minSdkVersion = 21)
    @RequiresApi(21)
    public void testOnApplyWindowInsetsReachesContent() throws Throwable {
        final A activity = mActivityTestRule.getActivity();
        if (!canShowSystemUi(activity)) {
            // Device cannot show system UI so setSystemUiVisibility will do nothing.
            return;
        }

        final View content = activity.findViewById(R.id.test_content);
        assertNotNull(content);

        final WindowInsetsCompat receivedInsets = waitForWindowInsets(content);
        assertNotNull(receivedInsets);
    }

    @Test
    @SdkSuppress(minSdkVersion = 23)
    public void testOnApplyWindowInsetsReachesContent_matchesRootBottom() throws Throwable {
        final A activity = mActivityTestRule.getActivity();
        if (!canShowSystemUi(activity)) {
            // Device cannot show system UI so setSystemUiVisibility will do nothing.
            return;
        }

        final View content = activity.findViewById(R.id.test_content);
        assertNotNull(content);

        final WindowInsetsCompat receivedInsets = waitForWindowInsets(content);
        assertNotNull(receivedInsets);

        final WindowInsetsCompat rootWindowInsets = ViewCompat.getRootWindowInsets(content);
        assertNotNull(rootWindowInsets);
        // Assert that we dispatch the correct bottom system window inset
        assertEquals(rootWindowInsets.getSystemWindowInsets().bottom,
                receivedInsets.getSystemWindowInsets().bottom);
    }

    @Test
    @SdkSuppress(minSdkVersion = 28)
    @RequiresApi(28)
    public void testOnApplyWindowInsetsReachesContent_withDisplayCutout() throws Throwable {
        final A activity = mActivityTestRule.getActivity();
        if (!canShowSystemUi(activity)) {
            // Device cannot show system UI so setSystemUiVisibility will do nothing.
            return;
        }

        final View content = activity.findViewById(R.id.test_content);
        assertNotNull(content);

        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<WindowInsetsCompat> received = new AtomicReference<>();
        // Set a listener to catch WindowInsets
        ViewCompat.setOnApplyWindowInsetsListener(content, new OnApplyWindowInsetsListener() {
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                received.set(insets);
                latch.countDown();
                return insets;
            }
        });

        // Tell the window that we will handle insets, and tell the WindowManager that we want to
        // handle DisplayCutouts
        mActivityTestRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WindowCompat.setDecorFitsSystemWindows(activity.getWindow(), false);

                WindowManager.LayoutParams wlp = activity.getWindow().getAttributes();
                wlp.layoutInDisplayCutoutMode =
                        WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
                activity.getWindow().setAttributes(wlp);
            }
        });

        // Await an inset pass
        latch.await(5, TimeUnit.SECONDS);

        WindowInsetsCompat receivedInsets = received.get();
        WindowInsetsCompat rootWindowInsets = ViewCompat.getRootWindowInsets(content);

        assertNotNull(receivedInsets);
        assertNotNull(rootWindowInsets);
        // Assert that the DisplayCutout was properly propagated
        assertEquals(rootWindowInsets.getDisplayCutout(), receivedInsets.getDisplayCutout());
    }

    @Test
    @UiThreadTest
    public void testSupportActionModeCallbacks() {
        final A activity = mActivityTestRule.getActivity();

        // Create a mock action mode callback which returns true from onCreateActionMode
        final ActionMode.Callback callback = mock(ActionMode.Callback.class);
        when(callback.onCreateActionMode(any(ActionMode.class), any(Menu.class))).thenReturn(true);

        // Start an action mode
        final ActionMode actionMode = activity.startSupportActionMode(callback);
        assertNotNull(actionMode);

        // Now verify that onCreateActionMode and onPrepareActionMode are called once
        verify(callback).onCreateActionMode(any(ActionMode.class), any(Menu.class));
        verify(callback).onPrepareActionMode(any(ActionMode.class), any(Menu.class));

        // Now finish and verify that onDestroyActionMode is called once, and there are no more
        // interactions
        actionMode.finish();
        verify(callback).onDestroyActionMode(any(ActionMode.class));
        verifyNoMoreInteractions(callback);
    }

    @Test
    @UiThreadTest
    public void testSupportActionModeCallbacksInvalidate() {
        final A activity = mActivityTestRule.getActivity();

        // Create a mock action mode callback which returns true from onCreateActionMode
        final ActionMode.Callback callback = mock(ActionMode.Callback.class);
        when(callback.onCreateActionMode(any(ActionMode.class), any(Menu.class))).thenReturn(true);

        // Start an action mode
        final ActionMode actionMode = activity.startSupportActionMode(callback);
        // Assert that one was created
        assertNotNull(actionMode);
        // Reset the mock so that any callback counts from the create are reset
        reset(callback);

        // Now invalidate the action mode
        actionMode.invalidate();

        // Now verify that onCreateActionMode is not called, and onPrepareActionMode is called once
        verify(callback, never()).onCreateActionMode(any(ActionMode.class), any(Menu.class));
        verify(callback).onPrepareActionMode(any(ActionMode.class), any(Menu.class));
    }

    @Test
    @UiThreadTest
    public void testSupportActionModeCallbacksWithFalseOnCreate() {
        final A activity = mActivityTestRule.getActivity();

        // Create a mock action mode callback which returns true from onCreateActionMode
        final ActionMode.Callback callback = mock(ActionMode.Callback.class);
        when(callback.onCreateActionMode(any(ActionMode.class), any(Menu.class))).thenReturn(false);

        // Start an action mode
        final ActionMode actionMode = activity.startSupportActionMode(callback);

        // Now verify that onCreateActionMode is called once
        verify(callback).onCreateActionMode(any(ActionMode.class), any(Menu.class));

        // Now verify that onPrepareActionMode is not called (since onCreateActionMode
        // returns false)
        verify(callback, never()).onPrepareActionMode(any(ActionMode.class), any(Menu.class));

        // Assert that an action mode was not created
        assertNull(actionMode);
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("InlinedApi")
    static boolean canShowSystemUi(Activity activity) {
        PackageManager manager = activity.getPackageManager();
        return !manager.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
                && !manager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
                && !manager.hasSystemFeature(PackageManager.FEATURE_WATCH);
    }

    protected void testSupportActionModeAppCompatCallbacks(final boolean fromWindow) {
        final A activity = mActivityTestRule.getActivity();

        // Create a mock action mode callback which returns true from onCreateActionMode
        final ActionMode.Callback amCallback = mock(ActionMode.Callback.class);
        when(amCallback.onCreateActionMode(any(ActionMode.class), any(Menu.class)))
                .thenReturn(true);

        // Create a mock AppCompatCallback, which returns null from
        // onWindowStartingSupportActionMode, and set it on the Activity
        final AppCompatCallback apCallback = mock(AppCompatCallback.class);
        when(apCallback.onWindowStartingSupportActionMode(any(ActionMode.Callback.class)))
                .thenReturn(null);
        activity.setAppCompatCallback(apCallback);

        // Start an action mode with the action mode callback
        final ActionMode actionMode = activity.startSupportActionMode(amCallback);

        if (fromWindow) {
            // Verify that the callback's onWindowStartingSupportActionMode was called
            verify(apCallback).onWindowStartingSupportActionMode(any(ActionMode.Callback.class));
        }

        // Now assert that an action mode was created
        assertNotNull(actionMode);

        // Now verify that onSupportActionModeStarted is called once
        verify(apCallback).onSupportActionModeStarted(any(ActionMode.class));

        // Now finish and verify that onDestroyActionMode is called once
        actionMode.finish();
        verify(apCallback).onSupportActionModeFinished(any(ActionMode.class));
    }

    @RequiresApi(16)
    private WindowInsetsCompat waitForWindowInsets(@NonNull final View view) throws Throwable {
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<WindowInsetsCompat> received = new AtomicReference<>();
        // Set a listener to catch WindowInsets
        ViewCompat.setOnApplyWindowInsetsListener(view, new OnApplyWindowInsetsListener() {
            @Override
            public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                received.set(insets);
                latch.countDown();
                return insets;
            }
        });

        // Tell the Window that we want to fit any system windows
        mActivityTestRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WindowCompat.setDecorFitsSystemWindows(
                        mActivityTestRule.getActivity().getWindow(), false);
            }
        });

        // Await an inset pass
        latch.await(5, TimeUnit.SECONDS);
        return received.get();
    }
}


text:
/*
 * The MIT License

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

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

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

/*
 * jQuery helper plugin for examples and tests
 */

(function( $ ){
    $.fn.html2canvas = function(options) {

        var date = new Date();
        var message,
        timeoutTimer,
        timer = date.getTime();

        var object = $.extend({},{
            logging: false,
            proxyUrl: "http://html2canvas.appspot.com/", // running html2canvas-python proxy
            ready: function(renderer) {

                var finishTime = new Date();
               // console.log((finishTime.getTime()-timer)/1000);

                document.body.appendChild(renderer.canvas);

                var canvas = $(renderer.canvas);
                canvas.css('position','absolute')
                .css('left',0).css('top',0);

               // $('body').append(canvas);
                $(canvas).siblings().toggle();

                throwMessage('Screenshot created in '+ ((finishTime.getTime()-timer)/1000) + " seconds<br />Total of "+renderer.numDraws+" draws performed",4000);

                $(window).click(function(){
                    if (!canvas.is(':visible')){
                        $(canvas).toggle().siblings().toggle();
                        throwMessage("Canvas Render visible");
                    } else{
                        $(canvas).siblings().toggle();
                        $(canvas).toggle();
                        throwMessage("Canvas Render hidden");
                    }

                });
            }

        },options)

        new html2canvas(this.get(0), object);

        function throwMessage(msg,duration){

            window.clearTimeout(timeoutTimer);
            timeoutTimer = window.setTimeout(function(){
                message.fadeOut(function(){
                    message.remove();
                });
            },duration || 2000);
            $(message).remove();
            message = $('<div />').html(msg).css({
                margin:0,
                padding:10,
                background: "#000",
                opacity:0.7,
                position:"fixed",
                top:10,
                right:10,
                fontFamily: 'Tahoma' ,
                color:'#fff',
                fontSize:12,
                borderRadius:12,
                width:'auto',
                height:'auto',
                textAlign:'center',
                textDecoration:'none'
            }).hide().fadeIn().appendTo('body');
        }

    };
})( jQuery );

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActionController::MimeResponds</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.0.2

            Module
            ActionController::MimeResponds

/usr/local/lib/ruby/gems/2.1.0/gems/actionpack-4.0.2/lib/action_controller/metal/mime_responds.rb

Namespace

          MODULE
          ActionController::MimeResponds::ClassMethods

          CLASS
          ActionController::MimeResponds::Collector

Methods

R

                respond_to,

                respond_with

Instance Public methods

              respond_to(*mimes, &block)

            Link

Without web-service support, an action which collects the data for
displaying a list of people might look something like this:

def index
  @people = Person.all
end

Here's the same action, with web-service support baked in:

def index
  @people = Person.all

  respond_to do |format|
    format.html
    format.xml { render xml: @people }
  end
end

What that says is, "if the client wants HTML in
response to this action, just respond as we would have before, but if the
client wants XML, return them the list of people in XML format." (Rails
determines the desired response format from the HTTP Accept header
submitted by the client.)

Supposing you have an action that adds a new person, optionally creating
their company (by name) if it does not already exist, without web-services,
it might look like this:

def create
  @company = Company.find_or_create_by(name: params[:company][:name])
  @person  = @company.people.create(params[:person])

  redirect_to(person_list_url)
end

Here's the same action, with web-service support baked in:

def create
  company  = params[:person].delete(:company)
  @company = Company.find_or_create_by(name: company[:name])
  @person  = @company.people.create(params[:person])

  respond_to do |format|
    format.html { redirect_to(person_list_url) }
    format.js
    format.xml  { render xml: @person.to_xml(include: @company) }
  end
end

If the client wants HTML, we just redirect them
back to the person list. If they want JavaScript, then it is an Ajax
request and we render the JavaScript template associated with this action.
Lastly, if the client wants XML, we render the created person as XML, but
with a twist: we also include the person's company in the rendered XML,
so you get something like this:

<person>
  <id>...</id>
  ...
  <company>
    <id>...</id>
    <name>...</name>
    ...
  </company>
</person>

Note, however, the extra bit at the top of that action:

company  = params[:person].delete(:company)
@company = Company.find_or_create_by(name: company[:name])

This is because the incoming XML document (if a web-service request is in
process) can only contain a single root-node. So, we have to rearrange
things so that the request looks like this (url-encoded):

person[name]=...&person[company][name]=...&...

And, like this (xml-encoded):

<person>
  <name>...</name>
  <company>
    <name>...</name>
  </company>
</person>

In other words, we make the request so that it operates on a single
entity's person. Then, in the action, we extract the company data from
the request, find or create the company, and then create the new person
with the remaining data.

Note that you can define your own XML parameter parser which would allow
you to describe multiple entities in a single request (i.e., by wrapping
them all in a single root node), but if you just go with the flow and
accept Rails' defaults, life will be much easier.

If you need to use a MIME type which isn't supported by default, you
can register your own handlers in config/initializers/mime_types.rb as
follows.

Mime::Type.register "image/jpg", :jpg

Respond to also allows you to specify a common block for different formats
by using any:

def index
  @people = Person.all

  respond_to do |format|
    format.html
    format.any(:xml, :json) { render request.format.to_sym => @people }
  end
end

In the example above, if the format is xml, it will render:

render xml: @people

Or if the format is json:

render json: @people

Since this is a common pattern, you can use the class method #respond_to with the #respond_with method to
have the same results:

class PeopleController < ApplicationController
  respond_to :html, :xml, :json

  def index
    @people = Person.all
    respond_with(@people)
  end
end

Be sure to check the documentation of respond_with and
ActionController::MimeResponds.respond_to for more examples.

                Source:
                show

# File ../../../../usr/local/lib/ruby/gems/2.1.0/gems/actionpack-4.0.2/lib/action_controller/metal/mime_responds.rb, line 186
def respond_to(*mimes, &block)
  raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?

  if collector = retrieve_collector_from_mimes(mimes, &block)
    response = collector.response
    response ? response.call : render({})
  end
end

              respond_with(*resources, &block)

            Link

For a given controller action, #respond_with generates
an appropriate response based on the mime-type requested by the client.

If the method is called with just a resource, as in this example -

class PeopleController < ApplicationController
  respond_to :html, :xml, :json

  def index
    @people = Person.all
    respond_with @people
  end
end

then the mime-type of the response is typically selected based on the
request's Accept header and the set of available formats declared by
previous calls to the controller's class method
respond_to. Alternatively the mime-type can be selected by
explicitly setting request.format in the controller.

If an acceptable format is not identified, the application returns a
'406 - not acceptable' status. Otherwise, the default response is
to render a template named after the current action and the selected
format, e.g. index.html.erb. If no template is available, the
behavior depends on the selected format:

for an html response - if the request method is get, an
exception is raised but for other requests such as post the
response depends on whether the resource has any validation errors (i.e.
assuming that an attempt has been made to save the resource, e.g. by a
create action) -

If there are no errors, i.e. the resource was saved successfully, the
response redirect's to the resource i.e. its
show action.

If there are validation errors, the response renders a default action,
which is :new for a post request or
:edit for patch or put.

Thus an example like this -

respond_to :html, :xml

def create
  @user = User.new(params[:user])
  flash[:notice] = 'User was successfully created.' if @user.save
  respond_with(@user)
end

is equivalent, in the absence of create.html.erb, to -

def create
  @user = User.new(params[:user])
  respond_to do |format|
    if @user.save
      flash[:notice] = 'User was successfully created.'
      format.html { redirect_to(@user) }
      format.xml { render xml: @user }
    else
      format.html { render action: "new" }
      format.xml { render xml: @user }
    end
  end
end

for a javascript request - if the template isn't found, an exception is
raised.

for other requests - i.e. data formats such as xml, json, csv etc, if the
resource passed to respond_with responds to
to_<format>, the method attempts to render the resource
in the requested format directly, e.g. for an xml request, the response is
equivalent to calling  render xml: resource.

Nested resources

As outlined above, the resources argument passed to
respond_with can play two roles. It can be used to generate
the redirect url for successful html requests (e.g. for create
actions when no template exists), while for formats other than html and
javascript it is the object that gets rendered, by being converted directly
to the required format (again assuming no template exists).

For redirecting successful html requests, respond_with also
supports the use of nested resources, which are supplied in the same way as
in form_for and polymorphic_url. For example -

def create
  @project = Project.find(params[:project_id])
  @task = @project.comments.build(params[:task])
  flash[:notice] = 'Task was successfully created.' if @task.save
  respond_with(@project, @task)
end

This would cause respond_with to redirect to
project_task_url instead of task_url. For request
formats other than html or javascript, if multiple resources are passed in
this way, it is the last one specified that is rendered.

Customizing response behavior

Like respond_to, respond_with may also be called
with a block that can be used to overwrite any of the default responses,
e.g. -

def create
  @user = User.new(params[:user])
  flash[:notice] = "User was successfully created." if @user.save

  respond_with(@user) do |format|
    format.html { render }
  end
end

The argument passed to the block is an ActionController::MimeResponds::Collector
object which stores the responses for the formats defined within the block.
Note that formats with responses defined explicitly in this way do not have
to first be declared using the class method respond_to.

Also, a hash passed to respond_with immediately after the
specified resource(s) is interpreted as a set of options relevant to all
formats. Any option accepted by render can be used, e.g.

respond_with @people, status: 200

However, note that these options are ignored after an unsuccessful attempt
to save a resource, e.g. when automatically rendering :new
after a post request.

Two additional options are relevant specifically to
respond_with -

:location - overwrites the default redirect location used
after a successful html post request.

:action - overwrites the default render action used after an
unsuccessful html post request.

                Source:
                show

# File ../../../../usr/local/lib/ruby/gems/2.1.0/gems/actionpack-4.0.2/lib/action_controller/metal/mime_responds.rb, line 323
def respond_with(*resources, &block)
  raise "In order to use respond_with, first you need to declare the formats your "              "controller responds to in the class level" if self.class.mimes_for_respond_to.empty?

  if collector = retrieve_collector_from_mimes(&block)
    options = resources.size == 1 ? {} : resources.extract_options!
    options[:default_response] = collector.response
    (options.delete(:responder) || self.class.responder).call(self, resources, options)
  end
end


text:
import { assert } from '@ember/debug';
import type Evented from '@ember/object/evented';
import type Service from '@ember/service';
import type { TestContext } from '@ember/test-helpers';
import { getContext } from '@ember/test-helpers';
import type IntlService from 'ember-intl/services/intl';

import type { ConditionalKeys, RemoveFirstFromTuple } from './type-utils';

type IntlMethods = Exclude<ConditionalKeys<IntlService, (...args: unknown[]) => void>, keyof Service | keyof Evented>;

/**
 * Resolves the `intl` service and provides it to the `fn` as the first
 * argument. Returns the partially applied function.
 *
 * @private
 * @function
 * @param {function} fn
 * @return {function}
 * @hide
 */
export function makeIntlHelper<Fn extends (intl: IntlService, ...rest: unknown[]) => void>(
  fn: Fn
): (...args: RemoveFirstFromTuple<Parameters<Fn>>) => ReturnType<Fn>;
export function makeIntlHelper<Fn extends IntlMethods>(fn: Fn): IntlService[Fn];
export function makeIntlHelper(fn: ((intl: IntlService, ...rest: unknown[]) => void) | IntlMethods) {
  return (...args: unknown[]) => {
    const { owner } = getContext() as TestContext;
    assert(
      'The current test context has no owner. Did you forget to call `setupTest(hooks)`, `setupContext(this)` or some other test helper?',
      typeof owner === 'object' && typeof owner.lookup === 'function'
    );
    const intl = owner.lookup('service:intl') as IntlService;

    if (typeof fn === 'string') {
      // @ts-expect-error I tried all the things. Seems like this dynamism is
      // just not possible in TypeScript. Luckily `makeIntlHelper()` generic
      // types already reliably prevent any misuse, so we do not sacrifice any
      // safety here.
      return intl[fn](...args);
    }

    return fn(intl, ...args);
  };
}

export default makeIntlHelper;


text:
import React, {Component, PropTypes} from 'react';

function getStyles(props, context) {
  const {
    baseTheme,
    gridTile,
  } = context.muiTheme;

  const actionPos = props.actionIcon && props.actionPosition;

  const styles = {
    root: {
      position: 'relative',
      display: 'block',
      height: '100%',
      overflow: 'hidden',
    },
    titleBar: {
      position: 'absolute',
      left: 0,
      right: 0,
      [props.titlePosition]: 0,
      height: props.subtitle ? 68 : 48,
      background: props.titleBackground,
      display: 'flex',
      alignItems: 'center',
    },
    titleWrap: {
      flexGrow: 1,
      marginLeft: actionPos !== 'left' ? baseTheme.spacing.desktopGutterLess : 0,
      marginRight: actionPos === 'left' ? baseTheme.spacing.desktopGutterLess : 0,
      color: gridTile.textColor,
      overflow: 'hidden',
    },
    title: {
      fontSize: '16px',
      textOverflow: 'ellipsis',
      overflow: 'hidden',
      whiteSpace: 'nowrap',
    },
    subtitle: {
      fontSize: '12px',
      textOverflow: 'ellipsis',
      overflow: 'hidden',
      whiteSpace: 'nowrap',
    },
    actionIcon: {
      order: actionPos === 'left' ? -1 : 1,
    },
    childImg: {
      height: '100%',
      transform: 'translateX(-50%)',
      position: 'relative',
      left: '50%',
    },
  };
  return styles;
}

class GridTile extends Component {
  static propTypes = {
    /**
     * An IconButton element to be used as secondary action target
     * (primary action target is the tile itself).
     */
    actionIcon: PropTypes.element,
    /**
     * Position of secondary action IconButton.
     */
    actionPosition: PropTypes.oneOf(['left', 'right']),
    /**
     * Theoretically you can pass any node as children, but the main use case is to pass an img,
     * in whichcase GridTile takes care of making the image "cover" available space
     * (similar to background-size: cover or to object-fit:cover).
     */
    children: PropTypes.node,
    /**
     * Width of the tile in number of grid cells.
     */
    cols: PropTypes.number,
    /**
     * Either a string used as tag name for the tile root element, or a ReactElement.
     * This is useful when you have, for example, a custom implementation of
     * a navigation link (that knows about your routes) and you want to use it as the primary tile action.
     * In case you pass a ReactElement, please ensure that it passes all props,
     * accepts styles overrides and render it's children.
     */
    containerElement: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.element,
    ]),
    /**
     * Height of the tile in number of grid cells.
     */
    rows: PropTypes.number,
    /**
     * Override the inline-styles of the root element.
     */
    style: PropTypes.object,
    /**
     * String or element serving as subtitle (support text).
     */
    subtitle: PropTypes.node,
    /**
     * Title to be displayed on tile.
     */
    title: PropTypes.node,
    /**
     * Style used for title bar background.
     * Useful for setting custom gradients for example
     */
    titleBackground: PropTypes.string,
    /**
     * Position of the title bar (container of title, subtitle and action icon).
     */
    titlePosition: PropTypes.oneOf(['top', 'bottom']),
  };

  static defaultProps = {
    titlePosition: 'bottom',
    titleBackground: 'rgba(0, 0, 0, 0.4)',
    actionPosition: 'right',
    cols: 1,
    rows: 1,
    containerElement: 'div',
  };

  static contextTypes = {
    muiTheme: PropTypes.object.isRequired,
  };

  componentDidMount() {
    this.ensureImageCover();
  }

  componentDidUpdate() {
    this.ensureImageCover();
  }

  ensureImageCover() {
    let imgEl = this.refs.img;

    if (imgEl) {
      const fit = () => {
        if (imgEl.offsetWidth < imgEl.parentNode.offsetWidth) {
          const {isRtl} = this.context.muiTheme;
          imgEl.style.height = 'auto';
          if (isRtl) {
            imgEl.style.right = '0';
          } else {
            imgEl.style.left = '0';
          }
          imgEl.style.width = '100%';
          imgEl.style.top = '50%';
          imgEl.style.transform = imgEl.style.WebkitTransform = 'translateY(-50%)';
        }
        imgEl.removeEventListener('load', fit);
        imgEl = null; // prevent closure memory leak
      };
      if (imgEl.complete) {
        fit();
      } else {
        imgEl.addEventListener('load', fit);
      }
    }
  }

  render() {
    const {
      title,
      subtitle,
      titlePosition, // eslint-disable-line no-unused-vars
      titleBackground, // eslint-disable-line no-unused-vars
      actionIcon, // eslint-disable-line no-unused-vars
      actionPosition, // eslint-disable-line no-unused-vars
      style,
      children,
      containerElement,
      ...other
    } = this.props;

    const {prepareStyles} = this.context.muiTheme;
    const styles = getStyles(this.props, this.context);
    const mergedRootStyles = Object.assign(styles.root, style);

    let titleBar = null;

    if (title) {
      titleBar = (

{title}

            {subtitle ? (
{subtitle}
) : null}

          {actionIcon ? (
{actionIcon}
) : null}

      );
    }

    let newChildren = children;

    // if there is a single image passed as children
    // clone it and add our styles
    if (React.Children.count(children) === 1) {
      newChildren = React.Children.map(children, (child) => {
        if (child.type === 'img') {
          return React.cloneElement(child, {
            key: 'img',
            ref: 'img',
            style: prepareStyles(Object.assign({}, styles.childImg, child.props.style)),
          });
        } else {
          return child;
        }
      });
    }

    const containerProps = {
      style: prepareStyles(mergedRootStyles),
      ...other,
    };

    return React.isValidElement(containerElement) ?
      React.cloneElement(containerElement, containerProps, [newChildren, titleBar]) :
      React.createElement(containerElement, containerProps, [newChildren, titleBar]);
  }
}

export default GridTile;


text: Repository for building microservices training


text:
package quizum.app.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import quizum.QuizumUtils;
import quizum.beans.Question;
import quizum.beans.UserInfo;

public class QuizFrame extends JFrame {
	private List<Question> questionList;
	private JLabel imageLabel, label;
	private UserInfo userInfo;
	private int iterator;
	private List<QuestionPanel> questionPanelList;
	private JButton buttonNext;
	private JButton buttonPrev;

	public QuizFrame(String fileName, UserInfo userInfo) {
		if (fileName == null || fileName.isEmpty()) {
			JOptionPane.showMessageDialog(null, "Nie można odczytać konfiguracji", "Błąd konfiguracji", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
		questionList = QuizumUtils.loadQuestionList(new File(fileName));
		this.userInfo = userInfo;
		initialize();
	}

	private void initialize() {
		setTitle("Quizum");
		setLocation(100, 100);
		setMinimumSize(new Dimension(1200, 700));
		setMaximumSize(new Dimension(1400, 900));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setLayout(new BorderLayout(10, 10));

		iterator = -1;

		JPanel imagePanel = new JPanel();
		imagePanel.setBorder(new EmptyBorder(5, 5, 5, 5));

		imageLabel = new JLabel();
		imagePanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
		imagePanel.add(imageLabel);

		questionPanelList = new ArrayList<QuestionPanel>();
		questionList.forEach(question -> questionPanelList.add(new QuestionPanel(question)));
		Collections.shuffle(questionPanelList);

		int width = questionPanelList.stream().max((qPanel1, qPanel2) -> Integer.compare(qPanel1.getSize().width, qPanel2.getSize().width)).get().getWidth();
		int height = questionPanelList.stream().max((qPanel1, qPanel2) -> Integer.compare(qPanel1.getSize().height, qPanel2.getSize().height)).get().getHeight();
		setSize(width, height);

		JPanel panel_1 = new JPanel();
		panel_1.setLayout(new GridLayout(1, 3, 0, 5));

		panel_1.add(new JPanel());

		JPanel panel_2 = new JPanel();
		panel_1.add(panel_2);

		buttonPrev = new JButton("Poprzednie");
		buttonPrev.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				QuestionPanel panel = getPrevQuestionPanel();

				if(panel != null){
					changePanel(panel);
				}
			}
		});
		panel_2.add(buttonPrev);

		label = new JLabel("");
		label.setHorizontalTextPosition(SwingConstants.CENTER);
		panel_2.add(label);

		buttonNext = new JButton("Następne");
		buttonNext.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				QuestionPanel panel = getNextQuestionPanel();

				if (panel != null) {
					changePanel(panel);
				}
			}
		});
		panel_2.add(buttonNext);

		changePanel(getNextQuestionPanel());

		JPanel panel_3 = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel_3.getLayout();
		flowLayout.setHgap(20);
		flowLayout.setAlignment(FlowLayout.RIGHT);
		panel_1.add(panel_3);

		JButton btnNewButton_1 = new JButton("Zakończ");
		btnNewButton_1.setHorizontalAlignment(SwingConstants.RIGHT);
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				questionPanelList.forEach(questionPanel -> {
					userInfo.resolveQuestion(questionPanel.question,
							questionPanel.getAnswer() != null ? questionPanel.getAnswer() : null);
				});

				QuizumUtils.generateReport(userInfo);
				JOptionPane.showMessageDialog(null, "Poprawnych odpowiedzi: "+userInfo.getTotal()+" z "+questionPanelList.size()+" ("+(int)((double)userInfo.getTotal()/questionPanelList.size()*100)+"%)", "Wynik", JOptionPane.INFORMATION_MESSAGE);
				System.exit(0);
			}
		});
		panel_3.add(btnNewButton_1);

		getContentPane().add(panel_1, BorderLayout.SOUTH);

		getContentPane().add(imagePanel, BorderLayout.EAST);
		setVisible(true);
	}

	public void changePanel(QuestionPanel panel) {
		if (panel == null)
			return;
		if (getContentPane().getComponents().length > 0)
			getContentPane().remove(0);
		getContentPane().add(panel, 0);

		if (panel.question.getPictureFileName() != null) {
			setQuestionImage(QuizumUtils.getImageByFilename(panel.question.getPictureFileName()));
		} else {
			setQuestionImage(null);
		}

		label.setText((iterator+1)+" / "+questionPanelList.size());

		if(iterator > 0) {
			revalidateButton(buttonPrev, true);
		} else {
			revalidateButton(buttonPrev, false);
		}

		if(iterator+1 < questionPanelList.size()) {
			revalidateButton(buttonNext, true);
		} else {
			revalidateButton(buttonNext, false);
		}

		revalidate();
		repaint();
		pack();
	}

	public QuestionPanel getNextQuestionPanel() {
		if (questionPanelList.size() - 1 > iterator) {
			iterator++;
			return questionPanelList.get(iterator);
		}

		return null;
	}

	public QuestionPanel getPrevQuestionPanel() {
		if (iterator > 0) {
			iterator--;
			return questionPanelList.get(iterator);
		}
		return null;
	}

	private void revalidateButton(JButton button, boolean toEnable) {
		if((button.isEnabled() && !toEnable) || (!button.isEnabled() && toEnable)) {
			button.setEnabled(toEnable);
		}
	}

	private void setQuestionImage(ImageIcon icon) {
		if (icon != null) {
			icon = QuizumUtils.fitIcon(icon, 600, getHeight());
		}
		imageLabel.setIcon(icon);
		imageLabel.repaint();
	}

}


text:
package org.innovateuk.ifs.competition.domain;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.innovateuk.ifs.category.domain.CategoryLink;
import org.innovateuk.ifs.category.domain.ResearchCategory;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
@DiscriminatorValue("org.innovateuk.ifs.competition.domain.Competition#researchCategory")
public class CompetitionResearchCategoryLink extends CategoryLink<Competition, ResearchCategory> {

    @ManyToOne(optional = false)
    @JoinColumn(name = "class_pk", referencedColumnName = "id")
    private Competition competition;

    public CompetitionResearchCategoryLink() {

    }

    public CompetitionResearchCategoryLink(Competition competition, ResearchCategory category) {
        super(category);

        if (competition == null) {
            throw new NullPointerException("competition cannot be null");
        }

        this.competition = competition;
    }

    public Competition getCompetition() {
        return competition;
    }

    @Override
    public Competition getEntity() {
        return competition;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        CompetitionResearchCategoryLink that = (CompetitionResearchCategoryLink) o;

        return new EqualsBuilder()
                .appendSuper(super.equals(o))
                .append(competition.getId(), that.competition.getId())
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .appendSuper(super.hashCode())
                .append(competition.getId())
                .toHashCode();
    }
}


text:
#if !DNXCORE50
using System;
using System.Linq;
using System.Security;
using System.Security.Permissions;
using Autofac.Test.Scenarios.Graph1;
using Xunit;

namespace Autofac.Test.PartialTrust
{
    /// <summary>
    /// Fixture containing the set of tests that will execute in partial trust.
    /// </summary>
    /// <remarks>
    /// <para>
    /// These tests are not marked with any NUnit attributes because they actually get executed
    /// through NUnit via the <see cref="Autofac.Test.PartialTrust.PartialTrustTestExecutor"/>.
    /// Any public void method with no parameters found here will execute as a unit test.
    /// </para>
    /// </remarks>
    public class PartialTrustTests : MarshalByRefObject
    {
        public void AppDomainSetupCorrect()
        {
            // The sandbox should have the expected name and we shouldn't be able to demand unrestricted permissions.
            Assert.Equal("Sandbox", AppDomain.CurrentDomain.FriendlyName);
            Assert.Throws<SecurityException>(() => new SecurityPermission(PermissionState.Unrestricted).Demand());
        }

        public void Integration_CanCorrectlyBuildGraph1()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<A1>().SingleInstance();
            builder.RegisterType<CD1>().As<IC1, ID1>().SingleInstance();
            builder.RegisterType<E1>().SingleInstance();
            builder.Register(ctr => new B1(ctr.Resolve<A1>()));

            var target = builder.Build();

            var e = target.Resolve<E1>();
            var a = target.Resolve<A1>();
            var b = target.Resolve<B1>();
            var c = target.Resolve<IC1>();
            var d = target.Resolve<ID1>();

            Assert.IsType<CD1>(c);
            var cd = (CD1)c;

            Assert.Same(a, b.A);
            Assert.Same(a, cd.A);
            Assert.NotSame(b, cd.B);
            Assert.Same(c, e.C);
            Assert.NotSame(b, e.B);
            Assert.NotSame(e.B, cd.B);
        }

        public interface I1<T> { }
        public interface I2<T> { }
        public class C<T> : I1<T>, I2<T> { }

        public void Integration_MultipleServicesOnAnOpenGenericType_ShareTheSameRegistration()
        {
            var builder = new ContainerBuilder();
            builder.RegisterGeneric(typeof(C<>)).As(typeof(I1<>), typeof(I2<>));
            var container = builder.Build();
            container.Resolve<I1<int>>();
            var count = container.ComponentRegistry.Registrations.Count();
            container.Resolve<I2<int>>();
            Assert.Equal(count, container.ComponentRegistry.Registrations.Count());
        }
    }
}
#endif


text:
function write_interconnect_textfiles(dirname, out)
% WRITE_INTERCONNECT_TEXTFILES - Write interconnect text file info for a given directory
%
%  WRITE_INTERCONNECT_TEXTFILES(DIRNAME, OUT)
%
%  Inputs:
%  DIRNAME - The full path to the directory where the textfiles should be written
%  OUT - A structure with the following fields:
%  -------------------------------|-----------------------------
%  StimTrigger                    | Times of stimulus triggers
%  StimTriggerOFF                 | Off times of all stimuli
%  FrameTriggerRaw                | Times of all frame triggers (not divided by stimulus)
%  StimulusMonitorVerticalRefresh | Vertical refresh times
%  TwoPhotonFrameTrigger          | 2-photon frame trigger
%  StimCode                       | Stim codes for each stim trigger
%
%  If there is a field 'FrameTrigger', it is assumed that this is a cell list with frame
%  triggers divided by stimulus (see WRITE_STIMTIMES_TXT)
%
%  It writes the files 'stimtimes.txt','verticalblanking.txt','stimontimes.txt',
%  'twophotontimes.txt'
%
%  This function also writes an empty text file 'Intan_decoding_finished.txt'. This serves
%  to indicate that the program need not decode this directory again.
%

if ~isfield(out,'FrameTrigger'),
	out.FrameTrigger = frametimesraw2frametimes(out.FrameTriggerRaw,out.StimTrigger);
end;

fnames = {'stimtimes.txt','stimontimes.txt','verticalblanking.txt','twophotontimes.txt','Intan_decoding_finished.txt'};
for i=1:length(fnames),
	if exist([dirname filesep fnames{i}],'file'),
		delete([dirname filesep fnames{i}]);
	end;
end;

write_stimtimes_txt(dirname,out.StimCode,out.StimTrigger,out.FrameTrigger);
write_stimtimes_txt(dirname,out.StimCode,out.StimTrigger);

if isfield(out,'TwoPhotonFrameTrigger'),
	dlmwrite([dirname filesep 'twophotontimes.txt'],out.TwoPhotonFrameTrigger,...
		'delimiter','\n','precision','%10.5f');
end;

if isfield(out,'StimulusMonitorVerticalRefresh'),
	dlmwrite([dirname filesep 'verticalblanking.txt'],out.StimulusMonitorVerticalRefresh,...
		'delimiter','\n','precision','%10.5f');
end;

 % now write an empty file indicating that our work is done
fid=fopen([dirname filesep 'Intan_decoding_finished.txt'],'wt');
fclose(fid);


text:
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android.desugar;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import com.google.common.collect.ImmutableList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

/**
 * Fixer of classes that extend interfaces with default methods to declare any missing methods
 * explicitly and call the corresponding companion method generated by {@link InterfaceDesugaring}.
 */
public class DefaultMethodClassFixer extends ClassVisitor {

  private final ClassReaderFactory classpath;
  private final ClassReaderFactory bootclasspath;
  private final ClassLoader targetLoader;
  private final HashSet<String> instanceMethods = new HashSet<>();

  private boolean isInterface;
  private String internalName;
  private ImmutableList<String> directInterfaces;
  private String superName;

  public DefaultMethodClassFixer(ClassVisitor dest, ClassReaderFactory classpath,
      ClassReaderFactory bootclasspath, ClassLoader targetLoader) {
    super(Opcodes.ASM5, dest);
    this.classpath = classpath;
    this.bootclasspath = bootclasspath;
    this.targetLoader = targetLoader;
  }

  @Override
  public void visit(
      int version,
      int access,
      String name,
      String signature,
      String superName,
      String[] interfaces) {
    checkState(this.directInterfaces == null);
    isInterface = BitFlags.isSet(access, Opcodes.ACC_INTERFACE);
    internalName = name;
    checkArgument(superName != null || "java/lang/Object".equals(name), // ASM promises this
        "Type without superclass: %s", name);
    this.directInterfaces = ImmutableList.copyOf(interfaces);
    this.superName = superName;
    super.visit(version, access, name, signature, superName, interfaces);
  }

  @Override
  public void visitEnd() {
    if (!isInterface && defaultMethodsDefined(directInterfaces)) {
      // Inherited methods take precedence over default methods, so visit all superclasses and
      // figure out what methods they declare before stubbing in any missing default methods.
      recordInheritedMethods();
      stubMissingDefaultMethods();
    }
    super.visitEnd();
  }

  @Override
  public MethodVisitor visitMethod(
      int access, String name, String desc, String signature, String[] exceptions) {
    // Keep track of instance methods implemented in this class for later.
    if (!isInterface) {
      recordIfInstanceMethod(access, name, desc);
    }
    return super.visitMethod(access, name, desc, signature, exceptions);
  }

  private void stubMissingDefaultMethods() {
    TreeSet<Class<?>> allInterfaces = new TreeSet<>(InterfaceComparator.INSTANCE);
    for (String direct : directInterfaces) {
      // Loading ensures all transitively implemented interfaces can be loaded, which is necessary
      // to produce correct default method stubs in all cases.  We could do without classloading but
      // it's convenient to rely on Class.isAssignableFrom to compute subtype relationships, and
      // we'd still have to insist that all transitively implemented interfaces can be loaded.
      // We don't load the visited class, however, in case it's a generated lambda class.
      Class<?> itf = loadFromInternal(direct);
      collectInterfaces(itf, allInterfaces);
    }

    Class<?> superclass = loadFromInternal(superName);
    for (Class<?> interfaceToVisit : allInterfaces) {
      // if J extends I, J is allowed to redefine I's default methods.  The comparator we used
      // above makes sure we visit J before I in that case so we can use J's definition.
      if (superclass != null && interfaceToVisit.isAssignableFrom(superclass)) {
        // superclass already implements this interface, so we must skip it.  The superclass will
        // be similarly rewritten or comes from the bootclasspath; either way we don't need to and
        // shouldn't stub default methods for this interface.
        continue;
      }
      stubMissingDefaultMethods(interfaceToVisit.getName().replace('.', '/'));
    }
  }

  private Class<?> loadFromInternal(String internalName) {
    try {
      return targetLoader.loadClass(internalName.replace('/', '.'));
    } catch (ClassNotFoundException e) {
      throw new IllegalStateException(
          "Couldn't load " + internalName + ", is the classpath complete?", e);
    }
  }

  private void collectInterfaces(Class<?> itf, Set<Class<?>> dest) {
    checkArgument(itf.isInterface());
    if (!dest.add(itf)) {
      return;
    }
    for (Class<?> implemented : itf.getInterfaces()) {
      collectInterfaces(implemented, dest);
    }
  }

  private void recordInheritedMethods() {
    InstanceMethodRecorder recorder = new InstanceMethodRecorder();
    String internalName = superName;
    while (internalName != null) {
      ClassReader bytecode = bootclasspath.readIfKnown(internalName);
      if (bytecode == null) {
        bytecode = checkNotNull(classpath.readIfKnown(internalName),
            "Superclass not found: %s", internalName);
      }
      bytecode.accept(recorder, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
      internalName = bytecode.getSuperName();
    }
  }

  private void recordIfInstanceMethod(int access, String name, String desc) {
    if (BitFlags.noneSet(access, Opcodes.ACC_STATIC)) {
      // Record all declared instance methods, including abstract, bridge, and native methods, as
      // they all take precedence over default methods.
      instanceMethods.add(name + ":" + desc);
    }
  }

  /**
   * Recursively searches the given interfaces for default methods not implemented by this class
   * directly.  If this method returns true we need to think about stubbing missing default methods.
   */
  private boolean defaultMethodsDefined(ImmutableList<String> interfaces) {
    for (String implemented : interfaces) {
      ClassReader bytecode = classpath.readIfKnown(implemented);
      if (bytecode != null && !bootclasspath.isKnown(implemented)) {
        // Class in classpath and bootclasspath is a bad idea but in any event, assume the
        // bootclasspath will take precedence like in a classloader.
        // We can skip code attributes as we just need to find default methods to stub.
        DefaultMethodFinder finder = new DefaultMethodFinder();
        bytecode.accept(finder, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
        if (finder.foundDefaultMethods()) {
          return true;
        }
      }
      // Else interface isn't on the classpath, which indicates incomplete classpaths. For now
      // we'll just assume the missing interfaces don't declare default methods but if they do
      // we'll end up with concrete classes that don't implement an abstract method, which can
      // cause runtime failures.  The classpath needs to be fixed in this case.
    }
    return false;
  }

  /**
   * Returns {@code true} for non-bridge default methods not in {@link #instanceMethods}.
   */
  private boolean shouldStub(int access, String name, String desc) {
    // Ignore private methods, which technically aren't default methods and can only be called from
    // other methods defined in the interface.  This also ignores lambda body methods, which is fine
    // as we don't want or need to stub those.  Also ignore bridge methods as javac adds them to
    // concrete classes as needed anyway and we handle them separately for generated lambda classes.
    return BitFlags.noneSet(access,
            Opcodes.ACC_ABSTRACT | Opcodes.ACC_STATIC | Opcodes.ACC_BRIDGE | Opcodes.ACC_PRIVATE)
        && !instanceMethods.contains(name + ":" + desc);
  }

  private void stubMissingDefaultMethods(String implemented) {
    if (bootclasspath.isKnown(implemented)) {
      // Default methods on the bootclasspath will be available at runtime, so just ignore them.
      return;
    }
    ClassReader bytecode = checkNotNull(classpath.readIfKnown(implemented),
        "Couldn't find interface %s implemented by %s", implemented, internalName);
    // We can skip code attributes as we just need to find default methods to stub.
    bytecode.accept(new DefaultMethodStubber(), ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG);
  }

  /**
   * Visitor for interfaces that produces delegates in the class visited by the outer
   * {@link DefaultMethodClassFixer} for every default method encountered.
   */
  private class DefaultMethodStubber extends ClassVisitor {

    private String interfaceName;

    public DefaultMethodStubber() {
      super(Opcodes.ASM5);
    }

    @Override
    public void visit(
        int version,
        int access,
        String name,
        String signature,
        String superName,
        String[] interfaces) {
      checkArgument(BitFlags.isSet(access, Opcodes.ACC_INTERFACE));
      checkState(interfaceName == null);
      interfaceName = name;
    }

    @Override
    public MethodVisitor visitMethod(
        int access, String name, String desc, String signature, String[] exceptions) {
      if (shouldStub(access, name, desc)) {
        // Remember we stubbed this method in case it's also defined by subsequently visited
        // interfaces.  javac would force the method to be defined explicitly if there any two
        // definitions conflict, but see stubMissingDefaultMethods() for how we deal with default
        // methods redefined in interfaces extending another.
        recordIfInstanceMethod(access, name, desc);

        // Add this method to the class we're desugaring and stub in a body to call the default
        // implementation in the interface's companion class. ijar omits these methods when setting
        // ACC_SYNTHETIC modifier, so don't.
        // Signatures can be wrong, e.g., when type variables are introduced, instantiated, or
        // refined in the class we're processing, so drop them.
        MethodVisitor stubMethod =
            DefaultMethodClassFixer.this.visitMethod(access, name, desc, (String) null, exceptions);

        int slot = 0;
        stubMethod.visitVarInsn(Opcodes.ALOAD, slot++); // load the receiver
        Type neededType = Type.getMethodType(desc);
        for (Type arg : neededType.getArgumentTypes()) {
          stubMethod.visitVarInsn(arg.getOpcode(Opcodes.ILOAD), slot);
          slot += arg.getSize();
        }
        stubMethod.visitMethodInsn(
            Opcodes.INVOKESTATIC,
            interfaceName + InterfaceDesugaring.COMPANION_SUFFIX,
            name,
            InterfaceDesugaring.companionDefaultMethodDescriptor(interfaceName, desc),
            /*itf*/ false);
        stubMethod.visitInsn(neededType.getReturnType().getOpcode(Opcodes.IRETURN));

        stubMethod.visitMaxs(0, 0); // rely on class writer to compute these
        stubMethod.visitEnd();
      }
      return null; // we don't care about the actual code in these methods
    }
  }

  /**
   * Visitor for interfaces that recursively searches interfaces for default method declarations.
   */
  private class DefaultMethodFinder extends ClassVisitor {

    @SuppressWarnings("hiding") private ImmutableList<String> interfaces;
    private boolean found;

    public DefaultMethodFinder() {
      super(Opcodes.ASM5);
    }

    @Override
    public void visit(
        int version,
        int access,
        String name,
        String signature,
        String superName,
        String[] interfaces) {
      checkArgument(BitFlags.isSet(access, Opcodes.ACC_INTERFACE));
      checkState(this.interfaces == null);
      this.interfaces = ImmutableList.copyOf(interfaces);
    }

    public boolean foundDefaultMethods() {
      return found;
    }

    @Override
    public void visitEnd() {
      if (!found) {
        found = defaultMethodsDefined(this.interfaces);
      }
    }

    @Override
    public MethodVisitor visitMethod(
        int access, String name, String desc, String signature, String[] exceptions) {
      if (!found && shouldStub(access, name, desc)) {
        // Found a default method we're not ignoring (instanceMethods at this point contains methods
        // the top-level visited class implements itself).
        found = true;
      }
      return null; // we don't care about the actual code in these methods
    }
  }

  private class InstanceMethodRecorder extends ClassVisitor {

    public InstanceMethodRecorder() {
      super(Opcodes.ASM5);
    }

    @Override
    public void visit(
        int version,
        int access,
        String name,
        String signature,
        String superName,
        String[] interfaces) {
      checkArgument(BitFlags.noneSet(access, Opcodes.ACC_INTERFACE));
      super.visit(version, access, name, signature, superName, interfaces);
    }

    @Override
    public MethodVisitor visitMethod(
        int access, String name, String desc, String signature, String[] exceptions) {
      recordIfInstanceMethod(access, name, desc);
      return null;
    }
  }

  /** Comparator for interfaces that compares by whether interfaces extend one another. */
  enum InterfaceComparator implements Comparator<Class<?>> {
    INSTANCE;

    @Override
    public int compare(Class<?> o1, Class<?> o2) {
      checkArgument(o1.isInterface());
      checkArgument(o2.isInterface());
      if (o1 == o2) {
        return 0;
      }
      if (o1.isAssignableFrom(o2)) { // o1 is supertype of o2
        return 1; // we want o1 to come after o2
      }
      if (o2.isAssignableFrom(o1)) { // o2 is supertype of o1
        return -1; // we want o2 to come after o1
      }
      // o1 and o2 aren't comparable so arbitrarily impose lexicographical ordering
      return o1.getName().compareTo(o2.getName());
    }
  }
}


text:
namespace google {
namespace protobuf {

#ifdef _WIN32

struct GoogleOnceInternal {
  GoogleOnceInternal() {
    InitializeCriticalSection(&critical_section);
  }
  ~GoogleOnceInternal() {
    DeleteCriticalSection(&critical_section);
  }
  CRITICAL_SECTION critical_section;
};

GoogleOnceType::GoogleOnceType() {
  // internal_ may be non-NULL if Init() was already called.
  if (internal_ == NULL) internal_ = new GoogleOnceInternal;
}

void GoogleOnceType::Init(void (*init_func)()) {
  // internal_ may be NULL if we're still in dynamic initialization and the
  // constructor has not been called yet.  As mentioned in once.h, we assume
  // that the program is still single-threaded at this time, and therefore it
  // should be safe to initialize internal_ like so.
  if (internal_ == NULL) internal_ = new GoogleOnceInternal;

  EnterCriticalSection(&internal_->critical_section);
  if (!initialized_) {
    init_func();
    initialized_ = true;
  }
  LeaveCriticalSection(&internal_->critical_section);
}

#endif

}  // namespace protobuf
}  // namespace google


text:
import boto
import sys
import json
import time
import boto.sqs
import config_manager as conf_man
import uuid
import sns_sqs
import dynamo_utils as dutils
import argparse
import bottle
from bottle import template
import ast

def update_record(record, key, value):
    record[key] = value
    record.save(overwrite=True)
    return

def submit_task(app, task_desc_file):

    uid = str(uuid.uuid1())
    t   = int(time.time())
    tstamp = str(time.strftime('%Y-%m-%d %H:%M:%S'))

    task_desc = template(task_desc_file,
                         uid=uid,
                         time=t,
                         tstamp=tstamp)
    print "-"*50
    print task_desc
    print "-"*50
    data = ast.literal_eval(task_desc)

    dutils.dynamodb_update(app.config["dyno.conn"], data)
    sns_sqs.publish(app.config["sns.conn"], app.config["instance.tags"]["JobsSNSTopicARN"],
                    data)
    return uid

def submit_task_N(app, task_desc_file, count):
    qtype   = "Test"
    jobdur  = 0
    jobname = "tput_test_{0}_{1}_{2}s".format(count, qtype, jobdur)
    jobids  = []
    test_q  = app.config["sqs.conn"].get_queue("Turing2-0-TestSQS-16WUKXE5TAGER")
    attr = {"job_id": {"data_type"   : "String",
                       "string_value": "Test"}}
    sqs_conn = app.config["sqs.conn"]
    start   = time.time()
    messages = []
    for i in range(0,int(count)):
        uid = str(uuid.uuid1())

        job_desc= { "jobname"            : "{0}".format(jobname),
                    "job_id"             : uid,
                    "username"           : "Yadu",
                    "i_user_id"          : "amzn1.account.AEKWXVYINCBBNY5MPRMOYND6CWWA",
                    "i_user_role"        : "arn:aws:iam::{0}:role/{1}".format(968994658855, "klab_public"),
                    "user_email"         : "yadu@uchicago.edu",
                    "user_email"         : "yadunand@uchicago.edu",
                    "submit_time"        : int(time.time()),
                    "submit_stamp"       : str(time.strftime('%Y-%m-%d %H:%M:%S')),
                    "status"             : "pending",
                    "executable"         : "/bin/sleep {0}".format(jobdur),
                    "queue"              : "{0}".format(qtype),
                    "i_script_name"      : "test.sh",
                    "i_script"           : "#Nothing",
                    "jobtype"            : "script",
                    "outputs"            : "",
                    "walltime"           : "{0}".format(jobdur*2 + 1) }
        message = {
            "Type" : "Notification",
            "MessageId" : "1eed1b29-9094-5d3e-b368-54eb58645f37",
            "Message" : json.dumps(job_desc),
            "Signature" : "V6kijhKkNlnkPvybJ3njb83eeHRlTuoqqyrzWbsuMtuXSSsxctxyBjM/gM57RB3hSKsWCfLwtjwR9eg4Uy5D59knNjtHoHUpdMqjQPDR21lO1OZCU2gWLQR3C1wpvkwpGEgNl5jGFZF3yzpX6j0kG8NU1y5KLnRKz4LOh2FZyUXkoGxdomf/bWctWrrMy3YcJzv6NmXIyJmJ/xyWMbOnPu5uiz6SsY7uJ7/e371Kqm8NO0WWyPbiu3ZsqPSPn5Qd0LzQfZVbmAwya+eeXelewMDL6nqGKhyYZMdo6PSlDH4q7RxYAusg76mKNPmFT9KGpEZIG72z1+M44pvIdJxMcg==",
            "SigningCertURL" : "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem"
        }

        messages.extend([message])
        jobids.extend([uid])
        dutils.dynamodb_update(app.config["dyno.conn"], job_desc)

    print "Done writing jobs to DDB in {0}s".format(time.time() - start)
    start = time.time()
    for message in messages:
        sqs_conn.send_message(test_q, json.dumps(message))
        #sns_sqs.publish(app.config["sns.conn"], app.config["instance.tags"][qtype + "JobsSNSTopicARN"],
        #                job_desc)
    for j in jobids:
        print "[JOBIDS] : job_id:{0} ".format(j)
    print "Completed in {0}s".format(time.time() - start)
    return jobids

def debug_print(string):
    if GLOBAL_VERBOSE :
        print string

def cancel_task(app, jobid):
    debug_print("Cancelling task : {0}".format(jobid))

    record = dutils.dynamodb_get(app.config["dyno.conn"], jobid)
    tstamp = str(time.strftime('%Y-%m-%d %H:%M:%S'))

    update_record(record, "status", "cancelled")
    update_record(record, "reason", "User request cancel")
    update_record(record, "cancel_time", tstamp)
    debug_print ("{0} - {1} - {2}".format(record["job_id"], record["status"], record["reason"]))
    return True

def status_task(app, jobid):
    debug_print("Status task : {0}".format(jobid))

    record = dutils.dynamodb_get(app.config["dyno.conn"], jobid)
    status = {}

    if GLOBAL_VERBOSE:
        for item in record.items():
            print "|{0:10}  | {1:50}".format(item[0], item[1])

    print record["status"]
    return record["status"]

GLOBAL_VERBOSE=False

if __name__ == "__main__":

    parser   = argparse.ArgumentParser()
    parser.add_argument("-j", "--jobinfo",  help="json job description or jobid", required=True)
    parser.add_argument("-r", "--request",  help="Request type [submit, status, cancel]", required=True)
    parser.add_argument("-t", "--tput_count",  help="Number of tasks to submit", required=True)
    parser.add_argument("-c", "--conffile", default="production.conf", help="Config file path. Defaults to ./test.conf")
    parser.add_argument("-v", "--verbose",  dest='verbose', action='store_true', help="Verbose output")
    args   = parser.parse_args()

    if args.verbose is True:
        GLOBAL_VERBOSE=True

    app = conf_man.load_configs(args.conffile)

    if args.request.lower() == "submit":
        #uid = submit_task(app, args.jobinfo)
        uid = submit_task_N(app, args.jobinfo, args.tput_count)
        #print "Uid : {0}".format(uid)

    elif args.request.lower() == "status":
        status_task(app, args.jobinfo)

    elif args.request.lower() == "cancel":
        cancel_task(app, args.jobinfo)

    else:
        print "Unknown request"
        exit(-1)

    exit(0)


text:
Proust (the name is inspired by the french writer known for his "madeleine") is a Business Event Tracker. This framework uses "event" which brings ability to synchronise business moments easily according to callback attached to a cawin (check and wait if necessary).

# Main features
* Event resources : this is the most simple resource on proust. The event is the earth of proust
  1. **id**          : numeric id of the event (its just a way to identify uniquely an event on the server)
  2. **topic**       : a category of the event (in order to have a first organisation of event and a schema which define the payload structure)
  3. **status**      : awaited, occured, invalidated
  4. **description** : partial payload defined in order to "recognise" the business event while event is awaited
  5. **payload**     : payload are only available when the event occured
* Description Category : Structure use to optimise the way description is searched
  1. **name**  : name of the category
  2. **paths** : list of path to values defined in the description. These path are used to extract description from existing description of an incoming event or payload of an event without description. The search of matched events are against the digest of the descriptions. Descriptions are evaluated automatically by the proust engine while event with description is published
* Cawin resources : a resource used to call a service in response to the occurence of an event
  1. **id**       : numeric id of the cawin
  2. **event**    : id of the related event
  4. **active**   : if true cawin intercept events by calling callback otherwise the cawin do nothing
  6. **callback** : url of the action to call if event occured or when event will occure

There are two ways to push an event :
 1. the event is pushed (using HTTP PUT) with a description but no payload. In this case Proust looks for an event which matches this description. If an event is found, this event is provided. If no event is found, a new event is created with the awaited status and the related description. This new event is provided.
 2. the event is pushed (using HTTP PUT) with a payload. In this case, Proust looks for the first event in the same topic which matches its description. If there's no matching event, a new event is created with the occured status. If there's a matching event an error is raised : event already occured.

A cawin could be used in order to wait for an event to occur. For exemple if an event is pushed but the response is an awaited event then a cawin could be added in order to wakeup a service which needs the event and its potentially its payload.


text:
namespace Google.Cloud.AIPlatform.V1.Snippets
{
    // [START aiplatform_v1_generated_VizierService_GetStudy_sync_flattened_resourceNames]
    using Google.Cloud.AIPlatform.V1;

    public sealed partial class GeneratedVizierServiceClientSnippets
    {
        /// <summary>Snippet for GetStudy</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void GetStudyResourceNames()
        {
            // Create client
            VizierServiceClient vizierServiceClient = VizierServiceClient.Create();
            // Initialize request argument(s)
            StudyName name = StudyName.FromProjectLocationStudy("[PROJECT]", "[LOCATION]", "[STUDY]");
            // Make the request
            Study response = vizierServiceClient.GetStudy(name);
        }
    }
    // [END aiplatform_v1_generated_VizierService_GetStudy_sync_flattened_resourceNames]
}


text:
import { LightningElement, wire, track, api } from "lwc";
import { refreshApex } from "@salesforce/apex";

import getAddressSettingsVModel from "@salesforce/apex/AddressSettingsController.getAddressSettingsVModel";

import stgAddressSettingsTitle from "@salesforce/label/c.stgAddressSettingsTitle";
import stgContactMultiAddressesEnabled from "@salesforce/label/c.stgContactMultiAddressesEnabled";
import stgHelpContactAddrs from "@salesforce/label/c.stgHelpContactAddrs";
import stgAccountTypesMultiAddressesEnabled from "@salesforce/label/c.stgAccountTypesMultiAddressesEnabled";
import stgHelpAddressAccRecType from "@salesforce/label/c.stgHelpAddressAccRecType";
import stgAccountRecordTypeGroupLabelTitle from "@salesforce/label/c.stgAccountRecordTypeGroupLabelTitle";
import stgAccountRecordTypeAvailableListTitle from "@salesforce/label/c.stgAccountRecordTypeAvailableListTitle";
import stgAccountRecordTypeSelectedListTitle from "@salesforce/label/c.stgAccountRecordTypeSelectedListTitle";
import stgSimpleAddressChangeUpdate from "@salesforce/label/c.stgSimpleAddressChangeUpdate";
import stgHelpSimpleAddrChangeIsUpdate from "@salesforce/label/c.stgHelpSimpleAddrChangeIsUpdate";

export default class addressSettings extends LightningElement {
    isEditMode = false;
    affordancesDisabledToggle = false;

    @track addressSettingsViewModel;
    @track addressSettingsWireResult;

    labelReference = {
        stgAddressSettingsTitle: stgAddressSettingsTitle,
        stgContactMultiAddressesEnabled: stgContactMultiAddressesEnabled,
        stgHelpContactAddrs: stgHelpContactAddrs,
        stgAccountTypesMultiAddressesEnabled: stgAccountTypesMultiAddressesEnabled,
        stgHelpAddressAccRecType: stgHelpAddressAccRecType,
        stgAccountRecordTypeGroupLabelTitle: stgAccountRecordTypeGroupLabelTitle,
        stgAccountRecordTypeAvailableListTitle: stgAccountRecordTypeAvailableListTitle,
        stgAccountRecordTypeSelectedListTitle: stgAccountRecordTypeSelectedListTitle,
        stgSimpleAddressChangeUpdate: stgSimpleAddressChangeUpdate,
        stgHelpSimpleAddrChangeIsUpdate: stgHelpSimpleAddrChangeIsUpdate,
    };

    inputAttributeReference = {
        multiAddressEnabledToggleId: "multiAddressModel",
        accountRecTypesDualListboxId: "accountRectypeModel",
        simpleAddressChangeTreatedAsUpdateToggleId: "simpleUpdateModel",
    };

    get affordancesDisabled() {
        if (!this.isEditMode || this.affordancesDisabledToggle === true) {
            return true;
        }
        return undefined;
    }

    @api
    handleSaveCanvasRender() {
        this.template.querySelector("c-settings-save-canvas").focusOnTitle();
    }

    @wire(getAddressSettingsVModel)
    addressSettingsViewModelWire(result) {
        this.addressSettingsWireResult = result;
        if (result.data) {
            this.addressSettingsViewModel = result.data;
        } else if (result.error) {
            //console.log("error retrieving accountmodelsettingsvmodel");
        }
    }

    handleMultiAddressEnabledChange(event) {
        let hierarchySettingsChange = {
            settingsType: "boolean",
            settingsName: "Contacts_Addresses_Enabled__c",
            settingsValue: event.detail.value,
        };
        this.template.querySelector("c-settings-save-canvas").handleHierarchySettingsChange(hierarchySettingsChange);
    }

    handleAccountRecordTypesChange(event) {
        // add selected values to hierarchySettingsChanges object
        let hierarchySettingsChange = {
            settingsType: "array",
            settingsName: "Accounts_Addresses_Enabled__c",
            settingsValue: event.detail.value,
        };

        this.template.querySelector("c-settings-save-canvas").handleHierarchySettingsChange(hierarchySettingsChange);
    }

    handleSimpleAddressUpdateChange(event) {
        let hierarchySettingsChange = {
            settingsType: "boolean",
            settingsName: "Simple_Address_Change_Treated_as_Update__c",
            settingsValue: event.detail.value,
        };

        this.template.querySelector("c-settings-save-canvas").handleHierarchySettingsChange(hierarchySettingsChange);
    }

    handleSettingsEditModeChange(event) {
        this.isEditMode = !event.detail;
        this.affordancesDisabledToggle = event.detail;
    }

    handleSettingsSaving(event) {
        this.affordancesDisabledToggle = true;
        // TODO: perform client side validation

        // if validation fails, call this.handleValidationFailure()
        //this.template.querySelector("c-settings-save-canvas").handleValidationFailure();

        // else, update hierarchy settings
        this.template.querySelector("c-settings-save-canvas").updateHierarchySettings();
    }

    handleSettingsSaveCompleted(event) {
        this.affordancesDisabledToggle = false;
        this.refreshAllApex();
    }

    handleSettingsSaveCancel(event) {
        this.refreshAllApex();
    }

    refreshAllApex() {
        refreshApex(this.addressSettingsWireResult).then(() => {
            this.template.querySelectorAll("c-settings-row-dual-listbox").forEach((dualListBox) => {
                dualListBox.resetValue();
            });
            this.template.querySelectorAll("c-settings-row-input").forEach((input) => {
                input.resetValue();
            });
        });
    }
}


text:
url_handlers

Used by packaged apps
to specify URL patterns the app wants to intercept and handle. An app can
define multiple URL handlers under this manifest entry, each having an identifier,
a URL pattern, and a title.
Here's an example of how to specify url_handlers:

"url_handlers": {
  "view_foo_presentation": {
    "matches": [
      "https://www.foo.com/presentation/view/*"
    ],
    "title": "View Foo presentation"
  },
  "view_bar_presentation": {
    "matches": [
      "https://www.bar.com/view/slideshow/*"
    ],
    "title": "View bar presentation"
  },
  "edit_spreadsheet": {
    "matches": [
      "https://www.foo.com/spreadsheet/edit/*",
      "https://www.bar.com/spreadsheet/edit/*"
    ],
    "title": "Edit spreadsheet"
  }
}

Apps can only register to handle URL patterns within domains that they own,
that is, can prove ownership of as determined by the
Chrome Web Store.
Apps that violate this requirement and attempt to register for handling external
URLs will be rejected by the Chrome Web Store on upload.

This automatically means that at least a complete domain should always be
specified for all the patterns under matches (otherwise ownership
cannot be verified).

Upon successful registration and installation, an app will be launched for all
matching navigations inside browser tabs as well as other apps. The app will
receive a new kind of the
app.runtime.onLaunched
event, with the launchData
object containing the matched handler's identifier (such as "view_foo_presentation"
above), the URL being navigated to, and the referrer's URL.

The title field is reserved for future use in all relevant UI elements.
It should describe the action that the app performs when launched with this type
of URL handler.


text:
<?php

trait GPNodeLoader {

  private static $cache = [];

  public static function createFromType($type, array $data = []) {
    $class = GPNodeMap::getClass($type);
    return new $class($data);
  }

  private static function nodeFromArray(array $data) {
    $class = GPNodeMap::getClass($data['type']);
    $node = new $class(json_decode($data['data'], true));
    $node->id = $data['id'];
    $node->updated = $data['updated'];
    $node->created = $data['created'];
    return $node;
  }

  public static function getByID($id) {
    if (!array_key_exists($id, self::$cache)) {
      $node_data = get_called_class() === GPNode::class ?
        GPDatabase::get()->getNodeByID($id) :
        GPDatabase::get()->getNodeByIDType($id, self::getType());
      if ($node_data === null) {
        return null;
      }
      self::$cache[$id] = self::nodeFromArray($node_data);
    }
    if (
      get_called_class() !== GPNode::class &&
      self::$cache[$id]->getType() !== self::getType()
    ) {
      return null;
    }
    return self::$cache[$id];
  }

  public static function multiGetByID(array $ids) {
    $ids = key_by_value($ids);
    $to_fetch = array_diff_key($ids, self::$cache);
    $node_datas = get_called_class() === GPNode::class ?
      GPDatabase::get()->multigetNodeByIDType($to_fetch) :
      GPDatabase::get()->multigetNodeByIDType($to_fetch, self::getType());
    foreach ($node_datas as $node_data) {
      self::$cache[$node_data['id']] = self::nodeFromArray($node_data);
    }
    $nodes = array_select_keys(self::$cache, $ids);
    if (get_called_class() === GPNode::class) {
      return $nodes;
    }
    $type = self::getType();
    return array_filter(
      $nodes,
      function($node) use ($type) { return $node->getType() === $type; }
    );
  }

  public static function __callStatic($name, array $arguments) {
    $only_one = false;
    $len = mb_strlen($name);
    if (
      strpos($name, 'getBy') === 0  &&
      strpos($name, 'Range') === ($len - 5)
    ) {
      $type_name = strtolower(mb_substr($name, 5, $len - 10));
      $range = true;
    } else if (substr_compare($name, 'getBy', 0, 5) === 0) {
      $type_name = strtolower(mb_substr($name, 5));
    } else if (substr_compare($name, 'getOneBy', 0, 8) === 0) {
      $type_name = strtolower(mb_substr($name, 8));
      $only_one = true;
    } else if (substr_compare($name, 'getAllWith', 0, 10) === 0) {
      $type_name = strtolower(mb_substr($name, 10));
      $get_all_with_type = true;
    }

    if (isset($type_name)) {
      $class = get_called_class();
      $data_type = static::getDataTypeByName($type_name);
      Assert::truthy($data_type, $name.' is not a method on '.$class);
      if (isset($range)) {
        $required_args = 2;
      } else if (isset($get_all_with_type)) {
        $required_args = 0;
      } else {
        $required_args = 1;
      }
      Assert::truthy(
        count($arguments) >= $required_args,
        GPErrorText::wrongArgs($class, $name, $required_args, count($arguments))
      );
      if ($arguments) {
        $arg = idx0($arguments);
        foreach (make_array($arg) as $val) {
          $data_type->assertValueIsOfType($val);
        }
      }
      if (isset($range)) {
        array_unshift($arguments, $data_type->getIndexedType());
        $results = self::getByIndexDataRange($arguments);
      } else if (isset($get_all_with_type)) {
        $results = self::getByIndexDataAll($data_type->getIndexedType());
      } else {
        $results = self::getByIndexData($data_type->getIndexedType(), $arg);
      }
      return $only_one ? idx0($results) : $results;
    }
    throw new GPException('Method '.$name.' not found in '.get_called_class());
  }

  public static function getAll($limit = GPDatabase::LIMIT, $offset = 0) {
    $node_datas =
      GPDatabase::get()->getAllByType(static::getType(), $limit, $offset);
    foreach ($node_datas as $node_data) {
      if (!isset(self::$cache[$node_data['id']])) {
        self::$cache[$node_data['id']] = self::nodeFromArray($node_data);
      }
    }
    return array_select_keys(self::$cache, ipull($node_datas, 'id'));
  }

  public static function clearCache() {
    self::$cache = [];
  }

  public static function unsetFromCache($id) {
    unset(self::$cache[$id]);
  }

  private static function getByIndexDataAll($data_type) {
    $node_ids = GPDatabase::get()->getNodeIDsByTypeDataAll($data_type);
    return self::multiGetByID($node_ids);
  }

  private static function getByIndexData($data_type, $data) {
    $db = GPDatabase::get();
    $node_ids = $db->getNodeIDsByTypeData($data_type, make_array($data));
    return self::multiGetByID($node_ids);
  }

  private static function getByIndexDataRange($args) {
    $ids = GPDatabase::get()->getNodeIDsByTypeDataRange(
      $args[0],
      $args[1],
      $args[2],
      idx($args, 3, GPDatabase::LIMIT),
      idx($args, 4, 0));
    return self::multiGetByID($ids);
  }
}


text:
xQueueHandle displayQueue = NULL;
PoiTimer ptimer(TIMER3, true);
uint16_t currentDelay=1000;
bool doPause = false;
bool skipFrames = false;

volatile SemaphoreHandle_t displayTimerSemaphore;
//portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;

String pixelFrameToString(PixelFrame f, int idx, bool withHeader){
  char buffer[40];
  if (withHeader) {
  snprintf(buffer, 40, "Frame %d (delay %d): %3d %3d %3d",
    f.idx, f.delay,
    f.pixel[idx].r, f.pixel[idx].g, f.pixel[idx].b);
  }
  else {
  snprintf(buffer, 40, "%3d %3d %3d",
    f.pixel[idx].r, f.pixel[idx].g, f.pixel[idx].b);
  }
  return String(buffer);
}

void IRAM_ATTR onDisplayTimer(){

  //portENTER_CRITICAL_ISR(&timerMux);
  // nothing critical for now
  //portEXIT_CRITICAL_ISR(&timerMux);

  // Give a semaphore that triggers the displayTask
  xSemaphoreGiveFromISR(displayTimerSemaphore, NULL);
}

static void displayTask(void* arg)
{
  struct PixelFrame rframe;

  for(;;) {
    // wait for timer
    if (xSemaphoreTake(displayTimerSemaphore, portMAX_DELAY)) {
      LOGV(DISP_T, "After semaphore - before queue - delay: %d", currentDelay);
      // grab next frame
      if(xQueueReceive(displayQueue, &( rframe ), portMAX_DELAY)) {
        if (skipFrames) {
          LOGD(DISP_T, "Skipping display frame...");
        }
        else {
          // change delay asap to make interval as exact as possible
          // need to make sure that next semaphore is not given before this step
          if (rframe.delay != currentDelay){
            ptimer.setInterval(rframe.delay);
            currentDelay = rframe.delay;
          }
          LOGD(DISP_T, "Received: %s %s %s %s %s %s ...",
            pixelFrameToString(rframe, 0, true).c_str(),
            pixelFrameToString(rframe, 1, false).c_str(),
            pixelFrameToString(rframe, 2, false).c_str(),
            pixelFrameToString(rframe, 3, false).c_str(),
            pixelFrameToString(rframe, 4, false).c_str(),
            pixelFrameToString(rframe, 5, false).c_str());
          ws2812_setColors(N_PIXELS, rframe.pixel);
          if (isSelftestActive()) {
            LOGD(DISP_T, "Verifying display frame %d...", rframe.idx);
            selftestValidateFrame(rframe);
          }
        }
      }
    }
  }
}

void display_setup(uint8_t queueSize){
  if(ws2812_init(WS2812_PIN, LED_WS2812B)){
    LOGE(DISP_T, "LED Pixel init error.");
  }

  displayQueue = xQueueCreate(queueSize, sizeof( PixelFrame ));
  displayTimerSemaphore = xSemaphoreCreateBinary();
  ptimer.init(onDisplayTimer);
}

void display_start(uint8_t prio){
  doPause = false;
  skipFrames = false;
  xTaskCreate(displayTask, "displayTask", 4096, NULL, prio, NULL);
  ptimer.setInterval(currentDelay);
}

void display_pause(){
  LOGI(DISP_T, "Display pausing...");
  ptimer.disable();
  doPause = true;
}

void display_skipFrames(){
  LOGI(DISP_T, "Display stopped...");
  skipFrames = true;
}

void display_resume(){
  LOGI(DISP_T, "Display resuming...");
  ptimer.enable();
  doPause = false;
  skipFrames = false;
}

bool display_isPaused() {
  return doPause;
}


text:
package com.exorath.simpleapi.api.npc;

import org.bukkit.Location;

/**
 * Created by Toon Sevrin on 5/22/2016.
 */
public interface NPC {
    /**
     * Gets the {@link Location} of the entity.
     * @return the {@link Location} of the entity
     */
    Location getLocation();

    /**
     * Teleports this entity to a specific {@link Location}
     * @param location location to teleport entity towards
     */
    void teleport(Location location);

    /**
     * Despawns the entity out of the world.
     */
    void despawn();
}