text:
Unix and Bash Cheat Sheet
==========================

## Command			                    	Description 			                            Example
```
* echo <string>	                   Print string to screen                      $ echo hello
* man <command>	                   Display manual page for command             $ man echo
* ⌃C	                              Get out of trouble 	                       $ tail^C
* ⌃A	                              Move to beginning of line
* ⌃E	                              Move to end of line
* ⌃U	                              Delete to beginning of line
* Option-click 		               Move cursor to location clicked
* Up & down arrow 	                Scroll through previous commands
* clear or ⌃L 	                    Clear screen 	                              $ clear
* exit or ⌃D 	                     Exit terminal 	                            $ exit
```

## Manipulating files
```
* \>		                          Redirect output to filename 	              $ echo foo > foo.txt
* \>>		                         Append output to filename 	                $ echo bar >> foo.txt
* cat <file>	                      Print contents of file to screen            $ cat hello.txt
* diff <f1> <f2>	                  Diff files 1 & 2                         	  $ diff foo.txt bar.txt
* ls		                          List directory or file 	                    $ ls hello.txt
* ls -l	                       	List long form 	                            $ ls -l hello.txt
* ls -rtl	                         Long by reverse modification time 	        $ ls -rtl
* ls -a		                       List all (including hidden) 	              $ ls -a
* touch <file>	                    Create an empty file                        $ touch foo
* mv <old> <new>	                  Rename (move) from old to new               $ mv foo bar
* cp <old> <new>	                  Copy old to new 	                          $ cp foo bar
* rm <file>		                   Remove (delete) file 	                      $ rm foo
* rm -f <file>	                    Force-remove file 	                        $ rm -f bar
```

## Inspecting files
```
* up & down arrow keys	            Move up or down one line
* spacebar	                    	Move forward one page
* ⌃F				                  Move forward one page
* ⌃B			                  	Move back one page
* G			                   	Move to end of file
* 1G			                  	Move to beginning of file
* /<string>			               Search file for string 			                  /rose
* n			                   	Move to next search result
* N				                   Move to previous search result
* q			                   	Quit less
* curl			                    Interact with URLs                          $ curl -O example.com
* which				               Locate a program on the path              	$ which curl
* head <file>			             Display first part of file                	$ head foo
* tail <file>			             Display last part of file 	                $ tail bar
* wc <file>			               Count lines, words, bytes 	                $ wc foo
* cmd1 | cmd2			             Pipe cmd1 to cmd2 	                      	$ head foo | wc
* ping <url>			              Ping a server URL 		                      $ ping google.com
* less <file>		                 View file contents interactively 	          $ less foo
* grep <string> <file>	            Find string in file 	                    	$ grep foo bar.txt
* grep -i <string> <file>	         Find case-insensitively 	                  $ grep -i foo bar.txt
* ps				                  Show processes 			                        $ ps aux
* top				                 Show processes (sorted) 	                  $ top
* kill -<level> <pid>             	Kill a process 			                        $ kill -15 24601
* pkill -<level> -f <name>	        Kill matching processes                     $ pkill -15 -f spring
```

## Directories
```
* mkdir <name>	                    Make directory with name 	                  $ mkdir foo
* pwd			                     Print working directory 	                  $ pwd
* cd <\dir>		                   Change to <\dir> 			                      $ cd foo/
* cd ~/<\dir>		                 cd relative to home 		                    $ cd ~/foo/
* cd		                          Change to home directory 	                  $ cd
* cd -			                    Change to previous directory 	              $ cd && pwd && cd -
* .			                       The current directory 		                  $ cp ~/foo.txt .
* ..			                      One directory up 			                      $ cd ..
* find			                    Find files & directories 	                  $ find . -name foo*.*
* cp -r <old> <new>	               Copy recursively 			                      $ cp -r ~/foo .
* rmdir <\dir>		                Remove (empty) dir 		                      $ rmdir foo/
* rm -rf <\dir>	                   Remove dir & contents 		                  $ rm -rf foo/
* grep -ri <\string> <\dir>	       Grep recursively (case-insensitive)         $ grep -ri foobar/
```
## Special Variables
```
* $0        -  The name of the Bash script.
* $1        -  $9 - The first 9 arguments to the Bash script. (As mentioned above.)
* $#        -  How many arguments were passed to the Bash script.
* $@        -  All the arguments supplied to the Bash script.
* $?        -  The exit status of the most recently run process.
* $$        -   The process ID of the current script.
* $USER     - The username of the user running the script.
* $HOSTNAME - The hostname of the machine the script is running on.
* $SECONDS  - The number of seconds since the script was started.
* $RANDOM   - Returns a different random number each time is it referred to.
* $LINENO   - Returns the current line number in the Bash script
```

##  Conditional Statements
If statements
```
if [ <some test> ]
	  then
    <commands>
   elif [ <some test> ]
   then
   <different commands>
   else
   <other commands>
fi
```
```
Case (switch) Statement
	case <variable> in
	<pattern 1>)
  <commands>
  ;;<pattern 2>)
  <other commands>
  ;;
esac
```
```
While loop
	•	while [ <some test> ]
	•	do
<commands>
	•	done
```
```
For Loop
	for var in <list>
	do
  <commands>
	done
```
```
Select (for var in)
	select var in <list>
	do
  <commands>
	done
```

## Functions
```
	function_name () {
	<commands>
	}
	or
	function function_name {
	<commands>
	}
```

* You do not pass any arguments into ( )
	1. When passing argument you access it arguments ($1,$2…)
	1. Then you declare the arguments after call the function


text:
require 'spec_helper'

require 'puppet/provider/naginator'

describe Puppet::Provider::Naginator do
  before do
    @resource_type = stub 'resource_type', :name => :nagios_test
    @class = Class.new(Puppet::Provider::Naginator)

    @class.stubs(:resource_type).returns @resource_type
  end

  it "should be able to look up the associated Nagios type" do
    nagios_type = mock "nagios_type"
    nagios_type.stubs :attr_accessor
    Nagios::Base.expects(:type).with(:test).returns nagios_type

    @class.nagios_type.should equal(nagios_type)
  end

  it "should use the Nagios type to determine whether an attribute is valid" do
    nagios_type = mock "nagios_type"
    nagios_type.stubs :attr_accessor
    Nagios::Base.expects(:type).with(:test).returns nagios_type

    nagios_type.expects(:parameters).returns [:foo, :bar]

    @class.valid_attr?(:test, :foo).should be_true
  end

  it "should use Naginator to parse configuration snippets" do
    parser = mock 'parser'
    parser.expects(:parse).with("my text").returns "my instances"
    Nagios::Parser.expects(:new).returns(parser)

    @class.parse("my text").should == "my instances"
  end

  it "should join Nagios::Base records with '\\n' when asked to convert them to text" do
    @class.expects(:header).returns "myheader\n"

    @class.to_file([:one, :two]).should == "myheader\none\ntwo"
  end

  it "should be able to prefetch instance from configuration files" do
    @class.should respond_to(:prefetch)
  end

  it "should be able to generate a list of instances" do
    @class.should respond_to(:instances)
  end

  it "should never skip records" do
    @class.should_not be_skip_record("foo")
  end
end

describe Nagios::Base do
  it "should not turn set parameters into arrays #17871" do
    obj = Nagios::Base.create('host')
    obj.host_name = "my_hostname"
    obj.host_name.should == "my_hostname"
  end
end

describe Nagios::Parser do
  include PuppetSpec::Files

  subject do
    described_class.new
  end

  let(:config) { File.new( my_fixture('define_empty_param') ).read }

  it "should handle empty parameter values" do
    expect { subject.parse(config) }.to_not raise_error
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.tr.zps.app.coolweather.util;

import java.io.InputStream;

/**
 * Created by zps on 2016/8/16.
 */
public interface HttpCallBackListener {

    public void onFinish(InputStream in);

    public void onError(Exception e);
}


text:
> Navigation available in Bootstrap share general markup and styles,
from the base `<b-nav>` class to the `active` and `disabled` states.
Swap modifier props to switch between each style.

```html
<div>
  <b-nav>
    <b-nav-item active>Active</b-nav-item>
    <b-nav-item>Link</b-nav-item>
    <b-nav-item>Another Link</b-nav-item>
    <b-nav-item disabled>Disabled</b-nav-item>
  </b-nav>
</div>

<!-- nav-default.vue -->
```

## Overview

The base `<b-nav>` component is built with flexbox and provides a strong
foundation for building all types of navigation components. It includes
some style overrides (for working with lists), some link padding for larger
hit areas, and basic disabled styling. No active states are included in the base nav.

## Link Appearance

Two style variations are supported: `tabs` and `pills`, which support `active` state styling.
These variants are mutually exclusive - use only one style or the other.

### Tab style

Make the nav look like tabs by setting the prop `tabs`.

```html
<b-nav tabs>
  <b-nav-item active>Active</b-nav-item>
  <b-nav-item>Link</b-nav-item>
  <b-nav-item>Another Link</b-nav-item>
  <b-nav-item disabled>Disabled</b-nav-item>
</b-nav>

<!-- nav-tabs.vue -->
```

### Pill style

Use the pill style by setting the prop `pills`.

```html
<b-nav pills>
  <b-nav-item active>Active</b-nav-item>
  <b-nav-item>Link</b-nav-item>
  <b-nav-item>Another Link</b-nav-item>
  <b-nav-item disabled>Disabled</b-nav-item>
</b-nav>

<!-- nav-pills.vue -->
```

## Fill and justify

Force your `b-nav` content to extend the full available width.

### Fill

To proportionately fill all available space with your `<b-nav-item>` components,
set the `fill` prop. Notice that all horizontal space is occupied, but not
every nav item has the same width.

```html
<b-nav fill tabs>
  <b-nav-item active>Active</b-nav-item>
  <b-nav-item>Link</b-nav-item>
  <b-nav-item>Link with a long name </b-nav-item>
  <b-nav-item disabled>Disabled</b-nav-item>
</b-nav>

<!-- nav-fill.vue -->
```

### Justified

For equal-width elements, set prop `justified` instead. All horizontal space
will be occupied by nav links, but unlike `fill` above, every `<b-nav-item>`
will be the same width.

```html
<b-nav justified tabs>
  <b-nav-item active>Active</b-nav-item>
  <b-nav-item>Link</b-nav-item>
  <b-nav-item>Link with a long name </b-nav-item>
  <b-nav-item disabled>Disabled</b-nav-item>
</b-nav>

<!-- nav-justified.vue -->
```

## Vertical variation

By default `<b-nav>` appear on a horizontal line. Stack your navigation by setting
the `vertical` prop.

```html
<b-nav vertical class="w-25">
  <b-nav-item active>Active</b-nav-item>
  <b-nav-item>Link</b-nav-item>
  <b-nav-item>Another Link</b-nav-item>
  <b-nav-item disabled>Disabled</b-nav-item>
</b-nav>

<!-- nav-vertical.vue -->
```

## Dropdown support

Use `<b-nav-item-dropdown>` to place dropdown items within your nav.

```html
<b-nav pills>
  <b-nav-item active>Active</b-nav-item>
  <b-nav-item>Link</b-nav-item>
  <b-nav-item-dropdown id="nav7_ddown" text="Dropdown" extra-toggle-classes="nav-link-custom" right>
    <b-dropdown-item>one</b-dropdown-item>
    <b-dropdown-item>two</b-dropdown-item>
    <b-dropdown-divider></b-dropdown-divider>
    <b-dropdown-item>three</b-dropdown-item>
  </b-nav-item-dropdown>
</b-nav>

<!-- nav-dropdown.vue -->
```

Sometimes you want to add your own class names to the generated dropdown toggle button, that by default have
the classes `nav-link` and `dropdown-toggle`. Use the `extra-toggle-classes` prop to add them (like above) which
will produce something like:

```html
<li id="nav7_ddown" class="nav-item b-nav-dropdown dropdown">
   <a href="#" id="nav7_ddown__BV_button_" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle nav-link-custom">
  </a>
  ...
</li>
```

Refer to [`<b-dropdown>`](../dropdown) for a list of supported sub-components.

### `<b-nav-item-dropdown>` Component Alias

`<b-nav-item-dropdown>` can be used via it's shorter aliases of `<b-nav-item-dd>` and `<b-nav-dd>`.

## Using in Navbar

Prop `is-nav-bar` has been deprecated and will be removed in a future release.

## Tabbed local content support

See the [`<b-tabs>`](./tabs) component for creating tabbable panes of local
content (not suited for navigation).

## Accessibility
If you're using `<b-nav>` to provide a navigation bar, be sure to add a
`role="navigation"` to the most logical parent container of `<b-nav>`, or wrap
a `<nav>` element around `<b-nav>`. Do **not** add the role to the `<b-nav>` itself,
as this would prevent it from being announced as an actual list by assistive technologies.

When using a `<b-nav-item-dropdown>` in your `<b-nav>`, be sure to assign a unique `id`
prop value to the `<b-nav-dropdown>` so that the appropriate `aria-*` attributes can
be automatically generated.

## See Also

- [`<b-tabs>`](/docs/components/tabs) to create tabbable panes of local content, even via dropdown menus.
- [`<b-navbar>`](/docs/components/navbar) a wrapper that positions branding, navigation, and other elements in a concise header.
- [`<b-dropdown>`](/docs/components/dropdown) for sub-components that you can place inside `<b-nav-item-dropdown>`
- [Router Link Support reference](/docs/reference/router-links) for information about router-link specific props available on `<b-nav-item>`

## Component Reference


text:
package com.facebook.litho.intellij.toolwindows;

import com.facebook.litho.intellij.LithoPluginUtils;
import com.facebook.litho.intellij.extensions.EventLogger;
import com.facebook.litho.intellij.logging.LithoLoggerProvider;
import com.facebook.litho.intellij.services.ComponentGenerateService;
import com.facebook.litho.specmodels.model.SpecModel;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.ide.structureView.StructureView;
import com.intellij.ide.structureView.StructureViewFactory;
import com.intellij.ide.structureView.StructureViewModel;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ex.ToolWindowManagerListener;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.FormBuilder;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UI;
import com.intellij.util.ui.UIUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JComponent;
import javax.swing.JTextArea;
import org.jetbrains.annotations.Nullable;

/** Service creates structure view reflecting {@link ComponentTreeModel}. */
class ComponentStructureView implements Disposable {
  private static final JComponent STUB;

  static {
    final JTextArea text =
        new JTextArea(
            "Spec structure will be shown here for a valid ComponentSpec file (LayoutSpec, MountSpec, GroupSectionSpec, DiffSectionSpec)");
    text.setLineWrap(true);
    text.setEditable(false);
    text.setBackground(null);
    text.setWrapStyleWord(true);
    text.setFont(UIUtil.getLabelFont());
    text.setMargin(JBUI.insets(10));

    STUB = UI.PanelFactory.panel(text).createPanel();
  }

  private final AtomicBoolean isVisible = new AtomicBoolean(false);
  private final Project project;
  private ContentManager contentManager;
  private Content contentContainer;
  @VisibleForTesting @Nullable StructureView structureView;

  static ComponentStructureView getInstance(Project project) {
    return ServiceManager.getService(project, ComponentStructureView.class);
  }

  ComponentStructureView(Project project) {
    this.project = project;
    Disposer.register(project, this);
  }

  @Override
  public void dispose() {
    contentManager = null;
    contentContainer.dispose();
    contentContainer = null;
    dispose(structureView);
  }

  synchronized void setup(ToolWindow toolWindow) {
    contentManager = toolWindow.getContentManager();
    Disposer.register(contentManager, this);
    contentContainer = contentManager.getFactory().createContent(STUB, "", false);
    contentManager.addContent(contentContainer);
    isVisible.set(toolWindow.isVisible());
    updateViewLater(null);
    ComponentGenerateService.getInstance().subscribe(this::updateViewLater, this);
    final MessageBusConnection busConnection = project.getMessageBus().connect(this);
    busConnection.subscribe(
        FileEditorManagerListener.FILE_EDITOR_MANAGER,
        new FileEditorManagerListener() {
          @Override
          public void selectionChanged(FileEditorManagerEvent event) {
            updateViewLater(null);
          }
        });
    busConnection.subscribe(
        ToolWindowManagerListener.TOPIC,
        new ToolWindowManagerListener() {
          @Override
          public void stateChanged() {
            final boolean visible = toolWindow.isVisible();
            final boolean wasVisible = isVisible.getAndSet(visible);
            if (visible && !wasVisible) {
              updateViewLater(null);
            }
          }
        });
  }

  private void updateViewLater(@Nullable PsiClass updatedClass) {
    if (!isVisible.get()) return;

    if (ApplicationManager.getApplication().isUnitTestMode()) {
      ReadAction.run(() -> updateView(updatedClass));
    } else {
      DumbService.getInstance(project).smartInvokeLater(() -> updateView(updatedClass));
    }
  }

  /** Updates view either if updatedClass is null, or if updatedClass is focused. */
  private synchronized void updateView(@Nullable PsiClass updatedClass) {
    // Sanity check in case view was disposed
    if (contentManager == null || contentContainer == null) return;

    final FileEditor selectedEditor = FileEditorManager.getInstance(project).getSelectedEditor();
    final PsiFile selectedFile = getSelectedFile(selectedEditor, project);
    final PsiClass selectedClass =
        Optional.ofNullable(selectedFile)
            .flatMap(file -> LithoPluginUtils.getFirstClass(file, cls -> true))
            .orElse(null);

    if (updatedClass != null && updatedClass != selectedClass) {
      return;
    }

    // assumes Litho Spec is always the first top level class in the file
    String loggingType;
    if (LithoPluginUtils.isLayoutSpec(selectedClass)) {
      loggingType = "layout_spec";
    } else if (LithoPluginUtils.isMountSpec(selectedClass)) {
      loggingType = "mount_spec";
    } else if (selectedClass != null
        && LithoPluginUtils.hasLithoSectionSpecAnnotation(selectedClass)) {
      loggingType = "section_spec";
    } else {
      loggingType = "not_spec";
    }

    final StructureView oldStructure = structureView;
    final Map<String, String> data = new HashMap<>();
    data.put(EventLogger.KEY_TYPE, loggingType);
    // Overridden below
    data.put(EventLogger.KEY_RESULT, "fail");
    final JComponent newView =
        Optional.ofNullable(selectedClass)
            .map(ComponentGenerateService.getInstance()::getOrCreateSpecModel)
            .map(
                model -> {
                  structureView = createStructureView(model, selectedEditor, selectedFile, project);
                  data.put(EventLogger.KEY_RESULT, "success");
                  return structureView.getComponent();
                })
            .orElse(STUB);
    contentContainer.setComponent(newView);
    // View wasn't updating without this step
    contentManager.setSelectedContent(contentContainer);
    dispose(oldStructure);
    LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_TOOLWINDOW, data);
  }

  private void dispose(@Nullable StructureView oldStructure) {
    if (oldStructure == null) return;

    oldStructure.dispose();
    if (this.structureView == oldStructure) {
      this.structureView = null;
    }
  }

  private static StructureView createStructureView(
      SpecModel model, FileEditor selectedEditor, PsiFile selectedFile, Project project) {
    final StructureViewModel viewModel = ComponentTreeModel.create(selectedFile, model);
    final StructureView view =
        StructureViewFactory.getInstance(project)
            .createStructureView(selectedEditor, viewModel, project, true);
    Disposer.register(view, viewModel);
    return view;
  }

  private static JComponent createView(JComponent top, JComponent bottom) {
    return FormBuilder.createFormBuilder()
        .addComponent(top, 1)
        .addComponentFillVertically(bottom, 0)
        .getPanel();
  }

  @Nullable
  private static PsiFile getSelectedFile(@Nullable FileEditor editor, Project project) {
    if (editor == null) return null;

    final VirtualFile vf = editor.getFile();
    if (vf == null) return null;

    return PsiManager.getInstance(project).findFile(vf);
  }
}


text:
package Challenges;

public class FixedArrayQueue implements QueueInterface{

	private Object[] nodes;
	int head = 0;
	int tail = 1;

	public FixedArrayQueue(int size) {
		nodes = new Object[size + 1];
	}

	@Override
	public void enqueue(Object item) {
		// reached the end of the array?
		if (tail == nodes.length) {
			// and is queue is full?
			if (head == 0)
				return; // nothing to do.
			else
				tail = 0; // point to the beginning of the array
		}
		nodes[tail++] = item;
	}

	@Override
	public Object dequeue() {
		if (isEmpty())
			return null;
		if (head + 1 == nodes.length) {
			if (tail != 0)
				head = -1;
			else
				return null;
		}
		Object item = nodes[++head];
		nodes[head] = null;

		return item;
	}

	@Override
	public boolean isEmpty() {
		return tail - head == 1;
	}

}


text:
package org.jivesoftware.openfire.fastpath.commands;

import org.jivesoftware.openfire.fastpath.util.WorkgroupUtils;
import org.dom4j.Element;
import org.jivesoftware.openfire.commands.AdHocCommand;
import org.jivesoftware.openfire.commands.SessionData;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.util.StringUtils;
import org.xmpp.forms.DataForm;
import org.xmpp.forms.FormField;
import org.xmpp.packet.JID;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Command that allows to create new workgroups.
 *
 * @author Gaston Dombiak
 *
 * TODO Use i18n
 */
public class CreateWorkgroup extends AdHocCommand {
    @Override
	public String getCode() {
        return "http://jabber.org/protocol/admin#add-workgroup";
    }

    @Override
	public String getDefaultLabel() {
        return "Add a Workgroup";
    }

    @Override
	public int getMaxStages(SessionData data) {
        return 1;
    }

    @Override
	public void execute(SessionData sessionData, Element command) {
        Element note = command.addElement("note");
        Map<String, List<String>> data = sessionData.getData();

        // Get the name of the new workgroup
        String wgName= get(data, "name", 0);
        String description = get(data, "description", 0);
        List<String> members = data.get("members");
        String agents = StringUtils.collectionToString(members);

        if (wgName == null) {
            note.addAttribute("type", "error");
            note.setText("Please specify the name of the workgroup.");
            return;
        }

        Map<String, String> errors = WorkgroupUtils.createWorkgroup(wgName, description, agents);

        if (!errors.isEmpty()) {
            note.addAttribute("type", "error");
            // TODO check errors. give better error message
            note.setText("Error creating workgroup.");
            return;
        }
        // Answer that the operation was successful
        note.addAttribute("type", "info");
        note.setText("Operation finished successfully");
    }

    @Override
	protected void addStageInformation(SessionData data, Element command) {
        DataForm form = new DataForm(DataForm.Type.form);
        form.setTitle("Adding a new workgroup");
        form.addInstruction("Fill out this form to add a workgroup.");

        FormField field = form.addField();
        field.setType(FormField.Type.hidden);
        field.setVariable("FORM_TYPE");
        field.addValue("http://jabber.org/protocol/admin");

        field = form.addField();
        field.setType(FormField.Type.text_single);
        field.setLabel("The name of the workgroup to be added");
        field.setVariable("name");
        field.setRequired(true);

        field = form.addField();
        field.setType(FormField.Type.text_multi);
        field.setLabel("Username of the members");
        field.setVariable("members");

        field = form.addField();
        field.setType(FormField.Type.text_single);
        field.setLabel("Description");
        field.setVariable("description");

        // Add the form to the command
        command.add(form.getElement());
    }

    @Override
	protected List<Action> getActions(SessionData data) {
        return Arrays.asList(AdHocCommand.Action.complete);
    }

    @Override
	protected AdHocCommand.Action getExecuteAction(SessionData data) {
        return AdHocCommand.Action.complete;
    }

    @Override
	public boolean hasPermission(JID requester) {
        return super.hasPermission(requester) && !UserManager.getUserProvider().isReadOnly();
    }
}


text:
package org.openengsb.core.ekb.transformation.wonderland.internal.deployer;

import java.io.File;

import org.apache.commons.io.FilenameUtils;
import org.apache.felix.fileinstall.ArtifactInstaller;
import org.openengsb.core.common.AbstractOpenEngSBService;
import org.openengsb.core.common.transformations.TransformationUtils;
import org.openengsb.core.ekb.api.TransformationEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * {@code ArtifactInstaller} that deploys transformation description files
 */
public class TransformationDeployerService extends AbstractOpenEngSBService implements ArtifactInstaller {
    private static final Logger LOGGER = LoggerFactory.getLogger(TransformationDeployerService.class);
    private static final String TRANSFORM_ENDING = "transformation";
    private TransformationEngine engine;

    @Override
    public boolean canHandle(File artifact) {
        LOGGER.debug("TransformationDeployer.canHandle(\"{}\")", artifact.getAbsolutePath());
        String fileEnding = FilenameUtils.getExtension(artifact.getName());

        if (artifact.isFile() && TRANSFORM_ENDING.equals(fileEnding)) {
            LOGGER.info("Found \"{}\" to deploy.", artifact);
            return true;
        }
        return false;
    }

    @Override
    public void install(File artifact) throws Exception {
        LOGGER.debug("TransformationDeployer.install(\"{}\")", artifact.getAbsolutePath());
        try {
            doInstall(artifact);
            LOGGER.info("Successfully installed transformation file \"{}\"", artifact.getName());
        } catch (Exception e) {
            LOGGER.error("Error while installing transformation file", e);
            throw e;
        }
    }

    private void doInstall(File artifact) {
        try {
            LOGGER.info("Read the transformation description file " + artifact.getName());
            engine.saveDescriptions(TransformationUtils.getDescriptionsFromXMLFile(artifact));
        } catch (Exception e) {
            LOGGER.error(String.format("Error while reading the content of file %s", artifact.getName()), e);
        }
    }

    @Override
    public void update(File artifact) throws Exception {
        LOGGER.debug("TransformationDeployer.update(\"{}\")", artifact.getAbsolutePath());
        try {
            doInstall(artifact);
        } catch (Exception e) {
            LOGGER.error("Error while updating transformation file", e);
            throw e;
        }
        LOGGER.info("Successfully updated transformation file \"{}\"", artifact.getName());
    }

    @Override
    public void uninstall(File artifact) throws Exception {
        LOGGER.debug("TransformationDeployer.uninstall(\"{}\")", artifact.getAbsolutePath());
        try {
            engine.deleteDescriptionsByFile(artifact.getName());
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            throw e;
        }
        LOGGER.info("Successfully deleted transformation file \"{}\"", artifact.getName());
    }

    public void setEngine(TransformationEngine engine) {
        this.engine = engine;
    }
}


text:
require 'test_helper'

class TokenPermissionTypesControllerTest < ActionDispatch::IntegrationTest

  include Devise::Test::IntegrationHelpers

  # CURRENT RESULTS OF `rake routes`
  # --------------------------------------------------
  #   token_permission_types  GET      /token_permission_types        token_permission_types#index

  setup do
    @user = User.first
  end

  # GET /token_permission_types (token_permission_types_path)
  # ----------------------------------------------------------
  test "retrieve the list of token permission types" do
    # Should redirect user to the root path if they are not logged in!
    get token_permission_types_path
    assert_unauthorized_redirect_to_root_path

    sign_in @user

    get token_permission_types_path
    assert_response :success
    assert assigns(:user)
    assert assigns(:token_types)
  end

end


text:
'use strict';

var errorHandling = require('./error-handling.module');

var httpErrorHandlerFactory = function httpErrorHandlerFactory($q, notificationService) {
  var securityRelatedCodes = [
    401,
    403
  ];
  var getResponseNotificationMessage = function getResponseNotificationMessage(errorCode, data) {
    if (errorCode === 400) {
      return {
        title: 'Validation error',
        userMessage: data.message,
        noLog: true
      };
    }

    if (errorCode === 413) {
      return {
        userMessage: 'The request could not be processed because it is too large for the system to handle.'
          + ' Please contact technical support.'
      };
    }

    if (errorCode >= 500 && errorCode < 600) {
      return {
        userMessage: 'The server is unavailable. Please try again.'
          + ' If the problem persists, please notify technical support.',
        noLog: true
      };
    }

    if (errorCode === 404) {
      return {
        title: 'Document not found',
        userMessage: 'The data you are requesting does not exist.'
      };
    }

    if (securityRelatedCodes.indexOf(errorCode) !== -1) {
      // Handled by authorization module
      return null;
    }

    return {
      title: 'General response error'
    };
  };

  return {
    responseError: function handleResponseError(response) {
      var notificationData = getResponseNotificationMessage(response.status, response.data);
      if (notificationData) {
        notificationService.notifyError(notificationData);
      }
      var isSecurityRelated = securityRelatedCodes.indexOf(response.status) !== -1;
      return isSecurityRelated ? $q.resolve(response) : $q.reject(response);
    }
  };
};

httpErrorHandlerFactory.$inject = ['$q', 'faNotificationService'];

errorHandling
  .factory('faHttpErrorHandler', httpErrorHandlerFactory);


text:
package cherry.csv;

import java.io.IOException;

/**
 * CSV形式データ解析エラー.<br>
 * CSV形式が不正であることを表す。
 */
public class CsvException extends IOException {

	/** シリアルバージョンID. */
	private static final long serialVersionUID = 1L;

	/**
	 * 例外オブジェクトを生成する.
	 */
	public CsvException(String message) {
		super(message);
	}

}


text:
using namespace Rendering::Light;
using namespace Rendering::Light::Buffer;

void Rendering::Light::Buffer::SpotLightBuffer::Initialize(Device::DirectX & dx)
{
	Parent::Initialize(dx, POINT_LIGHT_BUFFER_MAX_NUM, DXGI_FORMAT_R32G32B32A32_FLOAT);

	SpotLight::Param dummy[POINT_LIGHT_BUFFER_MAX_NUM];
	_paramSRBuffer.Initialize(dx, POINT_LIGHT_BUFFER_MAX_NUM, DXGI_FORMAT_R16G16B16A16_FLOAT, dummy);
}

void SpotLightBuffer::PushLight(const SpotLight& light)
{
	_paramSRBuffer.PushData(SpotLight::Param());
	Parent::PushLight(light);
}

void SpotLightBuffer::UpdateTransformBuffer(	const std::vector<SpotLight*>& dirtyTFLights,
												const Core::TransformPool& tfPool,
												const Core::ObjectID::IndexHashMap& indexer)
{
	for (const auto& light : dirtyTFLights)
	{
		Core::ObjectID objID = light->GetObjectID();
		const auto& tf = tfPool.Find(objID.Literal());

		uint index = indexer.Find(objID.Literal());
		_transformBuffer[index]	= light->MakeTransform(*tf);
		_paramSRBuffer[index]	= light->MakeParam(*tf);
	}

	_mustUpdateTransformSRBuffer |= (dirtyTFLights.empty() == false);
}

void SpotLightBuffer::UpdateSRBuffer(Device::DirectX& dx, bool forcedUpdate)
{
	if (_mustUpdateTransformSRBuffer | forcedUpdate)
		_paramSRBuffer.UpdateSRBuffer(dx);

	Parent::UpdateSRBuffer(dx, forcedUpdate);
}

void SpotLightBuffer::Delete(uint index)
{
	_paramSRBuffer.Delete(index);
	Parent::Delete(index);
}

void SpotLightBuffer::DeleteAll()
{
	_paramSRBuffer.DeleteAll();
	Parent::DeleteAll();
}


text:
- [What are they?](#what-are-they)
- [Demos](#demos)
- [Why have them?](#why-have-them)
- [How to use](#how-to-use)
  - [An example](#an-example)
  - [Applying to components](#applying-to-components)
- [Specificity](#specificity)
- [Namespacing](#namespacing)
- [Further reading](#further-reading)

## What are they?

Utilities are your helper classes and typically your last resort when needing
to apply styles to an element.

They apply really common CSS styles either as a single declaration e.g. *float
an element to the right:* `.u-float-right`, or a very simple, universal pattern
(multiline declaration) e.g. *hide an element but only visually:*
`.u-hide-visually`.

There scope is only ever one element i.e. utilities can't affect child elements
of the element they're being applied too and they never have any styles that
are concerned with cosmetics.

Utilities follow the [single responsibility principle](http://csswizardry.com/2012/04/the-single-responsibility-principle-applied-to-css/)
and the [open/closed principle](http://csswizardry.com/2012/06/the-open-closed-principle-applied-to-css/).

## Demos

<http://s.codepen.io/chris-pearce/full/WbMgMp> (work in progress)

## Why have them?

Utilities exist because every UI consists of really common styles that will
need to be applied many times, therefore it makes sense to abstract these
styles into nice reusable CSS snippets i.e. utilities. It's the same reason why
[objects](../objects/README.md) and [layout modules](../layout/README.md)
exist. The difference though with utilities is that they sit right at the
bottom of the food chain—so to speak—in comparison to the other Scally
sections, because they're so simple and low-level, and aren't too far away from
inline styles.

With that said and even though it's rare they'll always be the need to apply
utilities to a UI as not everything can be a
[component](../components/README.md) or taken care of by
objects and layout modules. In these scenarios, if utilities didn't exist, we
would have issues like:

- Where do these types of styles live in our CSS architecture?
- Lots of *micro* components that aren't *true* components.
- CSS not being as DRY and maintainable as it could be because we would have to
  keep writing the same styles over and over again.

Utilities help keep our CSS DRY and maintainable and more performant—resulting
in drastically smaller stylesheets. And utilities allow you to make far-reaching
changes to your UI with simple modifications to a single utility as you have the
confidence in your changes because edits to a utility only ever alter one
responsibility.

## How to use

Each utility applies a single style e.g.

```scss
// Center align text
%u-text-align-center,
.u-text-align-center {text-align: center;}
```

Or a very simple, universal pattern (multiline declaration) e.g.

```scss
// Pin an element to all corners of its parent
%u-position-pin-all,
.u-position-pin-all {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
```

Utility classes are applied directly to the HTML element or `@extend`ed via
it's [Sass silent placeholder selector](http://sass-lang.com/documentation/file.SASS_REFERENCE.html#placeholder_selectors_).

If the element already has a component class e.g. `.c-box` then utility classes
shouldn't be applied to the element as the styling needs to be taken care of by
the component itself in order to keep the component nicely self-contained, see
the section below: [Applying to components](#applying-to-components).

It should be acknowledged—like with most things CSS related—that the above is
not completely black and white, what matters is that you know when you're
overusing utilities.

They're two exceptions to utilities being your last resort: the
[**Spacing**](_u-spacing.scss) utility and the
[**Percentage widths**](_u-widths.scss) utility. The **Percentage widths**
utility is a fundamental part of the Grid layout module giving the grid items
their percentage based widths e.g. `.u-one-half`, `.u-three-quarters`, etc. The
**Spacing** utility which includes a lot of spacing rules via the `margin` and
`padding` properties and should be used to apply spacing to the *outside*
(`margin`) of elements especially components.

### An example

If we look at a snippet of the UI from this
[home page](http://www.manchester.gov.uk/):

[![alt text](https://s3.amazonaws.com/uploads.hipchat.com/22262/1524600/Rzy0WiEjhhp25k5/Screen%20Shot%202015-04-15%20at%208.12.45%20pm.png "Some UI from the Manchester City Council home page")](https://s3.amazonaws.com/uploads.hipchat.com/22262/1524600/Rzy0WiEjhhp25k5/Screen%20Shot%202015-04-15%20at%208.12.45%20pm.png)

We can construct almost all of it using a mixture of:

- [Base styles](../core/base/) for things like headings, links, paragraphs,
  etc.
- [Grid layout module](../layout/_l-grid.scss) to layout the sets of 2 and 4
  columns.
- [Container layout module](../layout/_l-container.scss) to group this set of
  content, center align it and apply the global width.
- [Button component](../components/_c-button.scss) for the *More ...* CTA
  buttons.
- Theme styles to apply the dark background and white text/yellow links.

The missing treatment is the center alignment of all the text and this is where
using a utility—one of the **Text** alignment utilities:
`.u-text-align-center`—would make sense, otherwise we'd have to **a)** create a
*micro* component/object that just applies `text-align: center` which is
overkill and doesn't fit the criteria of a component/object *OR* **b)** just
hack that style into our CSS architecture somewhere which can get real messy
quick.

We could just apply the utility to the main container element which would be
the container layout module, like so:

```html
<div class="l-container l-container--full-bleed  u-text-align-center">
  <div class="l-container">
    [ ... ]
  </div>
</div>
```

Note how the utility class comes last in the class attribute? The order is:

1. Components
2. Layout modules
3. Objects
4. Utilities

Preferably separated by 2 empty spaces to improve readability.

### Applying to components

It's quite rare to apply utilities in the context of components as components
are discrete custom elements of a UI that enclose specific semantics and
styling therefore applying lots of utilities to them doesn't make them as
self-contained, portable, and maintainable as they need to be. The exception to
this is when we need to apply really common universal patterns which are
multiline declaration blocks e.g. hide an element but only visually:
`.u-hide-visually`. When these types of utilities are needed you would apply
the utility via its Sass silent placeholder selector using the `@extend`
directive, rather than applying the utility class to the component HTML, however
some utilities can be applied to the component HTML:

- [Hide](_u-hide.scss)
- [Toggle visibility](_u-toggle-visibility.scss)

As mentioned already the most important thing with utilities is knowing how to use them appropriately.

If we had a **Modal dialog** component and part of that component was the
overlay that sits behind the dialog—covering the entire viewport—we could make
use of one of the **Position** utilities: `.u-position-pin-all` which will pin
an element—in this case the overlay—to all corners of it's parent—in this case
the main viewport.

A code example:

**HTML**

```html
<div class="c-modal-dialog__overlay"></div>
```

**CSS**

```scss
.modal__overlay {
    @extend %u-position-pin-all;
    [ ... ]
}
```

And we may have to provide some text in this component for users of assistive
technology e.g. screen reader users. In this case we can apply the utility
class direct to the HTML as the element we're applying it too only exists for
this reason therefore it's overkill to have to create a new component class
just for this, especially when we may have to apply this treatment a few
times. So it might look something like this:

```html
<div class="c-modal-dialog__header">
  <span class="u-hide-visually">Beginning of dialog window. It begins with a heading 1 called "Registration Form". Escape will cancel and close the window. This form does not collect any actual information.</span>
  <h1 class="c-modal-dialog__title">Registration Form</h1>
  [...]
</div>
```

**Do not `@extend` single declarations** as there is no benefit in doing
this, components only need to make use of utilities when they're applying
universal patterns which are multiline declarations.

## Specificity

Utilities always need to *win* when it comes to specificity (CSS' first C; the
cascade) as they should always *just work* otherwise they're not doing their
job properly i.e. you should never be needing to override a utility's styles.
If you are then you're not using them correctly.

To ensure this Scally does the following:

- Applies the `!important` keyword to all utilities to boost their specificity.
- Declares all utilities last in the Scally framework so they're compiled after
  everything else.

## Namespacing

All utility classes, silent placeholder selectors, settings, and filenames
are prefixed with `u-` so that they're easily identifiable e.g.

- `.u-text-align-center`
- `%u-text-align-center`
- `$u-text-apply-at-breakpoints`
- `_u-text.scss`

## Further reading

*Make sure to read the documentation within each utility Sass partial file as
it will contain information about the specific utility and it's implementation.*

- [More Transparent UI Code with Namespaces -> Utility Namespaces](http://csswizardry.com/2015/03/more-transparent-ui-code-with-namespaces/#utility-namespaces-u-)
- [The single responsibility principle applied to CSS](http://csswizardry.com/2012/04/the-single-responsibility-principle-applied-to-css/)
- [The open/closed principle applied to CSS](http://csswizardry.com/2012/06/the-open-closed-principle-applied-to-css/)
- [When to use `@extend`; when to use a mixin](http://csswizardry.com/2014/11/when-to-use-extend-when-to-use-a-mixin/)
- [The Role of Utility Classes](http://davidtheclark.com/on-utility-classes/)
- [CSS guidelines - The separation of concerns](http://cssguidelin.es/#the-separation-of-concerns)


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Adding model 'TokenPermission'
        db.create_table('tokit_tokenpermission', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=255)),
            ('codename', self.gf('django.db.models.fields.CharField')(unique=True, max_length=255)),
        ))
        db.send_create_signal('tokit', ['TokenPermission'])

        # Adding M2M table for field permissions on 'Token'
        db.create_table('tokit_token_permissions', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('token', models.ForeignKey(orm['tokit.token'], null=False)),
            ('tokenpermission', models.ForeignKey(orm['tokit.tokenpermission'], null=False))
        ))
        db.create_unique('tokit_token_permissions', ['token_id', 'tokenpermission_id'])

    def backwards(self, orm):

        # Deleting model 'TokenPermission'
        db.delete_table('tokit_tokenpermission')

        # Removing M2M table for field permissions on 'Token'
        db.delete_table('tokit_token_permissions')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'tokit.token': {
            'Meta': {'object_name': 'Token'},
            'access_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
            'access_count_last_day': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
            'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_internal': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
            'is_valid': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
            'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
            'last_access': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'last_modfied': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['tokit.TokenPermission']", 'null': 'True', 'blank': 'True'}),
            'request_per_day_limit': ('django.db.models.fields.IntegerField', [], {'default': '2000'})
        },
        'tokit.tokenaccesslog': {
            'Meta': {'object_name': 'TokenAccessLog'},
            'date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'key': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['tokit.Token']"})
        },
        'tokit.tokenpermission': {
            'Meta': {'object_name': 'TokenPermission'},
            'codename': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
        }
    }

    complete_apps = ['tokit']


text:
module RailsBestPractices
  module Core
    class ChecksLoader
      def initialize(config)
        @config = config
      end

      # load all lexical checks.
      def load_lexicals
        load_checks_from_config { |check_name| RailsBestPractices::Lexicals.const_get(check_name) }
      end

      # load all reviews according to configuration.
      def load_reviews
        load_checks_from_config do |check_name|
          RailsBestPractices::Reviews.const_get(check_name.gsub(/Check$/, 'Review'))
        end
      end

      private

      # read the checks from yaml config.
      def checks_from_config
        @checks ||= YAML.load_file @config
      end

      # load all checks from the configuration
      def load_checks_from_config(&block)
        checks_from_config.each_with_object([]) do |check, active_checks|
          check_instance = instantiate_check(block, *check)
          active_checks << check_instance unless check_instance.nil?
        end
      end

      # instantiates a check
      def instantiate_check(block, check_name, options)
        check_class = load_check_class(check_name, &block)
        check_class&.new(options || {})
      end

      # loads the class for a check by calling the given block
      def load_check_class(check_name)
        yield(check_name)
      rescue NameError
        # nothing to do, the check does not exist
      end
    end
  end
end


text:
package rcm.util;

public abstract class Thr {
    /**
      * Test whether the current thread has been interrupted with
      * Thread.interrupt().  If so, a ThreadDeath exception is thrown
      * to kill it cleanly.  If a background thread
      * calls check() periodically, then Thread.interrupt() will
      * kill it cleanly and safely at the next check() call.  Catch ThreadDeath
      * or use a try-finally construct if your background thread needs to do
      * any resource cleanup.
      *
      * @exception ThreadDeath if and only if
      * Thread.currentThread().isInterrupted() is true.
      */
    public static void check () throws ThreadDeath {
        if (Thread.currentThread ().isInterrupted ())
            throw new ThreadDeath ();
    }
}


text:
import AsyncStorage from "@react-native-async-storage/async-storage"
import { State } from "easy-peasy"
import { isArray, isBoolean, isNull, isNumber, isPlainObject, isString, throttle } from "lodash"
import { Middleware } from "redux"
import { GlobalStoreModel } from "./GlobalStoreModel"
import { migrate } from "./migration"

export const SESSION_KEY = "sessionState"
export const STORAGE_KEY = "artsy-app-state"

export const LEGACY_SEARCH_STORAGE_KEY = "SEARCH/RECENT_SEARCHES"

export function sanitize(object: unknown, path: Array<string | number> = []): unknown {
  if (isPlainObject(object)) {
    const result = {} as any
    for (const key of Object.keys(object as any)) {
      // ignore computed properties, sessionState
      if (key !== SESSION_KEY && !Object.getOwnPropertyDescriptor(object, key)?.get) {
        result[key] = sanitize((object as any)[key], [...path, key])
      }
    }
    return result
  } else if (isArray(object)) {
    return object.map((elem, i) => sanitize(elem, [...path, i]))
  } else if (isNumber(object) || isString(object) || isNull(object) || isBoolean(object)) {
    return object
  } else {
    console.error(`Cannot serialize value at path ${path.join(".")}: ${object}`)
    return null
  }
}

export function assignDeep(object: any, otherObject: any) {
  for (const k of Object.keys(otherObject)) {
    if (!(k in object) || !(isPlainObject(object[k]) && isPlainObject(otherObject[k]))) {
      object[k] = otherObject[k]
    } else {
      assignDeep(object[k], otherObject[k])
    }
  }
}

export async function persist(globalStoreState: State<GlobalStoreModel>) {
  return await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(sanitize(globalStoreState)))
}

async function loadLegacySearchState() {
  const json = await AsyncStorage.getItem(LEGACY_SEARCH_STORAGE_KEY)

  if (json) {
    await AsyncStorage.removeItem(LEGACY_SEARCH_STORAGE_KEY)

    try {
      const result = JSON.parse(json)
      if (Array.isArray(result)) {
        return result
      }
    } catch (e) {
      // noop
    }
  }

  return null
}

export async function unpersist(): Promise<DeepPartial<State<GlobalStoreModel>>> {
  const json = await AsyncStorage.getItem(STORAGE_KEY)

  try {
    const result = (json ? migrate({ state: JSON.parse(json) }) : {}) as State<GlobalStoreModel>
    const recentSearches = await loadLegacySearchState()
    if (recentSearches) {
      result.search = {
        ...result.search,
        recentSearches,
      }
    }
    return result
  } catch (e) {
    if (!__TEST__) {
      console.error(e)
    }
    return {}
  }
}

export const persistenceMiddleware: Middleware = (store) => {
  const throttledPersist = throttle(persist, 1000, { leading: false, trailing: true })
  return (next) => (action) => {
    next(action)
    // use requestAnimationFrame to make doubly sure we avoid blocking UI updates
    requestAnimationFrame(() => {
      throttledPersist(store.getState())
    })
  }
}


text:
using System;
using System.Globalization;
using System.Windows;
using bytePassion.Lib.WpfLib.ConverterBase;
using OQF.Net.DesktopClient.Contracts;

namespace OQF.Net.DesktopClient.Visualization.Computations
{
	internal class LeaveGamePanelVisiblity : GenericTwoToOneValueConverter<ConnectionStatus, GameStatus, Visibility>
	{
		protected override Visibility Convert (ConnectionStatus connectionStatus, GameStatus gameStatus, CultureInfo culture)
		{
			if (connectionStatus != ConnectionStatus.Connected)
				return Visibility.Collapsed;

			switch (gameStatus)
			{
				case GameStatus.GameOver:
				case GameStatus.WaitingForOponend:
				case GameStatus.NoGame:             return Visibility.Collapsed;

				case GameStatus.PlayingJoinedGame:
				case GameStatus.PlayingOpendGame:   return Visibility.Visible;
			}

			throw new ArgumentException();
		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Puccinia clematidis-secalis Dupias

### Remarks
null


text:
import itertools
import re as _re
import string

from ..logic.boolalg import Boolean
from .assumptions import StdFactKB
from .cache import cacheit
from .expr import AtomicExpr, Expr
from .logic import fuzzy_bool
from .numbers import Integer
from .sympify import sympify

class BaseSymbol(AtomicExpr, Boolean):
    """Abstract class for Symbols.

    Do not instantiate this, use derived classes.

    Notes
    =====

    We introduce this class to prevent "flipping" of arguments
    for "rich comparison" methods [1]_.  There is no swapped-argument
    versions of these methods, like :meth:`~object.__add__` vs
    :meth:`~object.__radd__`, rather e.g. :meth:`~object.__lt__` and
    :meth:`~object.__gt__` are each other's reflection.

    According to the documentation [1]_, if the operands of such
    method are of different types, and right operand's type is a direct or
    indirect subclass of the left operand's type, the reflected method
    of the right operand has priority, otherwise the left operand's
    method has priority.

    Thus, simple class hierarhy, where :class:`Symbol` is a parent
    class for both :class:`Dummy` and :class:`Wild` isn't possible,
    if we want to avoid silent switching to the reflected methods
    for rich comparisons of parent and child.  See also sympy/sympy#7951.

    Examples
    ========

    We illustrate the "flipping" problem, by using here
    BaseSymbol in place of ordinary Symbol:

    >>> p = Wild('p')
    >>> x = BaseSymbol('x')
    >>> x < p
    p_ > x

    See Also
    ========

    Symbol
    Dummy
    Wild

    References
    ==========

    * https://docs.python.org/3/reference/datamodel.html#object.__lt__

    """

    is_comparable = False

    is_Symbol = True

    @property
    def _diff_wrt(self):
        """Allow derivatives wrt Symbols.

        Examples
        ========

            >>> x._diff_wrt
            True

        """
        return True

    @staticmethod
    def _sanitize(assumptions, obj=None):
        """Remove None, covert values to bool, check commutativity *in place*."""
        # be strict about commutativity: cannot be None
        is_commutative = fuzzy_bool(assumptions.get('commutative', True))
        if is_commutative is None:
            whose = f'{obj.__name__} ' if obj else ''
            raise ValueError(
                f'{whose}commutativity must be True or False.')

        # sanitize other assumptions so 1 -> True and 0 -> False
        for key in list(assumptions):
            v = assumptions[key]
            if v is None:
                assumptions.pop(key)
                continue
            assumptions[key] = bool(v)

    def __new__(cls, name, **assumptions):
        """Symbols are identified by name and assumptions::

        >>> Symbol('x') == Symbol('x')
        True
        >>> Symbol('x', real=True) == Symbol('x', real=False)
        False

        """
        cls._sanitize(assumptions, cls)
        return BaseSymbol.__xnew_cached_(cls, name, **assumptions)

    @staticmethod
    def __new_stage2__(obj_cls, name, **assumptions):
        if not isinstance(name, str):
            raise TypeError(f'name should be a string, not {type(name)!r}')

        obj = Expr.__new__(obj_cls)
        obj.name = name

        # TODO: Issue sympy/sympy#8873: Forcing the commutative assumption here means
        # later code such as ``repr()`` cannot tell whether the user
        # specified ``commutative=True`` or omitted it.  To workaround this,
        # we keep a copy of the assumptions dict, then create the StdFactKB,
        # and finally overwrite its ``._generator`` with the dict copy.  This
        # is a bit of a hack because we assume StdFactKB merely copies the
        # given dict as ``._generator``, but future modification might, e.g.,
        # compute a minimal equivalent assumption set.
        tmp_asm_copy = assumptions.copy()

        # be strict about commutativity
        is_commutative = fuzzy_bool(assumptions.get('commutative', True))
        assumptions['commutative'] = is_commutative
        obj._assumptions = StdFactKB(assumptions)
        obj._assumptions._generator = tmp_asm_copy  # Issue sympy/sympy#8873
        return obj

    __xnew__ = __new_stage2__  # never cached (e.g. dummy)
    __xnew_cached_ = cacheit(__new_stage2__)  # symbols are always cached

    def __getnewargs__(self):
        return self.name,

    def __getstate__(self):
        state = super().__getstate__()
        state['_assumptions'] = self._assumptions
        return state

    def _hashable_content(self):
        # Note: user-specified assumptions not hashed, just derived ones
        return ((self.name,) +
                tuple(sorted((k, v) for k, v in self._assumptions.items()
                             if v is not None)))

    @classmethod
    def class_key(cls):
        """Nice order of classes."""
        return 2, 0, cls.__name__

    @cacheit
    def sort_key(self, order=None):
        """Return a sort key."""
        return self.class_key(), (1, (str(self),)), Integer(1).sort_key(), Integer(1)

    def as_dummy(self):
        """Return a Dummy having the same name and same assumptions as self."""
        return Dummy(self.name, **self._assumptions.generator)

    def is_constant(self, *wrt, **flags):
        """Test if self is constant.

        See Also
        ========

        diofant.core.expr.Expr.is_constant

        """
        if not wrt:
            return False
        return self not in wrt

    @property
    def free_symbols(self):
        """Return from the atoms of self those which are free symbols.

        See Also
        ========

        diofant.core.basic.Basic.free_symbols

        """
        return {self}

class Symbol(BaseSymbol):
    r"""Symbol is a placeholder for atomic symbolic expression.

    It has a name and a set of assumptions.

    Parameters
    ==========

    name : str
        The name for Symbol.
    \*\*assumptions : dict
        Keyword arguments to specify assumptions for
        Symbol.  Default assumption is commutative=True.

    Examples
    ========

    >>> a, b = symbols('a b')
    >>> bool(a*b == b*a)
    True

    You can override default assumptions:

    >>> A, B = symbols('A B', commutative=False)
    >>> bool(A*B != B*A)
    True
    >>> bool(A*B*2 == 2*A*B) is True  # multiplication by scalars is commutative
    True

    See Also
    ========

    :mod:`diofant.core.assumptions`
    Dummy
    Wild

    """

class Dummy(BaseSymbol):
    """Dummy symbols are each unique, identified by an internal count index:

    >>> bool(Dummy('x') == Dummy('x')) is True
    False

    If a name is not supplied then a string value of the count index will be
    used. This is useful when a temporary variable is needed and the name
    of the variable used in the expression is not important.

    See Also
    ========

    Symbol

    """

    _count = 0

    is_Dummy = True

    def __new__(cls, name=None, **assumptions):
        if name is None:
            name = 'Dummy_' + str(Dummy._count)

        cls._sanitize(assumptions, cls)
        obj = Symbol.__xnew__(cls, name, **assumptions)

        Dummy._count += 1
        obj.dummy_index = Dummy._count
        return obj

    def __getstate__(self):
        state = super().__getstate__()
        state['dummy_index'] = self.dummy_index
        return state

    @classmethod
    def class_key(cls):
        """Nice order of classes."""
        return 3, 0, cls.__name__

    @cacheit
    def sort_key(self, order=None):
        """Return a sort key."""
        return self.class_key(), (
            2, (str(self), self.dummy_index)), Integer(1).sort_key(), Integer(1)

    def _hashable_content(self):
        return BaseSymbol._hashable_content(self) + (self.dummy_index,)

class Wild(BaseSymbol):
    """A Wild symbol matches anything, whatever is not explicitly excluded.

    Examples
    ========

    >>> a = Wild('a')
    >>> x.match(a)
    {a_: x}
    >>> pi.match(a)
    {a_: pi}
    >>> (3*x**2).match(a*x)
    {a_: 3*x}
    >>> cos(x).match(a)
    {a_: cos(x)}
    >>> b = Wild('b', exclude=[x])
    >>> (3*x**2).match(b*x)
    >>> b.match(a)
    {a_: b_}
    >>> A = WildFunction('A')
    >>> A.match(a)
    {a_: A_}

    Notes
    =====

    When using Wild, be sure to use the exclude
    keyword to make the pattern more precise.
    Without the exclude pattern, you may get matches
    that are technically correct, but not what you
    wanted. For example, using the above without
    exclude:

    >>> a, b = symbols('a b', cls=Wild)
    >>> (2 + 3*y).match(a*x + b*y)
    {a_: 2/x, b_: 3}

    This is technically correct, because
    (2/x)*x + 3*y == 2 + 3*y, but you probably
    wanted it to not match at all. The issue is that
    you really didn't want a and b to include x and y,
    and the exclude parameter lets you specify exactly
    this.  With the exclude parameter, the pattern will
    not match.

    >>> a = Wild('a', exclude=[x, y])
    >>> b = Wild('b', exclude=[x, y])
    >>> (2 + 3*y).match(a*x + b*y)

    Exclude also helps remove ambiguity from matches.

    >>> E = 2*x**3*y*z
    >>> a, b = symbols('a b', cls=Wild)
    >>> E.match(a*b)
    {a_: 2*y*z, b_: x**3}
    >>> a = Wild('a', exclude=[x, y])
    >>> E.match(a*b)
    {a_: z, b_: 2*x**3*y}
    >>> a = Wild('a', exclude=[x, y, z])
    >>> E.match(a*b)
    {a_: 2, b_: x**3*y*z}

    See Also
    ========

    Symbol

    """

    is_Wild = True

    def __new__(cls, name, exclude=(), properties=(), **assumptions):
        exclude = tuple(sympify(x) for x in exclude)
        properties = tuple(properties)
        cls._sanitize(assumptions, cls)
        return Wild.__xnew__(cls, name, exclude, properties, **assumptions)

    def __getnewargs__(self):
        return self.name, self.exclude, self.properties

    @staticmethod
    @cacheit
    def __xnew__(cls_, name, exclude, properties, **assumptions):
        obj = BaseSymbol.__xnew__(cls_, name, **assumptions)
        obj.exclude = exclude
        obj.properties = properties
        return obj

    def _hashable_content(self):
        return super()._hashable_content() + (self.exclude, self.properties)

    # TODO add check against another Wild
    def _matches(self, expr, repl_dict={}):
        """Helper method for match().

        See Also
        ========

        diofant.core.basic.Basic.matches

        """
        if any(expr.has(x) for x in self.exclude):
            return
        if any(not f(expr) for f in self.properties):
            return
        repl_dict = repl_dict.copy()
        repl_dict[self] = expr
        return repl_dict

_range = _re.compile('([0-9]*:[0-9]+|[a-zA-Z]?:[a-zA-Z])')

def symbols(names, **args):
    r"""
    Transform strings into instances of :class:`Symbol` class.

    :func:`symbols` function returns a sequence of symbols with names taken
    from ``names`` argument, which can be a comma or whitespace delimited
    string, or a sequence of strings::

        >>> a, b, c = symbols('a b c')

    The type of output is dependent on the properties of input arguments::

        >>> symbols('x')
        x
        >>> symbols('x,')
        (x,)
        >>> symbols('x,y')
        (x, y)
        >>> symbols(('a', 'b', 'c'))
        (a, b, c)
        >>> symbols(['a', 'b', 'c'])
        [a, b, c]
        >>> symbols({'a', 'b', 'c'})
        {a, b, c}

    If an iterable container is needed for a single symbol, set the ``seq``
    argument to ``True`` or terminate the symbol name with a comma::

        >>> symbols('x', seq=True)
        (x,)

    To reduce typing, range syntax is supported to create indexed symbols.
    Ranges are indicated by a colon and the type of range is determined by
    the character to the right of the colon. If the character is a digit
    then all contiguous digits to the left are taken as the nonnegative
    starting value (or 0 if there is no digit left of the colon) and all
    contiguous digits to the right are taken as 1 greater than the ending
    value::

        >>> symbols('x:10')
        (x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)

        >>> symbols('x5:10')
        (x5, x6, x7, x8, x9)
        >>> symbols('x5(:2)')
        (x50, x51)

        >>> symbols('x5:10 y:5')
        (x5, x6, x7, x8, x9, y0, y1, y2, y3, y4)

        >>> symbols(('x5:10', 'y:5'))
        ((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))

    If the character to the right of the colon is a letter, then the single
    letter to the left (or 'a' if there is none) is taken as the start
    and all characters in the lexicographic range *through* the letter to
    the right are used as the range::

        >>> symbols('x:z')
        (x, y, z)
        >>> symbols('x:c')  # null range
        ()
        >>> symbols('x(:c)')
        (xa, xb, xc)

        >>> symbols(':c')
        (a, b, c)

        >>> symbols('a:d, x:z')
        (a, b, c, d, x, y, z)

        >>> symbols(('a:d', 'x:z'))
        ((a, b, c, d), (x, y, z))

    Multiple ranges are supported; contiguous numerical ranges should be
    separated by parentheses to disambiguate the ending number of one
    range from the starting number of the next::

        >>> symbols('x:2(1:3)')
        (x01, x02, x11, x12)
        >>> symbols(':3:2')  # parsing is from left to right
        (00, 01, 10, 11, 20, 21)

    Only one pair of parentheses surrounding ranges are removed, so to
    include parentheses around ranges, double them. And to include spaces,
    commas, or colons, escape them with a backslash::

        >>> symbols('x((a:b))')
        (x(a), x(b))
        >>> symbols(r'x(:1\,:2)')  # or 'x((:1)\,(:2))'
        (x(0,0), x(0,1))

    All newly created symbols have assumptions set according to ``args``::

        >>> a = symbols('a', integer=True)
        >>> a.is_integer
        True

        >>> x, y, z = symbols('x y z', real=True)
        >>> x.is_real and y.is_real and z.is_real
        True

    Despite its name, :func:`symbols` can create symbol-like objects like
    instances of Function or Wild classes. To achieve this, set ``cls``
    keyword argument to the desired type::

        >>> symbols('f g h', cls=Function)
        (f, g, h)

        >>> type(_[0])
        <class 'diofant.core.function.UndefinedFunction'>

    """
    result = []

    if isinstance(names, str):
        marker = 0
        literals = [r'\,', r'\:', r'\ ']
        for i in range(len(literals)):
            lit = literals.pop(0)
            if lit in names:
                while chr(marker) in names:
                    marker += 1
                lit_char = chr(marker)
                marker += 1
                names = names.replace(lit, lit_char)
                literals.append((lit_char, lit[1:]))

        def literal(s):
            if literals:
                for c, l in literals:
                    s = s.replace(c, l)
            return s

        names = names.strip()
        as_seq = names.endswith(',')
        if as_seq:
            names = names[:-1].rstrip()
        if not names:
            raise ValueError('no symbols given')

        # split on commas
        names = [n.strip() for n in names.split(',')]
        if not all(n for n in names):
            raise ValueError('missing symbol between commas')
        # split on spaces
        for i in range(len(names) - 1, -1, -1):
            names[i: i + 1] = names[i].split()

        cls = args.pop('cls', Symbol)
        seq = args.pop('seq', as_seq)

        for name in names:
            if ':' not in name:
                symbol = cls(literal(name), **args)
                result.append(symbol)
                continue

            split = _range.split(name)
            # remove 1 layer of bounding parentheses around ranges
            for i in range(len(split) - 1):
                if i and ':' in split[i] and split[i] != ':' and \
                        split[i - 1].endswith('(') and \
                        split[i + 1].startswith(')'):
                    split[i - 1] = split[i - 1][:-1]
                    split[i + 1] = split[i + 1][1:]
            for i, s in enumerate(split):
                if ':' in s:
                    if s[-1].endswith(':'):
                        raise ValueError('missing end range')
                    a, b = s.split(':')
                    if b[-1] in string.digits:
                        a = 0 if not a else int(a)
                        b = int(b)
                        split[i] = [str(c) for c in range(a, b)]
                    else:
                        a = a or 'a'
                        split[i] = [string.ascii_letters[c] for c in range(
                            string.ascii_letters.index(a),
                            string.ascii_letters.index(b) + 1)]  # inclusive
                    if not split[i]:
                        break
                else:
                    split[i] = [s]
            else:
                seq = True
                names = [''.join(s) for s in itertools.product(*split)]
                if literals:
                    result.extend([cls(literal(s), **args) for s in names])
                else:
                    result.extend([cls(s, **args) for s in names])

        if not seq and len(result) <= 1:
            if not result:
                return ()
            return result[0]

        return tuple(result)
    else:
        for name in names:
            result.append(symbols(name, **args))

        return type(names)(result)

def var(names, **args):
    """
    Create symbols and inject them into the global namespace.

    This calls :func:`symbols` with the same arguments and puts the results
    into the *global* namespace. It's recommended not to use :func:`var` in
    library code, where :func:`symbols` has to be used.

    Examples
    ========

    >>> var('x')
    x
    >>> x
    x

    >>> var('a ab abc')
    (a, ab, abc)
    >>> abc
    abc

    >>> var('x y', real=True)
    (x, y)
    >>> x.is_real and y.is_real
    True

    See Also
    ========

    symbols

    """
    from ..utilities import flatten
    from ..utilities.magic import pollute

    ret = symbols(names, **args)
    syms = flatten([ret])
    pollute([str(_) for _ in syms], syms)

    return ret


text:
package com.spotify.heroic.async;

import eu.toolchain.async.AsyncFuture;

/**
 * XXX: consider replacing with RxJava at some point.
 *
 * @author udoprog
 * @param <T>
 */
public interface AsyncObserver<T> {
    AsyncFuture<Void> observe(final T value) throws Exception;

    void cancel() throws Exception;

    void fail(Throwable cause) throws Exception;

    void end() throws Exception;
}


text:
<?php namespace Norm\Dialect;

use Exception;
use PDO;

class MySQLDialect extends SQLDialect
{
    protected $FIELD_MAP = array(
        'Norm\Schema\Boolean' => 'TINYINT',
        'Norm\Schema\DateTime' => 'DATETIME',
        'Norm\Schema\Integer' => 'INT',
        'Norm\Schema\Password' => 'VARCHAR',
        'Norm\Schema\Reference' => 'INT',
        'Norm\Schema\String' => 'VARCHAR',
        'Norm\Schema\Text' => 'TEXT',
    );

    public function listCollections()
    {
        $statement = $this->raw->query("SHOW TABLES");
        $result = $statement->fetchAll();
        $retval = array();
        foreach ($result as $key => $value) {
            $retval[] = $value[0];
        }

        return $retval;
    }

    public function prepareCollection($collection)
    {
        throw new Exception('Not implemented yet! Please recheck the method later!');
        $collectionName = $collection->name;
        $collectionSchema = $collection->schema();

        $sql = 'SHOW TABLES LIKE "'.$collectionName.'"';
        $statement = $this->raw->query($sql);
        $row = $statement->fetch(PDO::FETCH_ASSOC);
        $tableExist = (empty($row)) ? false : true;

        $fields = array();
        if ($tableExist) {
            // fetch old table info
            $sql = 'DESCRIBE `'.$collectionName.'`';
            $statement = $this->raw->query($sql);
            $describe = $statement->fetchAll(PDO::FETCH_ASSOC);
            foreach ($describe as $key => $value) {
                $fields[$value['name']] = $value;
            }
        }

        // add new fields to new table
        $newFields = array(
            'id' => array(
                'name' => 'id',
                'type' => 'INTEGER',
                'notnull' => '1',
                'dflt_value' => null,
                'pk' => '1',
                'autoincrement' => '1',
            ),
        );

        $isUpdated = false;

        // populate fields from old to new
        foreach ($collectionSchema as $schemaField) {
            $existingField = isset($fields[$schemaField['name']]) ? $fields[$schemaField['name']] : array();
            $clazz = get_class($schemaField);
            $type = (isset($this->FIELD_MAP[$clazz])) ? $this->FIELD_MAP[$clazz] : null;

            if (!isset($existingField['type']) || $existingField['type'] !== $type) {
                $isUpdated = true;
                $newField = array_merge($existingField, array(
                    'name' => $schemaField['name'],
                    'type' => $type,
                )) + array(
                    'notnull' => '0',
                    'dflt_value' => null,
                    'pk' => '0',
                );
                $newFields[$schemaField['name']] = $newField;
            } else {
                $newFields[$schemaField['name']] = $existingField;
            }
        }

        foreach ($fields as $field) {
            if (empty($newFields[$field['name']])) {
                $isUpdated = true;
                $newFields[$field['name']] = $field;
            }
        }

        if (!$isUpdated) {
            return;
        }

        $fieldMeta = array();
        $newFieldNames = array();
        $oldFieldNames = array();
        foreach ($newFields as $field) {
            $meta = $field['name'].' '.$field['type'];
            if (isset($field['pk']) && $field['pk'] == '1') {
                $meta .= ' PRIMARY KEY';
            }
            if (isset($field['autoincrement']) && $field['autoincrement'] == '1') {
                $meta .= ' AUTOINCREMENT';
            }
            if (isset($field['notnull']) && $field['notnull'] == '1') {
                $meta .= ' NOT NULL';
            }
            if (isset($field['dflt_value'])) {
                $meta .= ' DEFAULT "'.$field['dflt_value'].'"';
            }

            $fieldMeta[] = $meta;
            $newFieldNames[] = '"'.$field['name'].'"';
            if (isset($fields[$field['name']])) {
                $oldFieldNames[] = '"'.$field['name'].'"';
            } else {
                $oldFieldNames[] = 'NULL AS "'.$field['name'].'"';
            }
        }

        $tmpTable = ($tableExist) ? uniqid($collectionName.'_') : $collectionName;
        $sql = 'CREATE TABLE "'.$tmpTable.'" ('."\n".
                '    '.implode(",\n    ", $fieldMeta)."\n".
                ')';

        $this->raw->query($sql);

        if ($tableExist) {
            $sql = 'INSERT INTO "' . $tmpTable . '" (' . implode(', ', $newFieldNames) . ') SELECT '.implode(', ', $oldFieldNames).' FROM "'.$collectionName.'"';
            $this->raw->query($sql);
            $sql = 'DROP TABLE "'.$collectionName.'"';
            $this->raw->query($sql);
            $sql = 'ALTER TABLE "'.$tmpTable.'" RENAME TO "'.$collectionName.'"';
            $this->raw->query($sql);
        }
    }

    public function grammarExpression($key, $value, $collection, &$data)
    {

        if ($key === '!or' || $key === '!and') {
            $wheres = array();
            foreach ($value as $subValues) {

                $subWheres = array();

                foreach ($subValues as $k => $v) {
                    $subWheres[] = $this->grammarExpression($k, $v, $collection, $data);
                }

                switch (count($subWheres)) {
                    case 0:
                        break;
                    case 1:
                        $wheres[] = implode(' AND ', $subWheres);
                        break;
                    default:
                        $wheres[] = '('.implode(' AND ', $subWheres).')';
                        break;
                }
            }

            return '('.implode(' '.strtoupper(substr($key, 1)).' ', $wheres).')';
        }

        $splitted = explode('!', $key, 2);

        $field = $splitted[0];

        $schema = $collection->schema($field);

        if ($field == '$id') {
            $field = 'id';
        } elseif (strlen($field) > 0 && $field[0] === '$') {
            $field = '_'.substr($field, 1);
        }

        $operator = '=';
        $multiValue = false;
        $fValue = $value;

        if (isset($splitted[1])) {
            switch ($splitted[1]) {
                case 'like':
                    $fValue = "%$value%";
                    $operator = 'LIKE';
                    break;
                case 'lte':
                    $operator = '<=';
                    break;
                case 'lt':
                    $operator = '<';
                    break;
                case 'gte':
                    $operator = '>=';
                    break;
                case 'gt':
                    $operator = '>';
                    break;
                case 'regex':
                    throw new Exception('Operator regex is not supported to query.');
                    // return array($field, array('$regex', new \MongoRegex($value)));
                case 'in':
                    $operator = 'IN';
                    break;
                case 'nin':
                    throw new Exception('Operator regex is not supported to query.');
                    // $operator = '$'.$splitted[1];
                    // $multiValue = true;
                    // break;
                default:
                    throw new Exception('Operator regex is not supported to query.');
                    // $operator = '$'.$splitted[1];
                    // break;
            }
        }

        if ($operator == 'IN') {
            $fgroup = array();
            foreach ($value as $k => $v) {
                $this->expressionCounter++;
                $data['f'.$this->expressionCounter] = $v;
                $fgroup[] = ':f'.$this->expressionCounter;
            }

            $sql = $field . ' ' . $operator . ' ('.implode(', ', $fgroup).')';
            $this->expressionCounter++;

        } else {
            $fk = 'f'.$this->expressionCounter++;
            $data[$fk] = $fValue;
            $sql = $field.' '.$operator.' :'.$fk;

            if (empty($fValue)) {
                $sql = '('.$sql.' OR '.$field.' is null)';
            }
        }

        // var_dump($sql);
        // exit();

        return $sql;
    }
}


text:
module Sparkle
  module Controller

    def fetch
      cache_entry = Rails.cache.read(params[:key])
      partial = cache_entry[:partial]
      locals = cache_entry[:locals]
      begin
        locals.values.each { |value| value._sparkle_refresh! if value.class.include?(Refreshable) }
      rescue Exception => e
        session[:sparkle_exception] = e
      end
      render :partial => partial, :locals => locals.merge(:sparkle_cache_key => nil)
      raise session.delete(:sparkle_exception) if session[:sparkle_exception]
    end

  end
end


text:
using Sniper.Common;
using Sniper.Http;
using Sniper.TargetProcess.Routes;
using Xunit;

namespace Sniper.Tests.CRUD.Update.Common.CustomActivities
{
    public class UpdateCustomActivityTests
    {
        [Fact]
        public void CustomActivityThrowsError()
        {
            var client = new TargetProcessClient
            {
                ApiSiteInfo = new ApiSiteInfo(TargetProcessRoutes.Route.CustomActivities)
            };
            var customActivity = new CustomActivity
            {
            };
        }
    }
}


text:
package org.apache.zeppelin.helium;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import javax.inject.Inject;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterGroup;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.ManagedInterpreterGroup;
import org.apache.zeppelin.interpreter.remote.RemoteAngularObjectRegistry;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcess;
import org.apache.zeppelin.interpreter.thrift.RemoteApplicationResult;
import org.apache.zeppelin.notebook.ApplicationState;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.NoteEventListener;
import org.apache.zeppelin.notebook.Notebook;
import org.apache.zeppelin.notebook.Paragraph;
import org.apache.zeppelin.scheduler.ExecutorFactory;
import org.apache.zeppelin.scheduler.Job;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HeliumApplicationFactory
 */
public class HeliumApplicationFactory implements ApplicationEventListener, NoteEventListener {
  private final Logger logger = LoggerFactory.getLogger(HeliumApplicationFactory.class);
  private final ExecutorService executor;
  private Notebook notebook;
  private ApplicationEventListener applicationEventListener;

  @Inject
  public HeliumApplicationFactory(
      Notebook notebook, ApplicationEventListener applicationEventListener) {
    this.executor =
        ExecutorFactory.singleton().createOrGet(HeliumApplicationFactory.class.getName(), 10);
    this.notebook = notebook;
    this.applicationEventListener = applicationEventListener;

    // TODO(jl): Hmmmmmmmm...
    this.notebook.addNotebookEventListener(this);
  }

  private boolean isRemote(InterpreterGroup group) {
    return group.getAngularObjectRegistry() instanceof RemoteAngularObjectRegistry;
  }

  /**
   * Load pkg and run task
   */
  public String loadAndRun(HeliumPackage pkg, Paragraph paragraph) {
    ApplicationState appState = paragraph.createOrGetApplicationState(pkg);
    onLoad(paragraph.getNote().getId(), paragraph.getId(), appState.getId(),
        appState.getHeliumPackage());
    executor.submit(new LoadApplication(appState, pkg, paragraph));
    return appState.getId();
  }

  /**
   * Load application and run in the remote process
   */
  private class LoadApplication implements Runnable {
    private final HeliumPackage pkg;
    private final Paragraph paragraph;
    private final ApplicationState appState;

    public LoadApplication(ApplicationState appState, HeliumPackage pkg, Paragraph paragraph) {
      this.appState = appState;
      this.pkg = pkg;
      this.paragraph = paragraph;
    }

    @Override
    public void run() {
      try {
        // get interpreter process
        Interpreter intp = paragraph.getBindedInterpreter();
        ManagedInterpreterGroup intpGroup = (ManagedInterpreterGroup) intp.getInterpreterGroup();
        RemoteInterpreterProcess intpProcess = intpGroup.getRemoteInterpreterProcess();
        if (intpProcess == null) {
          throw new ApplicationException("Target interpreter process is not running");
        }

        // load application
        load(intpProcess, appState);

        // run application
        RunApplication runTask = new RunApplication(paragraph, appState.getId());
        runTask.run();
      } catch (Exception e) {
        logger.error(e.getMessage(), e);

        if (appState != null) {
          appStatusChange(paragraph, appState.getId(), ApplicationState.Status.ERROR);
          appState.setOutput(e.getMessage());
        }
      }
    }

    private void load(RemoteInterpreterProcess intpProcess, ApplicationState appState)
        throws Exception {

      synchronized (appState) {
        if (appState.getStatus() == ApplicationState.Status.LOADED) {
          // already loaded
          return;
        }

        appStatusChange(paragraph, appState.getId(), ApplicationState.Status.LOADING);
        final String pkgInfo = pkg.toJson();
        final String appId = appState.getId();

        RemoteApplicationResult ret = intpProcess.callRemoteFunction(client ->
                client.loadApplication(
                        appId,
                        pkgInfo,
                        paragraph.getNote().getId(),
                        paragraph.getId()));
        if (ret.isSuccess()) {
          appStatusChange(paragraph, appState.getId(), ApplicationState.Status.LOADED);
        } else {
          throw new ApplicationException(ret.getMsg());
        }
      }
    }
  }

  /**
   * Get ApplicationState
   * @param paragraph
   * @param appId
   * @return
   */
  public ApplicationState get(Paragraph paragraph, String appId) {
    return paragraph.getApplicationState(appId);
  }

  /**
   * Unload application
   * It does not remove ApplicationState
   *
   * @param paragraph
   * @param appId
   */
  public void unload(Paragraph paragraph, String appId) {
    executor.execute(new UnloadApplication(paragraph, appId));
  }

  /**
   * Unload application task
   */
  private class UnloadApplication implements Runnable {
    private final Paragraph paragraph;
    private final String appId;

    public UnloadApplication(Paragraph paragraph, String appId) {
      this.paragraph = paragraph;
      this.appId = appId;
    }

    @Override
    public void run() {
      ApplicationState appState = null;
      try {
        appState = paragraph.getApplicationState(appId);

        if (appState == null) {
          logger.warn("Can not find {} to unload from {}", appId, paragraph.getId());
          return;
        }
        if (appState.getStatus() == ApplicationState.Status.UNLOADED) {
          // not loaded
          return;
        }
        unload(appState);
      } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (appState != null) {
          appStatusChange(paragraph, appId, ApplicationState.Status.ERROR);
          appState.setOutput(e.getMessage());
        }
      }
    }

    private void unload(final ApplicationState appsToUnload) throws ApplicationException {
      synchronized (appsToUnload) {
        if (appsToUnload.getStatus() != ApplicationState.Status.LOADED) {
          throw new ApplicationException(
              "Can't unload application status " + appsToUnload.getStatus());
        }
        appStatusChange(paragraph, appsToUnload.getId(), ApplicationState.Status.UNLOADING);
        Interpreter intp = null;
        try {
          intp = paragraph.getBindedInterpreter();
        } catch (InterpreterException e) {
          throw new ApplicationException("No interpreter found", e);
        }

        RemoteInterpreterProcess intpProcess =
            ((ManagedInterpreterGroup) intp.getInterpreterGroup()).getRemoteInterpreterProcess();
        if (intpProcess == null) {
          throw new ApplicationException("Target interpreter process is not running");
        }

        RemoteApplicationResult ret = intpProcess.callRemoteFunction(client ->
                client.unloadApplication(appsToUnload.getId()));
        if (ret.isSuccess()) {
          appStatusChange(paragraph, appsToUnload.getId(), ApplicationState.Status.UNLOADED);
        } else {
          throw new ApplicationException(ret.getMsg());
        }
      }
    }
  }

  /**
   * Run application
   * It does not remove ApplicationState
   *
   * @param paragraph
   * @param appId
   */
  public void run(Paragraph paragraph, String appId) {
    executor.execute(new RunApplication(paragraph, appId));
  }

  /**
   * Run application task
   */
  private class RunApplication implements Runnable {
    private final Paragraph paragraph;
    private final String appId;

    public RunApplication(Paragraph paragraph, String appId) {
      this.paragraph = paragraph;
      this.appId = appId;
    }

    @Override
    public void run() {
      ApplicationState appState = null;
      try {
        appState = paragraph.getApplicationState(appId);

        if (appState == null) {
          logger.warn("Can not find {} to unload from {}", appId, paragraph.getId());
          return;
        }

        run(appState);
      } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (appState != null) {
          appStatusChange(paragraph, appId, ApplicationState.Status.UNLOADED);
          appState.setOutput(e.getMessage());
        }
      }
    }

    private void run(final ApplicationState app) throws ApplicationException {
      synchronized (app) {
        if (app.getStatus() != ApplicationState.Status.LOADED) {
          throw new ApplicationException(
              "Can't run application status " + app.getStatus());
        }

        Interpreter intp = null;
        try {
          intp = paragraph.getBindedInterpreter();
        } catch (InterpreterException e) {
          throw new ApplicationException("No interpreter found", e);
        }

        RemoteInterpreterProcess intpProcess =
            ((ManagedInterpreterGroup) intp.getInterpreterGroup()).getRemoteInterpreterProcess();
        if (intpProcess == null) {
          throw new ApplicationException("Target interpreter process is not running");
        }
        RemoteApplicationResult ret = intpProcess.callRemoteFunction(client ->
                client.runApplication(app.getId()));
        if (ret.isSuccess()) {
          // success
        } else {
          throw new ApplicationException(ret.getMsg());
        }
      }
    }
  }

  @Override
  public void onOutputAppend(
      String noteId, String paragraphId, int index, String appId, String output) {
    ApplicationState appToUpdate = getAppState(noteId, paragraphId, appId);

    if (appToUpdate != null) {
      appToUpdate.appendOutput(output);
    } else {
      logger.error("Can't find app {}", appId);
    }

    if (applicationEventListener != null) {
      applicationEventListener.onOutputAppend(noteId, paragraphId, index, appId, output);
    }
  }

  @Override
  public void onOutputUpdated(
      String noteId, String paragraphId, int index, String appId,
      InterpreterResult.Type type, String output) {
    ApplicationState appToUpdate = getAppState(noteId, paragraphId, appId);

    if (appToUpdate != null) {
      appToUpdate.setOutput(output);
    } else {
      logger.error("Can't find app {}", appId);
    }

    if (applicationEventListener != null) {
      applicationEventListener.onOutputUpdated(noteId, paragraphId, index, appId, type, output);
    }
  }

  @Override
  public void onLoad(String noteId, String paragraphId, String appId, HeliumPackage pkg) {
    if (applicationEventListener != null) {
      applicationEventListener.onLoad(noteId, paragraphId, appId, pkg);
    }
  }

  @Override
  public void onStatusChange(String noteId, String paragraphId, String appId, String status) {
    ApplicationState appToUpdate = getAppState(noteId, paragraphId, appId);
    if (appToUpdate != null) {
      appToUpdate.setStatus(ApplicationState.Status.valueOf(status));
    }

    if (applicationEventListener != null) {
      applicationEventListener.onStatusChange(noteId, paragraphId, appId, status);
    }
  }

  private void appStatusChange(Paragraph paragraph,
                               String appId,
                               ApplicationState.Status status) {
    ApplicationState app = paragraph.getApplicationState(appId);
    app.setStatus(status);
    onStatusChange(paragraph.getNote().getId(), paragraph.getId(), appId, status.toString());
  }

  private ApplicationState getAppState(String noteId, String paragraphId, String appId) {
    if (notebook == null) {
      return null;
    }
    try {
      return notebook.processNote(noteId,
        note -> {
          if (note == null) {
            logger.warn("Note {} not found", noteId);
            return null;
          }
          Paragraph paragraph = note.getParagraph(paragraphId);
          if (paragraph == null) {
            logger.error("Can't get paragraph {}", paragraphId);
            return null;
          }
          return paragraph.getApplicationState(appId);
        });
    } catch (IOException e) {
      logger.error("Can't get note {}", noteId);
      return null;
    }
  }

  @Override
  public void onNoteRemove(Note note, AuthenticationInfo subject) {
    // do nothing
  }

  @Override
  public void onNoteCreate(Note note, AuthenticationInfo subject) {
    // do nothing
  }

  @Override
  public void onNoteUpdate(Note note, AuthenticationInfo subject) {
    // do nothing
  }

  @Override
  public void onParagraphRemove(Paragraph paragraph) {
    List<ApplicationState> appStates = paragraph.getAllApplicationStates();
    for (ApplicationState app : appStates) {
      UnloadApplication unloadJob = new UnloadApplication(paragraph, app.getId());
      unloadJob.run();
    }
  }

  @Override
  public void onParagraphCreate(Paragraph p) {
    // do nothing
  }

  @Override
  public void onParagraphUpdate(Paragraph p) {
    // do nothing
  }

  @Override
  public void onParagraphStatusChange(Paragraph p, Job.Status status) {
    if (status == Job.Status.FINISHED) {
      // refresh application
      List<ApplicationState> appStates = p.getAllApplicationStates();

      for (ApplicationState app : appStates) {
        loadAndRun(app.getHeliumPackage(), p);
      }
    }
  }
}