text:
package com.github.jengelman.gradle.plugins.shadow.util.file;

import org.apache.commons.lang3.StringUtils;
import org.junit.rules.MethodRule;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A JUnit rule which provides a unique temporary folder for the test.
 */
public class TestNameTestDirectoryProvider implements MethodRule, TestRule, TestDirectoryProvider {
    private TestFile dir;
    private String prefix;
    private static TestFile root;
    private static AtomicInteger testCounter = new AtomicInteger(1);

    static {
        // NOTE: the space in the directory name is intentional
        root = new TestFile(new File("build/tmp/test files"));
    }

    private String determinePrefix() {
        StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
        for (StackTraceElement element : stackTrace) {
            if (element.getClassName().endsWith("Test") || element.getClassName().endsWith("Spec")) {
                return StringUtils.substringAfterLast(element.getClassName(), ".") + "/unknown-test-" + testCounter.getAndIncrement();
            }
        }
        return "unknown-test-class-" + testCounter.getAndIncrement();
    }

    public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
        init(method.getName(), target.getClass().getSimpleName());
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                base.evaluate();
                getTestDirectory().maybeDeleteDir();
                // Don't delete on failure
            }
        };
    }

    public Statement apply(final Statement base, Description description) {
        init(description.getMethodName(), description.getTestClass().getSimpleName());
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                base.evaluate();
                getTestDirectory().maybeDeleteDir();
                // Don't delete on failure
            }
        };
    }

    private void init(String methodName, String className) {
        if (methodName == null) {
            // must be a @ClassRule; use the rule's class name instead
            methodName = getClass().getSimpleName();
        }
        if (prefix == null) {
            String safeMethodName = methodName.replaceAll("\\s", "_").replace(File.pathSeparator, "_").replace(":", "_");
            if (safeMethodName.length() > 64) {
                safeMethodName = safeMethodName.substring(0, 32) + "..." + safeMethodName.substring(safeMethodName.length() - 32);
            }
            prefix = String.format("%s/%s", className, safeMethodName);
        }
    }

    public static TestNameTestDirectoryProvider newInstance() {
        return new TestNameTestDirectoryProvider();
    }

    public static TestNameTestDirectoryProvider newInstance(FrameworkMethod method, Object target) {
        TestNameTestDirectoryProvider testDirectoryProvider = new TestNameTestDirectoryProvider();
        testDirectoryProvider.init(method.getName(), target.getClass().getSimpleName());
        return testDirectoryProvider;
    }

    public TestFile getTestDirectory() {
        if (dir == null) {
            if (prefix == null) {
                // This can happen if this is used in a constructor or a @Before method. It also happens when using
                // @RunWith(SomeRunner) when the runner does not support rules.
                prefix = determinePrefix();
            }
            for (int counter = 1; true; counter++) {
                dir = root.file(counter == 1 ? prefix : String.format("%s%d", prefix, counter));
                if (dir.mkdirs()) {
                    break;
                }
            }
        }
        return dir;
    }

    public TestFile file(Object... path) {
        return getTestDirectory().file((Object[]) path);
    }

    public TestFile createFile(Object... path) {
        return file((Object[]) path).createFile();
    }

    public TestFile createDir(Object... path) {
        return file((Object[]) path).createDir();
    }
}


text:
package gobblin.runtime.std;

import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;

import gobblin.runtime.api.JobCatalogListenersContainer;
import gobblin.runtime.api.JobExecutionDriver;
import gobblin.runtime.api.JobExecutionState;
import gobblin.runtime.api.JobLifecycleListener;
import gobblin.runtime.api.JobSpecSchedulerListenersContainer;

/**
 * Unit tests for {@link JobLifecycleListenersList}
 */
public class TestJobLifecycleListenersList {

  @Test public void testHappyPath() {
    Logger log = LoggerFactory.getLogger("testHappyPath");
    JobCatalogListenersContainer jobCatalog = mock(JobCatalogListenersContainer.class);
    JobSpecSchedulerListenersContainer jobScheduler = mock(JobSpecSchedulerListenersContainer.class);
    JobExecutionDriver mockDriver = mock(JobExecutionDriver.class);
    JobExecutionState mockState = mock(JobExecutionState.class);

    JobLifecycleListener listener1 = mock(JobLifecycleListener.class);
    JobLifecycleListener listener2 = mock(JobLifecycleListener.class);

    JobLifecycleListenersList disp = new JobLifecycleListenersList(jobCatalog, jobScheduler, log);

    disp.registerJobLifecycleListener(listener1);
    disp.onJobLaunch(mockDriver);

    disp.registerWeakJobLifecycleListener(listener2);
    disp.onMetadataChange(mockState, "key", "oldValue", "newValue");

    verify(jobCatalog).addListener(eq(listener1));
    verify(jobScheduler).registerJobSpecSchedulerListener(eq(listener1));
    verify(listener1).onJobLaunch(eq(mockDriver));
    verify(listener2, never()).onJobLaunch(eq(mockDriver));

    verify(jobCatalog).registerWeakJobCatalogListener(eq(listener2));
    verify(jobScheduler).registerWeakJobSpecSchedulerListener(eq(listener2));
    verify(listener1).onMetadataChange(eq(mockState), eq("key"), eq("oldValue"), eq("newValue"));
    verify(listener2).onMetadataChange(eq(mockState), eq("key"), eq("oldValue"), eq("newValue"));
  }

}

redpajama_set_name: RedPajamaGithub


text:
package com.etc.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.bean.TeacherInfoBean;
import com.etc.server.TeacherServer;
import com.etc.server.TeacherServerImpl;

@WebServlet("/TeacherinfoFetchServlet")
public class TeacherinfoFetchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String sort = request.getParameter("sort");
		String idString = request.getParameter("id");
		String message = "";
		String url = "./TeacherinfoListServlet";
		TeacherInfoBean teacherInfoBean = null;
		try {
			int id = Integer.parseInt(idString);
			TeacherServer teacherServer = new TeacherServerImpl();
			teacherInfoBean = new TeacherInfoBean();
			teacherInfoBean = teacherServer.TeacherinfoFetchById(id);
			if (teacherInfoBean != null) {
				if (sort!=null && sort.equals("view")) {
					url = "teacherinfo_view.jsp";
				} else if (sort!=null && sort.equals("update")) {
					url = "teacherinfo_update.jsp";
				} else {
					message = "操作不明确!";
				}
			} else {
				message = "暂无此管理员信息";
			}

		} catch (Exception e) {
			message = "管理员id不合法!";
			url="teacherinfo_list.jsp";
		}
		request.setAttribute("teacherInfoBean", teacherInfoBean);
		request.setAttribute("message", message);
		request.getRequestDispatcher(url).forward(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}


text:
"""
Some wrappers to avoid circular imports, or make certain calls easier.

The idea of a 'global' vispy.use function is that although vispy.app
and vispy.gloo.gl can be used independently, they are not complely
independent for some configureation. E.g. when using real ES 2.0,
the app backend should use EGL and not a desktop OpenGL context. Also,
we probably want it to be easy to configure vispy to use the ipython
notebook backend, which requires specifc config of both app and gl.

This module does not have to be aware of the available app and gl
backends, but it should be(come) aware of (in)compatibilities between
them.
"""

import subprocess
import inspect

def use(app=None, gl=None):
    """ Set the usage options for vispy

    Specify what app backend and GL backend to use.

    Parameters
    ----------
    app : str
        The app backend to use (case insensitive). Standard backends:
            * 'PyQt4': use Qt widget toolkit via PyQt4.
            * 'PyQt5': use Qt widget toolkit via PyQt5.
            * 'PySide': use Qt widget toolkit via PySide.
            * 'PyGlet': use Pyglet backend.
            * 'Glfw': use Glfw backend (successor of Glut). Widely available
              on Linux.
            * 'SDL2': use SDL v2 backend.
        Additional backends:
            * 'ipynb_vnc': render in the IPython notebook via a VNC approach
              (experimental)
    gl : str
        The gl backend to use (case insensitive). Options are:
            * 'gl2': use Vispy's desktop OpenGL API.
            * 'pyopengl2': use PyOpenGL's desktop OpenGL API. Mostly for
              testing.
            * 'es2': (TO COME) use real OpenGL ES 2.0 on Windows via Angle.
              Availability of ES 2.0 is larger for Windows, since it relies
              on DirectX.
            * 'gl+': use the full OpenGL functionality available on
              your system (via PyOpenGL).

    Notes
    -----
    If the app option is given, ``vispy.app.use_app()`` is called. If
    the gl option is given, ``vispy.gloo.use_gl()`` is called.

    If an app backend name is provided, and that backend could not be
    loaded, an error is raised.

    If no backend name is provided, Vispy will first check if the GUI
    toolkit corresponding to each backend is already imported, and try
    that backend first. If this is unsuccessful, it will try the
    'default_backend' provided in the vispy config. If still not
    succesful, it will try each backend in a predetermined order.

    See Also
    --------
    vispy.app.use_app
    vispy.gloo.gl.use_gl
    """
    if app is None and gl is None:
        raise TypeError('Must specify at least one of "app" or "gl".')

    # Example for future. This wont work (yet).
    if app == 'ipynb_webgl':
        app = 'headless'
        gl = 'webgl'

    # Apply now
    if gl:
        import vispy.gloo
        from vispy import config
        config['gl_backend'] = gl
        vispy.gloo.gl.use_gl(gl)
    if app:
        import vispy.app
        vispy.app.use_app(app)

def run_subprocess(command, return_code=False, **kwargs):
    """Run command using subprocess.Popen

    Run command and wait for command to complete. If the return code was zero
    then return, otherwise raise CalledProcessError.
    By default, this will also add stdout= and stderr=subproces.PIPE
    to the call to Popen to suppress printing to the terminal.

    Parameters
    ----------
    command : list of str
        Command to run as subprocess (see subprocess.Popen documentation).
    return_code : bool
        If True, the returncode will be returned, and no error checking
        will be performed (so this function should always return without
        error).
    **kwargs : dict
        Additional kwargs to pass to ``subprocess.Popen``.

    Returns
    -------
    stdout : str
        Stdout returned by the process.
    stderr : str
        Stderr returned by the process.
    code : int
        The command exit code. Only returned if ``return_code`` is True.
    """
    # code adapted with permission from mne-python
    use_kwargs = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    use_kwargs.update(kwargs)

    p = subprocess.Popen(command, **use_kwargs)
    output = p.communicate()

    # communicate() may return bytes, str, or None depending on the kwargs
    # passed to Popen(). Convert all to unicode str:
    output = ['' if s is None else s for s in output]
    output = [s.decode('utf-8') if isinstance(s, bytes) else s for s in output]
    output = tuple(output)

    if not return_code and p.returncode:
        print(output[0])
        print(output[1])
        err_fun = subprocess.CalledProcessError.__init__
        if 'output' in inspect.getargspec(err_fun).args:
            raise subprocess.CalledProcessError(p.returncode, command, output)
        else:
            raise subprocess.CalledProcessError(p.returncode, command)
    if return_code:
        output = output + (p.returncode,)
    return output


text:
{% extends path+"/scenario_prompts-typical_01b/_layout-case-simple-full-width.html" %}

{% block citizen_content %}

{{ data.nuggets | log }}

Back

Condition history

Mental health risk

Suicidal ideation

<form action="condition-history_home" method="post">

	<fieldset>
		<legend class="mb10">Have they ever thought about harming themselves in any way?</legend>

				<input id="selfHarmThoughtsYes" name="selfHarmQuestion" type="radio" value="yes">
				Yes

	<fieldset>
		<legend class="mb10">Has there been an actual attempt or act of self-harm?</legend>

				<input id="continenceYes" name="continencePads" type="radio" value="yes~/fha/assessment-scenarios/scenario_prompts_01a/condition-history_RiskFull">
				Yes

				<input id="continenceNo" name="continencePads" type="radio" value="no~/fha/assessment-scenarios/scenario_prompts_01a/condition-history_RiskOngoing">
				No

	</fieldset>

				<input id="selfHarmThoughtsNo" name="selfHarmQuestion" type="radio" value="no~/fha/assessment-scenarios/scenario_prompts_01a/condition-history_RiskOther">
				No

		</fieldset>

<input type="submit" class="button" value="Save and continue" id="submitButton">

      </form>

{% endblock %}


text:
layout: page
title: Delgado Diamond Tech Show
date: 2016-05-24
author: Mildred Wiggins
tags: weekly links, java
status: published
summary: Aliquam et magna diam. Donec egestas augue eu nulla volutpat.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 11/15/2019
  endDate: 11/20/2019
  ctyhocn: CMHHSHX
  groupCode: DDTS
published: true
---
Sed tincidunt, lorem convallis volutpat accumsan, est magna euismod nulla, sed tempor neque urna sit amet sapien. Sed nec mauris commodo, facilisis sapien sit amet, eleifend lectus. Proin et dui sed dui pellentesque accumsan. Morbi ac condimentum elit, sit amet euismod mi. Etiam porttitor quam nunc. Proin mollis diam a orci dignissim lacinia. Pellentesque tincidunt lacus eu magna efficitur, quis semper neque convallis. Duis vitae aliquam lectus. Fusce consequat eget sapien sed pulvinar.

* In dignissim nunc ut condimentum bibendum.

Sed malesuada gravida mollis. Vestibulum tempus diam mauris. Vestibulum et vulputate lectus. Aenean id dictum libero, quis ornare elit. Curabitur nisi nunc, tincidunt quis placerat at, sodales eu ante. Integer luctus sem at accumsan condimentum. Sed eget nunc vel orci maximus facilisis. Cras bibendum rutrum iaculis.
Mauris scelerisque tellus nunc, eget finibus orci dapibus vitae. Curabitur quis nunc dapibus, facilisis nisl nec, tempus justo. Sed non pretium ex. Aliquam facilisis tortor nec dolor lobortis cursus. Phasellus auctor, mauris eu dapibus blandit, arcu dui feugiat ante, a lobortis dolor nisi ut dui. Nulla rutrum posuere erat, nec vestibulum orci ultrices eu. Nulla ultrices ante lectus. Proin nisi dolor, mollis quis sapien in, pharetra dictum massa. Vivamus vel ex at dolor laoreet cursus at non dolor. Integer ornare elit ut tortor convallis interdum. Vestibulum quis eleifend nunc. Integer porttitor quam eu ullamcorper rutrum. Nunc cursus tellus sodales pellentesque vestibulum. Praesent consectetur scelerisque turpis a venenatis. Quisque porta luctus elit, nec ornare metus tincidunt id. Duis finibus dui sed malesuada varius.


text:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_purple">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/paged_scene_3_text"
        android:textColor="@android:color/white"
        style="@style/TutorialText"/>
</RelativeLayout>


text:
package com.bevelio.ultragames.commands;

import java.util.Arrays;
import java.util.UUID;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.bevelio.ultragames.core.MatchManager;
import com.bevelio.ultragames.core.MatchState;
import com.bevelio.ultragames.plugin.BevelioPlugin;
import com.bevelio.ultragames.team.Team;

public class SkipCommand extends Command
{

	public SkipCommand()
	{
		super("Skip", "Skip to the next game", "/skip", Arrays.asList("end"));
	}

	@Override
	public boolean execute(CommandSender sender, String commandLabel, String[] args)
	{
		if(!(sender instanceof Player))
		{
			sender.sendMessage(ChatColor.RED + "Only players can do this command.");
			return false;
		}
		Player player = (Player) sender;

		if(player.hasPermission("ultragames.commands.skip"))
		{
			MatchManager mm = BevelioPlugin.getMatchManager();

			mm.setState(MatchState.FINISHING);
			player.sendMessage(ChatColor.GREEN + "Match ended!");
		}
		return false;
	}

}


text:
require 'rails_helper'

describe Cangaroo::CountJsonObject do
  subject(:context) { Cangaroo::CountJsonObject.call(json_body: json_body) }

  let(:json_body) { JSON.parse(load_fixture('json_payload_ok.json')) }

  describe '.call' do
    it 'provides the object_count' do
      expect(context.object_count)
        .to eq('orders' => 2, 'shipments' => 2,
               'line_items' => 0, 'line-items' => 0)
    end

    it 'succeeds' do
      expect(context).to be_a_success
    end
  end
end


text:
using Xunit;

// In SDK-style projects such as this one, several assembly attributes that were historically
// defined in this file are now automatically added during build and populated with
// values defined in project properties. For details of which attributes are included
// and how to customise this process see: https://aka.ms/assembly-info-properties

// Setting ComVisible to false makes the types in this assembly not visible to COM
// components.  If you need to access a type in this assembly from COM, set the ComVisible
// attribute to true on that type.

[assembly: CollectionBehavior(DisableTestParallelization = true)]


text:
package com.automation.seletest.pagecomponents.pageObjects.Web;

import java.text.MessageFormat;

import lombok.extern.slf4j.Slf4j;

import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.springframework.stereotype.Component;

import com.automation.seletest.core.selenium.common.KeyInfo;
import com.automation.seletest.core.selenium.webAPI.elements.Locators;
import com.automation.seletest.pagecomponents.pageObjects.AbstractPage;

/**
 * @author Giannis Papadakis(mailTo:gpapadakis84@gmail.com)
 *
 */
@Component
@Slf4j
public class GitHubSearchPage extends AbstractPage<GitHubSearchPage>{

    public enum GitHubPageLocators {

        DIV_PARENT("$(\"[class*='container clearfix']\").css(\"borderStyle\", \"dotted\" )") {
            @Override
            public String log() {
               return "Parent div element" + DIV_PARENT.get() + "'!!!";
            }
        },
        BTN_SIGN_IN("jquery=a:contains(Sign in)") {
            @Override
            public String log() {
               return "Button \"Sign in\" used with locator: '" + BTN_SIGN_IN.get() + "'!!!";
            }
        },
        BTN_SEARCH("name=q") {
            @Override
            public String log() {
                return "Button \"Search\" used with locator: '" + BTN_SEARCH.get() + "'!!!";
            }
        },
        ;

    private final String myLocator;

    GitHubPageLocators(String locator) {
        myLocator = locator;
    }

    public String get() {
        return myLocator;
    }

    public String getWithParams(Object... params) {
        return MessageFormat.format(myLocator, params);
    }

    // Abstract method which need to be implemented
    public abstract String log();

}

    public GitHubSearchPage searchRepository(String search) {
        webControl().type(GitHubPageLocators.BTN_SEARCH.get(),search);
        actionsControl().press(KeyInfo.ENTER).performActions();
        return this;
    }

    public GitHubSearchPage openPage() {
        openPage(GitHubSearchPage.class);
        for(GitHubPageLocators s: GitHubPageLocators.values()) {
            log.info("The following locator will be used in GitHubPage PO : "+s.log());
        }
        webControl().executeJS(GitHubPageLocators.DIV_PARENT.get());
        return this;
    }

    /* (non-Javadoc)
     * @see com.automation.seletest.pagecomponents.pageObjects.AbstractPage#getPageLoadCondition()
     */
    @Override
    protected ExpectedCondition<?> getPageLoadCondition() {
        return ExpectedConditions.presenceOfElementLocated(Locators.findByLocator(GitHubPageLocators.BTN_SEARCH.get()).setLocator(GitHubPageLocators.BTN_SEARCH.get()));

    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<products xmlns:xlink="http://www.w3.org/1999/xlink">
   <latestpdf>MidoNet_Quick_Start_Guide_Ubuntu-1404_Kilo_JA_5.0-SNAPSHOT-latest.pdf</latestpdf>
   <pdfoutname>MidoNet_Quick_Start_Guide_Ubuntu-1404_Kilo_JA_5.0-SNAPSHOT.pdf</pdfoutname>
   <docname>MidoNet クイック スタート ガイド Ubuntu 14.04 / Kilo</docname>
   <productname>MidoNet クイック スタート ガイド</productname>
   <webappname>quick-start-guide/ubuntu-1404_kilo_ja</webappname>
   <pominfo>
      <groupid>org.midonet</groupid>
      <artifactid>midonet-docs-quick-start-guide-ubuntu-1404-kilo-ja</artifactid>
      <version>5.0-SNAPSHOT</version>
      <pomname>midonet-docs-quick-start-guide-ubuntu-1404-kilo-ja v5.0-SNAPSHOT</pomname>
   </pominfo>
</products>


text:
import React from 'react';
import { spy } from 'sinon';
import { assert } from 'chai';
import { createShallow, getClasses } from '../test-utils';
import Input from '../Input';
import FormControl from './FormControl';

describe('<FormControl />', () => {
  let shallow;
  let classes;

  before(() => {
    shallow = createShallow({ dive: true });
    classes = getClasses(<FormControl />);
  });

  describe('initial state', () => {
    it('should render a div with the root and user classes', () => {
      const wrapper = shallow(<FormControl className="woofFormControl" />);

      assert.strictEqual(wrapper.name(), 'div');
      assert.strictEqual(wrapper.hasClass(classes.root), true);
      assert.strictEqual(wrapper.hasClass('woofFormControl'), true);
    });

    it('should have the focused class', () => {
      const wrapper = shallow(<FormControl className="woofFormControl" />);

      assert.strictEqual(wrapper.name(), 'div');
      assert.strictEqual(wrapper.hasClass(classes.root), true);
      assert.strictEqual(wrapper.hasClass('woofFormControl'), true);
    });

    it('should have no margin', () => {
      const wrapper = shallow(<FormControl />);

      assert.strictEqual(wrapper.name(), 'div');
      assert.strictEqual(wrapper.hasClass(classes.marginNormal), false);
      assert.strictEqual(wrapper.hasClass(classes.marginDense), false);
    });

    it('should have the margin normal class', () => {
      const wrapper = shallow(<FormControl margin="normal" />);

      assert.strictEqual(wrapper.name(), 'div');
      assert.strictEqual(wrapper.hasClass(classes.marginNormal), true);
    });

    it('should have the margin dense class', () => {
      const wrapper = shallow(<FormControl margin="dense" />);

      assert.strictEqual(wrapper.name(), 'div');
      assert.strictEqual(wrapper.hasClass(classes.marginDense), true);
      assert.strictEqual(wrapper.hasClass(classes.marginNormal), false);
    });
  });

  describe('initial state', () => {
    let wrapper;

    beforeEach(() => {
      wrapper = shallow(<FormControl />);
    });

    it('should not be dirty initially', () => {
      assert.strictEqual(wrapper.state().dirty, false);
    });

    it('should not be focused initially', () => {
      assert.strictEqual(wrapper.state().focused, false);
    });
  });

  describe('should be dirty if has input with value set', () => {
    it('should be dirty with a value', () => {
      const wrapper = shallow(
        <FormControl>
          <Input value="bar" />
        </FormControl>,
      );
      assert.strictEqual(wrapper.state().dirty, true);
    });

    it('should be dirty with a defaultValue', () => {
      const wrapper = shallow(
        <FormControl>
          <Input defaultValue="bar" />
        </FormControl>,
      );
      assert.strictEqual(wrapper.state().dirty, true);
    });
  });

  describe('muiFormControl child context', () => {
    let wrapper;
    let muiFormControlContext;

    function loadChildContext() {
      muiFormControlContext = wrapper.instance().getChildContext().muiFormControl;
    }

    beforeEach(() => {
      wrapper = shallow(<FormControl />);
      loadChildContext();
    });

    describe('from state', () => {
      it('should have the dirty state from the instance', () => {
        assert.strictEqual(muiFormControlContext.dirty, false);
        wrapper.setState({ dirty: true });
        loadChildContext();
        assert.strictEqual(muiFormControlContext.dirty, true);
      });

      it('should have the focused state from the instance', () => {
        assert.strictEqual(muiFormControlContext.focused, false);
        wrapper.setState({ focused: true });
        loadChildContext();
        assert.strictEqual(muiFormControlContext.focused, true);
      });
    });

    describe('from props', () => {
      it('should have the required prop from the instance', () => {
        assert.strictEqual(muiFormControlContext.required, false);
        wrapper.setProps({ required: true });
        loadChildContext();
        assert.strictEqual(muiFormControlContext.required, true);
      });

      it('should have the error prop from the instance', () => {
        assert.strictEqual(muiFormControlContext.error, false);
        wrapper.setProps({ error: true });
        loadChildContext();
        assert.strictEqual(muiFormControlContext.error, true);
      });

      it('should have the margin prop from the instance', () => {
        assert.strictEqual(muiFormControlContext.margin, 'none');
        wrapper.setProps({ margin: 'dense' });
        loadChildContext();
        assert.strictEqual(muiFormControlContext.margin, 'dense');
      });
    });

    describe('callbacks', () => {
      describe('onDirty', () => {
        it('should set the dirty state', () => {
          assert.strictEqual(muiFormControlContext.dirty, false);
          muiFormControlContext.onDirty();
          loadChildContext();
          assert.strictEqual(muiFormControlContext.dirty, true);
          muiFormControlContext.onDirty();
          assert.strictEqual(muiFormControlContext.dirty, true);
        });
      });

      describe('onClean', () => {
        it('should clean the dirty state', () => {
          muiFormControlContext.onDirty();
          loadChildContext();
          assert.strictEqual(muiFormControlContext.dirty, true);
          muiFormControlContext.onClean();
          loadChildContext();
          assert.strictEqual(muiFormControlContext.dirty, false);
          muiFormControlContext.onClean();
          assert.strictEqual(muiFormControlContext.dirty, false);
        });
      });

      describe('handleFocus', () => {
        it('should set the focused state', () => {
          assert.strictEqual(wrapper.state('focused'), false);
          muiFormControlContext.onFocus();
          assert.strictEqual(wrapper.state('focused'), true);
          muiFormControlContext.onFocus();
          assert.strictEqual(wrapper.state('focused'), true);
        });

        it('should be able to use a onFocus property', () => {
          const handleFocus = spy();
          wrapper.setProps({
            onFocus: handleFocus,
          });
          muiFormControlContext.onFocus();
          assert.strictEqual(handleFocus.callCount, 1);
        });
      });

      describe('handleBlur', () => {
        it('should clear the focused state', () => {
          assert.strictEqual(wrapper.state('focused'), false);
          muiFormControlContext.onFocus();
          assert.strictEqual(wrapper.state('focused'), true);
          muiFormControlContext.onBlur();
          assert.strictEqual(wrapper.state('focused'), false);
          muiFormControlContext.onBlur();
          assert.strictEqual(wrapper.state('focused'), false);
        });

        it('should be able to use a onBlur property', () => {
          const handleBlur = spy();
          wrapper.setProps({
            onBlur: handleBlur,
          });
          muiFormControlContext.onFocus();
          muiFormControlContext.onBlur();
          assert.strictEqual(handleBlur.callCount, 1);
        });
      });
    });
  });
});


text:
<?php

/**
 * DO NOT EDIT!
 * This file was automatically generated via bin/generate-validator-spec.php.
 */

namespace AmpProject\Validator\Spec\Tag;

use AmpProject\Extension;
use AmpProject\Format;
use AmpProject\Html\Attribute;
use AmpProject\Html\Tag as Element;
use AmpProject\Validator\Spec\AttributeList;
use AmpProject\Validator\Spec\Identifiable;
use AmpProject\Validator\Spec\SpecRule;
use AmpProject\Validator\Spec\Tag;

/**
 * Tag class InputMaskCustomMask.
 *
 * @package ampproject/amp-toolbox.
 *
 * @property-read string $tagName
 * @property-read string $specName
 * @property-read array $attrs
 * @property-read array<string> $attrLists
 * @property-read string $specUrl
 * @property-read array<string> $htmlFormat
 * @property-read array<string> $requiresExtension
 */
final class InputMaskCustomMask extends Tag implements Identifiable
{
    /**
     * ID of the tag.
     *
     * @var string
     */
    const ID = 'input [mask] (custom mask)';

    /**
     * Array of spec rules.
     *
     * @var array
     */
    const SPEC = [
        SpecRule::TAG_NAME => Element::INPUT,
        SpecRule::SPEC_NAME => 'input [mask] (custom mask)',
        SpecRule::ATTRS => [
            Attribute::MASK => [
                SpecRule::MANDATORY => true,
                SpecRule::DISALLOWED_VALUE_REGEX => '(payment-card|date-dd-mm-yyyy|date-mm-dd-yyyy|date-mm-yy|date-yyyy-mm-dd)',
                SpecRule::DISPATCH_KEY => 'NAME_DISPATCH',
            ],
            Attribute::MASK_TRIM_ZEROS => [
                SpecRule::VALUE_REGEX => '\d+',
            ],
            '[type]' => [],
        ],
        SpecRule::ATTR_LISTS => [
            AttributeList\AmpInputmaskCommonAttr::ID,
            AttributeList\InputCommonAttr::ID,
            AttributeList\NameAttr::ID,
        ],
        SpecRule::SPEC_URL => 'https://amp.dev/documentation/components/amp-inputmask/',
        SpecRule::HTML_FORMAT => [
            Format::AMP,
        ],
        SpecRule::REQUIRES_EXTENSION => [
            Extension::INPUTMASK,
        ],
    ];
}


text:
module Macros4Cuke # Module used as a namespace
  # Namespace for all formatters of MacroCollection and MacroStep objects
  module Formatter
    # The list of all formatting notifications
    AllNotifications = %i[
      on_collection
      on_collection_end
      on_step
      on_step_end
      on_phrase
      on_renderer
      on_renderer_end
      on_source
      on_static_text
      on_eol
      on_comment
      on_placeholder
      on_section
      on_section_end
    ].freeze
  end # module
end # module

# End of file


text:
package flatbuf

import (
	flatbuffers "github.com/google/flatbuffers/go"
)

type SparseTensor struct {
	_tab flatbuffers.Table
}

func GetRootAsSparseTensor(buf []byte, offset flatbuffers.UOffsetT) *SparseTensor {
	n := flatbuffers.GetUOffsetT(buf[offset:])
	x := &SparseTensor{}
	x.Init(buf, n+offset)
	return x
}

func (rcv *SparseTensor) Init(buf []byte, i flatbuffers.UOffsetT) {
	rcv._tab.Bytes = buf
	rcv._tab.Pos = i
}

func (rcv *SparseTensor) Table() flatbuffers.Table {
	return rcv._tab
}

func (rcv *SparseTensor) TypeType() Type {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(4))
	if o != 0 {
		return Type(rcv._tab.GetByte(o + rcv._tab.Pos))
	}
	return 0
}

func (rcv *SparseTensor) MutateTypeType(n Type) bool {
	return rcv._tab.MutateByteSlot(4, byte(n))
}

/// The type of data contained in a value cell.
/// Currently only fixed-width value types are supported,
/// no strings or nested types.
func (rcv *SparseTensor) Type(obj *flatbuffers.Table) bool {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(6))
	if o != 0 {
		rcv._tab.Union(obj, o)
		return true
	}
	return false
}

/// The type of data contained in a value cell.
/// Currently only fixed-width value types are supported,
/// no strings or nested types.
/// The dimensions of the tensor, optionally named.
func (rcv *SparseTensor) Shape(obj *TensorDim, j int) bool {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
	if o != 0 {
		x := rcv._tab.Vector(o)
		x += flatbuffers.UOffsetT(j) * 4
		x = rcv._tab.Indirect(x)
		obj.Init(rcv._tab.Bytes, x)
		return true
	}
	return false
}

func (rcv *SparseTensor) ShapeLength() int {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(8))
	if o != 0 {
		return rcv._tab.VectorLen(o)
	}
	return 0
}

/// The dimensions of the tensor, optionally named.
/// The number of non-zero values in a sparse tensor.
func (rcv *SparseTensor) NonZeroLength() int64 {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(10))
	if o != 0 {
		return rcv._tab.GetInt64(o + rcv._tab.Pos)
	}
	return 0
}

/// The number of non-zero values in a sparse tensor.
func (rcv *SparseTensor) MutateNonZeroLength(n int64) bool {
	return rcv._tab.MutateInt64Slot(10, n)
}

func (rcv *SparseTensor) SparseIndexType() SparseTensorIndex {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(12))
	if o != 0 {
		return SparseTensorIndex(rcv._tab.GetByte(o + rcv._tab.Pos))
	}
	return 0
}

func (rcv *SparseTensor) MutateSparseIndexType(n SparseTensorIndex) bool {
	return rcv._tab.MutateByteSlot(12, byte(n))
}

/// Sparse tensor index
func (rcv *SparseTensor) SparseIndex(obj *flatbuffers.Table) bool {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(14))
	if o != 0 {
		rcv._tab.Union(obj, o)
		return true
	}
	return false
}

/// Sparse tensor index
/// The location and size of the tensor's data
func (rcv *SparseTensor) Data(obj *Buffer) *Buffer {
	o := flatbuffers.UOffsetT(rcv._tab.Offset(16))
	if o != 0 {
		x := o + rcv._tab.Pos
		if obj == nil {
			obj = new(Buffer)
		}
		obj.Init(rcv._tab.Bytes, x)
		return obj
	}
	return nil
}

/// The location and size of the tensor's data
func SparseTensorStart(builder *flatbuffers.Builder) {
	builder.StartObject(7)
}
func SparseTensorAddTypeType(builder *flatbuffers.Builder, typeType Type) {
	builder.PrependByteSlot(0, byte(typeType), 0)
}
func SparseTensorAddType(builder *flatbuffers.Builder, type_ flatbuffers.UOffsetT) {
	builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(type_), 0)
}
func SparseTensorAddShape(builder *flatbuffers.Builder, shape flatbuffers.UOffsetT) {
	builder.PrependUOffsetTSlot(2, flatbuffers.UOffsetT(shape), 0)
}
func SparseTensorStartShapeVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT {
	return builder.StartVector(4, numElems, 4)
}
func SparseTensorAddNonZeroLength(builder *flatbuffers.Builder, nonZeroLength int64) {
	builder.PrependInt64Slot(3, nonZeroLength, 0)
}
func SparseTensorAddSparseIndexType(builder *flatbuffers.Builder, sparseIndexType SparseTensorIndex) {
	builder.PrependByteSlot(4, byte(sparseIndexType), 0)
}
func SparseTensorAddSparseIndex(builder *flatbuffers.Builder, sparseIndex flatbuffers.UOffsetT) {
	builder.PrependUOffsetTSlot(5, flatbuffers.UOffsetT(sparseIndex), 0)
}
func SparseTensorAddData(builder *flatbuffers.Builder, data flatbuffers.UOffsetT) {
	builder.PrependStructSlot(6, flatbuffers.UOffsetT(data), 0)
}
func SparseTensorEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT {
	return builder.EndObject()
}


text:
package com.squarespace.less.exec;

import com.squarespace.less.model.Mixin;
import com.squarespace.less.model.MixinParams;
import com.squarespace.less.model.Node;
import com.squarespace.less.model.Ruleset;
import com.squarespace.less.model.Selector;

/**
 * Represents a single match found during mixin resolution.
 */
public class MixinMatch {

  /**
   * The mixin being matched. This can be either a {@link Ruleset} or {@link Mixin}.
   */
  private final Node mixin;

  /**
   * {@link Selector} we're matching.
   */
  private final Selector selector;

  /**
   * Parameters for the {@link Mixin}.
   */
  private final MixinParams params;

  public MixinMatch(Node mixin, Selector selector, MixinParams params) {
    this.mixin = mixin;
    this.selector = selector;
    this.params = params;
  }

  public Node mixin() {
    return mixin;
  }

  public Selector selector() {
    return selector;
  }

  public MixinParams params() {
    return params;
  }

}


text:
from django.test import TestCase
from .models import Client, Contact

class ClientTestCase(TestCase):
    def setUp(self):
        Client.objects.create(name='Test Starbucks', address='Felipe Ángeles 225')
        Client.objects.create(name='Test OXXO', address='Reforma 190')

    def test_client_names(self):
        """The objects are created and their __str__ func works"""
        starbucks = Client.objects.get(name='Test Starbucks')
        oxxo = Client.objects.get(name='Test OXXO')
        self.assertEqual(str(starbucks), 'Test Starbucks')
        self.assertEqual(str(oxxo), 'Test OXXO')

class ContactTestCase(ClientTestCase):
    def setUp(self):
        starbucks = Client.objects.create(name='Test Starbucks', address='Felipe Ángeles 225')
        Client.objects.create(name='Test OXXO', address='Reforma 190')

        Contact.objects.create(
            name='Fernando',
            last_name='Lobato Meeser',
            charge='Project Owner',
            landline='4424674323',
            mobile_phone_1='2341631',
            email='lobato.meeser.fernando@hotmail.com',
            alternate_email='ferlobo93@hotmail.com',
            client=starbucks)

    def test_contact_name(self):
        """Tests if the objects are being created in the database and their __str__ func works
        """
        client_instance = Contact.objects.get(name='Fernando')
        self.assertEqual(str(client_instance), 'Fernando Lobato Meeser')

    def test_relation_contact(self):
        """Test if the contact objects are correctly referecing their clients.
        """
        client_instance = Contact.objects.get(name='Fernando')
        starbucks = Client.objects.get(name='Test Starbucks')
        self.assertEqual(client_instance.client, starbucks)


text:
module SpreeSkrillRecurring
  class ApplicationController < ActionController::Base
  	private
	  def recurring_params
	    params.require(:recurring).permit(:preferred_merchant_id, :preferred_language, :preferred_currency, :preferred_payment_options, :preferred_server, :preferred_test_mode)
	  end
  end
end


text: warnings={{ count }}


text:
var CoreJsLanguage = {
    "No items in recent compare list!": "No items in recent compare list!",
    "Error Message": "Error Message",
    "Successful Message": "Successful Message",
    "Failed to add item in compare list!": "Failed to add item in compare list!",
    "Information Alert": "Information Alert",
    "The selected item already exist in wishlist.": "The selected item already exist in wishlist.",
    "Failed to add item in wishlist!": "Failed to add item in wishlist!",
    "Item has been successfully added to wishlist.": "Item has been successfully added to wishlist.",
    "Item has been successfully added to cart.": "Item has been successfully added to cart.",
    "This product is currently out of stock!.": "This product is currently out of stock!.",
    "OK": "OK",
    "Continue Shopping": "Continue Shopping",
    "CheckOut": "CheckOut",
    "Cancel": "Cancel",
    "Yes": "Yes",
    "No": "No",
    "View Per Page:": "View Per Page:",
    "Page": "Page",
    "Of": "Of",
    "View": "View",
    "records": "records",
    "Showing": "Showing",
    "Pages": "Pages",
    "Prev": "Prev",
    "Next": "Next",
    "No items found!": "No items found!",
    "Sorry, Failed to load sortby options!": "Sorry, Failed to load sortby options!",
    "Sorry, Failed to load viewas options!": "Sorry, Failed to load viewas options!",
    "Out Of Stock": "Out Of Stock",
    "Add to cart": "Add to cart",
    "Add to Wishlist": "Add to Wishlist",
    "View Details": "View Details",
    "This store has no items listed yet!": "This store has no items listed yet!",
    "This field is required.": "This field is required.",
    "Please fix this field.": "Please fix this field.",
    "Please enter a valid email address.": "Please enter a valid email address.",
    "Please enter a valid URL.": "Please enter a valid URL.",
    "Please enter a valid date.": "Please enter a valid date.",
    "Please enter a valid date (ISO).": "Please enter a valid date (ISO).",
    "Please enter a valid number.": "Please enter a valid number.",
    "Please enter alpha numeri": "Please enter alpha numeri",
    "Please enter only digits": "Please enter only digits",
    "Please enter a valid credit card number.": "Please enter a valid credit card number.",
    "Please enter the same value again.": "Please enter the same value again.",
    "Please enter a value with a valid extension.": "Please enter a value with a valid extension.",
    "Please enter no more than {0} characters.": "Please enter no more than {0} characters.",
    "(at least {0} characters.)": "(at least {0} characters.)",
    "Please enter a value between {0} and {1} characters long.": "Please enter a value between {0} and {1} characters long.",
    "Please enter a value between {0} and {1}.": "Please enter a value between {0} and {1}.",
    "Please enter a value less than or equal to {0}.": "Please enter a value less than or equal to {0}.",
    "Please enter a value greater than or equal to {0}.": "Please enter a value greater than or equal to {0}.",
    "Download the file now?": "Download the file now?",
    "AspxCommerce download sample item:": "AspxCommerce download sample item:",
    "AspxCommerce download actual item:": "AspxCommerce download actual item:",
    "Fetching File...": "Fetching File...",
    "Fatal Error.": "Fatal Error.",
    "File cannot be found.": "File cannot be found.",
    "This file type is not allowed.": "This file type is not allowed.",
    "This file is not found!": "This file is not found!",
    "File Name:": "File Name:",
    "File Type:": "File Type:",
    "File Size:": "File Size:",
    "Cancel": "Cancel",
    "Download": "Download",
    "Active To date must be higher date than Active From date!": "Active To date must be higher date than Active From date!",
    "You have entered invalid Active To date!": "You have entered invalid Active To date!",
    "You have entered invalid Active From date!": "You have entered invalid Active From date!",
    "Mandatory Fields": "Mandatory Fields",
    "Starting At": "Starting At "
};


text:
/**
 * Module dependencies.
 */
var util = require('util'),
    OAuth2Strategy = require('passport-oauth').OAuth2Strategy;

/**
 * `Strategy` constructor.
 *
 * The Nest authentication strategy authenticates with the Nest OAuth server to
 * get an access_token for the Nest API
 *
 * Options:
 *   - `clientID`      Nest client ID
 *   - `clientSecret`  Nest secret
 *
 * Examples:
 *
 *     passport.use(new NestStrategy({
 *       clientID: NEST_ID,
 *       clientSecret: NEST_SECRET,
 *     }));
 *
 * @param {Object} options
 * @param {Funciton} verify (optional)
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.authorizationURL = options.authorizationURL || 'https://home.nest.com/login/oauth2';
  options.tokenURL = options.tokenURL || 'https://api.home.nest.com/oauth2/access_token';

  // Nest requires the state parameter for increased security
  options.state = true;

  // The only data returned is an accessToken, no profile data is available
  // so we handle creating a sparse profile of the user
  verify = verify || function(accessToken, refreshToken, profile, done) {
    done(null, { accessToken: accessToken });
  };

  OAuth2Strategy.call(this, options, verify);

  this.name = 'nest';
}

/**
 * Inherit from `OAuth2Strategy`.
 */
util.inherits(Strategy, OAuth2Strategy);

/**
 * Export Strategy constructor.
 */
module.exports = Strategy;


text:
namespace YAF.Core.Services;

using System;
using System.Collections.Generic;

///
/// Class to Generate The Reputation Bar
///
public class Reputation : IReputation, IHaveServiceLocator
{
    ///
    /// Initializes a new instance of the <see cref="Reputation"/> class.
    ///
    /// <param name="serviceLocator">
    /// The service locator.
    /// </param>
    public Reputation([NotNull] IServiceLocator serviceLocator)
    {
        this.ServiceLocator = serviceLocator;
    }

    ///
    /// Gets or sets ServiceLocator.
    ///
    public IServiceLocator ServiceLocator { get; set; }

    ///
    /// Checks if allow reputation voting.
    ///
    /// <param name="voteDateToCheck">The last vote date to check.</param>
    /// <returns>
    /// Returns if the Users is allowed to Vote
    /// </returns>
    public bool CheckIfAllowReputationVoting(object voteDateToCheck)
    {
        if (voteDateToCheck.IsNullOrEmptyField())
        {
            return true;
        }

        var reputationVoteDate = voteDateToCheck.ToType<DateTime>();

        return reputationVoteDate < DateTime.UtcNow.AddHours(-24);
    }

    ///
    /// Generate The Reputation Bar for the user
    ///
    /// <param name="points">
    /// The points.
    /// </param>
    /// <param name="userId">
    /// The user id.
    /// </param>
    /// <returns>
    /// Returns the Html String
    /// </returns>
    public string GenerateReputationBar([NotNull] int points, [NotNull] int userId)
    {
        var formatInfo = new NumberFormatInfo { NumberDecimalSeparator = "." };

        var percentage = this.Get<IReputation>().ConvertPointsToPercentage(points);

        return $@"

                      <div class=""progress-bar progress-bar-striped{this.Get<IReputation>().GetReputationBarColor(percentage)}""
                           role=""progressbar""
                           style=""width:{percentage.ToString(formatInfo)}%;""
                           aria-valuenow=""{percentage.ToString(formatInfo)}""
                           aria-valuemax=""100"">
                      {percentage.ToString(formatInfo)}% ({this.GetReputationBarText(percentage)})

";
    }

    ///
    /// Gets the reputation bar text.
    ///
    /// <param name="percentage">The percentage.</param>
    /// <returns>Returns the Text for the Current Value</returns>
    [NotNull]
    public string GetReputationBarText([NotNull] float percentage)
    {
        var lookup = new Dictionary<int, string>
                         {
                             { 0, "HATED" },
                             { 20, "HOSTILE" },
                             { 30, "HOSTILE" },
                             { 40, "HOSTILE" },
                             { 50, "UNFRIENDLY" },
                             { 60, "NEUTRAL" },
                             { 80, "FRIENDLY" },
                             { 90, "HONORED" },
                             { int.MaxValue, "EXALTED" }
                         };

        var pageName = "HATED";

        if (percentage > 1)
        {
            pageName =
                lookup.OrderBy(s => s.Key).Where(x => percentage < x.Key).Select(x => x.Value).FirstOrDefault();
        }

        return this.Get<ILocalization>().GetText("REPUTATION_VALUES", pageName);
    }

    ///
    /// Gets the reputation bar color.
    ///
    /// <param name="percentage">The percentage.</param>
    /// <returns>Returns the Color for the Current Value</returns>
    [NotNull]
    public string GetReputationBarColor([NotNull] float percentage)
    {
        var lookup = new Dictionary<int, string>
                         {
                             { 0, " bg-danger" },
                             { 20, " bg-warning" },
                             { 30, " bg-warning" },
                             { 40, " bg-warning" },
                             { 50, " bg-info" },
                             { 60, " bg-info" },
                             { 80, " bg-success" },
                             { 90, " bg-success" },
                             { int.MaxValue, " bg-success" }
                         };

        var color = "bg-danger";

        if (percentage > 1)
        {
            color =
                lookup.OrderBy(s => s.Key).Where(x => percentage < x.Key).Select(x => x.Value).FirstOrDefault();
        }

        return color;
    }

    ///
    /// Converts the points to percentage.
    ///
    /// <param name="points">The points.</param>
    /// <returns>Returns the Percentage Value</returns>
    [NotNull]
    public float ConvertPointsToPercentage([NotNull] int points)
    {
        var percentage = points;

        var minValue = this.Get<BoardSettings>().ReputationMaxNegative;

        var maxValue = this.Get<BoardSettings>().ReputationMaxPositive;

        if (!this.Get<BoardSettings>().ReputationAllowNegative)
        {
            minValue = 0;
        }

        var testValue = minValue + maxValue;

        if (percentage.Equals(0) && this.Get<BoardSettings>().ReputationAllowNegative)
        {
            return 50;
        }

        if (percentage >= maxValue)
        {
            return 100;
        }

        if (percentage <= minValue)
        {
            return 0;
        }

        var returnValue = 100 / (float)testValue * percentage + 50;

        return returnValue > 100 ? 100 : returnValue;
    }
}


text:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace WebApplication2
{
	/// <summary>
	/// Summary description for frmResourcesInfo.
	/// </summary>
	public partial class frmServInputsAll: System.Web.UI.Page
	{
		/*SqlConnection epsDbConn=new SqlConnection("Server=cp2693-a\\eps1;database=eps1;"+
			"uid=tauheed;pwd=tauheed;");*/
		private static string strURL =
			System.Configuration.ConfigurationSettings.AppSettings["local_url"];
		private static string strDB =
			System.Configuration.ConfigurationSettings.AppSettings["local_db"];
		public SqlConnection epsDbConn=new SqlConnection(strDB);
		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			Load_ServInputs();
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{

		}
		#endregion
		private void Load_ServInputs()
		{
			Session["Caller99"]="frmResourcesAll";
			if (Session["btnAddOwn"].ToString() == "false")
			{
				btnAdd.Visible=false;
				DataGrid1.Columns[1].Visible=true;
				DataGrid1.Columns[9].Visible=false;
			}
			else
			{
				btnAdd.Visible=true;
				DataGrid1.Columns[1].Visible=false;
				DataGrid1.Columns[9].Visible=true;
			}
			if (!IsPostBack)
			{
				lblOrg.Text=Session["OrgName"].ToString();
				if (Session["Avail"].ToString() == "Institution")
				{
					lblAvail.Text="Resources available from Other Units";
				}
				else if (Session["Avail"].ToString() == "Public")
				{
					lblAvail.Text="Publicly Available Resources";
				}
				else if (Session["Avail"].ToString() == "Owner")
				{
					lblAvail.Text="Own Resources";
				}
				loadData();
			}
		}
		private void loadData()
		{
			SqlCommand cmd=new SqlCommand();
			cmd.CommandType=CommandType.StoredProcedure;
			cmd.CommandText="eps_RetrieveResourcesAll";
			cmd.Connection=this.epsDbConn;
			cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int);
			cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString();
			cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
			cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
			cmd.Parameters.Add ("@Avail",SqlDbType.NVarChar);
			cmd.Parameters["@Avail"].Value=Session["Avail"].ToString();
			DataSet ds=new DataSet();
			SqlDataAdapter da=new SqlDataAdapter(cmd);
			da.Fill(ds,"ServInputsAll");
			Session["ds"] = ds;
			DataGrid1.DataSource=ds;
			DataGrid1.DataBind();
			refreshGrid();
		}
		private void refreshGrid()
		{
			foreach (DataGridItem i in DataGrid1.Items)
			{
				CheckBox cb = (CheckBox)(i.Cells[8].FindControl("cbxSel"));
				SqlCommand cmd=new SqlCommand();
				cmd.Connection=this.epsDbConn;
				cmd.CommandType=CommandType.Text;
				cmd.CommandText="Select Id from ResourceInputs"
					+ " Where ResourceInput=" + i.Cells[0].Text
					+ " and ResourceOutput=" + Session["ResourceId"];
				cmd.Connection.Open();
				if (cmd.ExecuteScalar() != null) cb.Checked = true;
				cmd.Connection.Close();
			}
		}
		protected void btnOK_Click(object sender, System.EventArgs e)
		{
			SqlCommand cmd=new SqlCommand();
			cmd.CommandType=CommandType.StoredProcedure;
			cmd.CommandText="eps_DeleteServiceInputs";
			cmd.Connection=this.epsDbConn;
			cmd.Parameters.Add ("@ResourceId",SqlDbType.Int);
			cmd.Parameters["@ResourceId"].Value=Session["ResourceId"].ToString();
			cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
			cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
			cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int);
			cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString();
			cmd.Parameters.Add ("@Avail",SqlDbType.NVarChar);
			cmd.Parameters["@Avail"].Value=Session["Avail"].ToString();
			cmd.Connection.Open();
			cmd.ExecuteNonQuery();
			cmd.Connection.Close();
			updateGrid();
			Exit();
		}
		private void updateGrid()
		{
			foreach (DataGridItem i in DataGrid1.Items)
			{
				CheckBox cb = (CheckBox)(i.Cells[8].FindControl("cbxSel"));
				if (cb.Checked)
				{
					SqlCommand cmd=new SqlCommand();
					cmd.CommandType=CommandType.StoredProcedure;
					cmd.CommandText="eps_UpdServInputs";
					cmd.Connection=this.epsDbConn;
					cmd.Parameters.Add("@ResourceOutput", SqlDbType.Int);
					cmd.Parameters ["@ResourceOutput"].Value=Session["ResourceId"].ToString();
					cmd.Parameters.Add("@ResourceInput", SqlDbType.Int);
					cmd.Parameters ["@ResourceInput"].Value=i.Cells[0].Text;
					cmd.Connection.Open();
					cmd.ExecuteNonQuery();
					cmd.Connection.Close();
				}
			}
		}
		private void Exit()
		{
		  Response.Redirect (strURL + Session["Caller3"].ToString() + ".aspx?");
		}

		protected void btnCancel_Click(object sender, System.EventArgs e)
		{
			Response.Redirect (strURL + Session["Caller3"].ToString() + ".aspx?");
		}
	}

}


text:
from django.apps import AppConfig

class Config(AppConfig):
    name = 'plata_charts'
    verbose_name = 'Charts'


text:
var assert = require('assert')
var crypto = require('./crypto')
var ecdsa = require('./ecdsa')
var networks = require('./networks')

var Address = require('./address')

var ecurve = require('ecurve')
var curve = ecurve.getCurveByName('secp256k1')

function ECPubKey(Q, compressed) {
  assert(Q instanceof ecurve.Point, 'Expected Point, got ' + Q)

  if (compressed == undefined) compressed = true
  assert.strictEqual(typeof compressed, 'boolean', 'Expected boolean, got ' + compressed)

  this.compressed = compressed
  this.Q = Q
}

// Static constructors
ECPubKey.fromBuffer = function(buffer) {
  var Q = ecurve.Point.decodeFrom(curve, buffer)
  return new ECPubKey(Q, Q.compressed)
}

ECPubKey.fromHex = function(hex) {
  return ECPubKey.fromBuffer(new Buffer(hex, 'hex'))
}

// Operations
ECPubKey.prototype.getAddress = function(network) {
  network = network || networks.startcoin

  return new Address(crypto.hash160(this.toBuffer()), network.pubKeyHash)
}

ECPubKey.prototype.verify = function(hash, signature) {
  return ecdsa.verify(curve, hash, signature, this.Q)
}

// Export functions
ECPubKey.prototype.toBuffer = function() {
  return this.Q.getEncoded(this.compressed)
}

ECPubKey.prototype.toHex = function() {
  return this.toBuffer().toString('hex')
}

module.exports = ECPubKey


text:
<?php
// auto-generated by sfFilterConfigHandler
// date: 2013/05/06 02:03:14

list($class, $parameters) = (array) sfConfig::get('sf_rendering_filter', array('sfRenderingFilter', array (
)));
$filter = new $class(sfContext::getInstance(), $parameters);
$this->register($filter);

list($class, $parameters) = (array) sfConfig::get('sf_cache_control_filter', array('opCacheControlFilter', null));
$filter = new $class(sfContext::getInstance(), $parameters);
$this->register($filter);

list($class, $parameters) = (array) sfConfig::get('sf_enable_app_filter', array('opCheckEnabledApplicationFilter', null));
$filter = new $class(sfContext::getInstance(), $parameters);
$this->register($filter);

list($class, $parameters) = (array) sfConfig::get('sf_xrds_header_filter', array('opAppendXRDSHeaderFilter', null));
$filter = new $class(sfContext::getInstance(), $parameters);
$this->register($filter);

// does this action require security?
if ($actionInstance->isSecure())
{

list($class, $parameters) = (array) sfConfig::get('sf_security_filter', array('sfBasicSecurityFilter', array (
)));
$filter = new $class(sfContext::getInstance(), $parameters);
$this->register($filter);
}

list($class, $parameters) = (array) sfConfig::get('sf_emoji_filter', array('opEmojiFilter', null));
$filter = new $class(sfContext::getInstance(), $parameters);
$this->register($filter);

list($class, $parameters) = (array) sfConfig::get('sf_execution_filter', array('opExecutionFilter', array (
)));
$filter = new $class(sfContext::getInstance(), $parameters);
$this->register($filter);


text:
package com.facebook.stetho.dumpapp;

/**
 * Usage error in a {@link DumperPlugin}.
 */
public class DumpUsageException extends DumpException {
  public DumpUsageException(String message) {
    super(message);
  }
}


text:
Rule `no-property-vendor-prefix` will enforce that vendor prefixes for properties are not allowed to be used.
We check against Autoprefixers list of prefixable properties from [caniuse.com](https://caniuse.com). If Autoprefixer would handle the prefixing of a property automatically for you it will be flagged as invalid here. If the prefixed property is non standard and Autoprefixer wouldn't handle this for you then this rule will allow it.

## Options

* `additional-identifiers`: `[array of additional prefixes to flag as invalid]` (defaults to empty array `[]`)
* `excluded-identifiers`: `[array of prefixes to exclude checking for]` (defaults to empty array `[]`)

## Examples

When enabled, the following are disallowed:

```scss
.foo {
  -webkit-transform: scale(1);
}
```
When enabled, the following are allowed:

```scss
.foo {
  -webkit-touch-callout: none;
}
```

### Additional Identifiers

When `additional-identifiers` contains a currently allowed property value of `-webkit-touch-callout` as shown below

```yaml
no-property-vendor-prefix:
  - 1
  -
    additional-identifiers:
      - -webkit-touch-callout
```

The following would now also be disallowed

```scss
.baz {
  -webkit-touch-callout: none;
}
```

### Excluded Identifiers

When `excluded-identifiers` contains currently disallowed prefixed properties such as `-webkit-transform` as shown below

```yaml
no-property-vendor-prefix:
  - 1
  -
    excluded-identifiers:
      - -webkit-transform
```

The following would now be allowed

```scss
.foo {
  -webkit-transform: scale(1)
}
```


text:
#region Copyright (c) 2014 Orcomp development team.
// -------------------------------------------------------------------------------------------------------------------
// <copyright file="ValidationResult.cs" company="Orcomp development team">
//   Copyright (c) 2014 Orcomp development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#endregion

namespace SolutionValidator.Common
{
	#region using...
	using System;
	using System.Collections.Generic;
	using Properties;

	#endregion

	public class ValidationResult
	{
		private readonly List<ValidationMessage> _messages;
		private readonly string _ruleDescription;

		public ValidationResult(Rule rule)
		{
			// Currently we do not need to reference the rule itself, and hopefully we will not
			// However it sounds practical to spare the calling client to know how the complete
			// Validation Result metainfo is prepared:
			if (rule != null)
			{
				_ruleDescription = rule.ToString();
			}
			else
			{
				_ruleDescription = Resources.ValidationResult_ValidationResult_Unknown_rule;
			}

			_messages = new List<ValidationMessage>();
			ErrorCount = 0;
			CheckCount = 0;
		}

		public bool IsValid
		{
			get { return ErrorCount == 0; }
		}

		public string RuleDescription
		{
			get { return _ruleDescription; }
		}

		public int ErrorCount { get; private set; }
		public int CheckCount { get; private set; }

		public IEnumerable<ValidationMessage> Messages
		{
			get { return _messages.AsReadOnly(); }
		}

		public void AddResult(ResultLevel resultLevel, string message, Action<ValidationResult> notify = null)
		{
			if (resultLevel == ResultLevel.NotPassed)
			{
				ErrorCount++;
			}

			CheckCount++;
			_messages.Add(new ValidationMessage {ResultLevel = resultLevel, Message = message});

			if (notify != null)
			{
				notify(this);
			}
		}
	}
}


text:
"""
@file
@brief Text normalization
"""
import unicodedata

def remove_diacritics(input_str):
    """
    remove diacritics

    @param      input_str       string to clean
    @return                     cleaned string

    Example::

        enguérand --> enguerand

    .. versionadded:: 1.0
    """
    nkfd_form = unicodedata.normalize('NFKD', input_str)
    only_ascii = nkfd_form.encode('ASCII', 'ignore')
    return only_ascii.decode("utf8")


text:
package uk.co.ben_gibson.git.link.test.Git;

import junit.framework.TestCase;
import uk.co.ben_gibson.git.link.Git.Branch;

public class BranchTest extends TestCase
{
    public void testCanBeCastToString()
    {
        Branch branch = new Branch("dev");

        assertSame("dev", branch.toString());
    }

    public void testCanCreateMasterBranch()
    {
        Branch branch = Branch.master();

        assertSame("master", branch.toString());
    }
}


text:
<?php

namespace Plugin\GiftWrapping\Service;

use Eccube\Application;

class GiftWrappingService
{
    /** @var \Eccube\Application */
    public $app;

    public function __construct(Application $app)
    {
        $this->app = $app;
    }

}


text:
const { Command } = require("klasa");

module.exports = class extends Command {
    constructor(...args) {
        super(...args, {
            name: "coin",
            enabled: true,
            runIn: ["text"],
            description: "Flip a coin!",
            usage: "<heads|tails> <bet:intcheck{1,}>", usageDelim: " "
        });

        this.humanUse = "<heads|tails> <bet>";
    }

    async run(msg, [choice=choice.toLowerCase(), bet]) {
        var data = this.client.dataManager("select", msg.author.id, "users");
        if (!data) { return msg.sendLocale("DATACHECK_NOACCOUNT"); }
        if (data.credits < bet) { return msg.sendLocale("DATACHECK_LACKCREDIT"); }

        let y = Math.random() > .5 ? "Heads": "Tails";

        if (y.toLowerCase() === choice) {
            this.client.dataManager("update", [`credits=${data.credits + (bet * 2)}`, msg.author.id], "users");
            return msg.sendLocale("COIN_SUCCESS", [msg, y, bet]);
        }

        this.client.dataManager("update", [`credits=${data.credits - bet}`, msg.author.id], "users");
        msg.sendLocale("COIN_LOSS", [msg, y, bet]);
    }
};


text:
try:
    import simplejson
    JSONDecodeError = simplejson.scanner.JSONDecodeError
except ImportError:
    JSONDecodeError = ValueError
import iso8601
import urllib

from keystoneauth1 import adapter

from openstack import _log
from openstack import exceptions
from openstack import resource

# The _check_resource decorator is used on Proxy methods to ensure that
# the `actual` argument is in fact the type of the `expected` argument.
# It does so under two cases:
# 1. When strict=False, if and only if `actual` is a Resource instance,
#    it is checked to see that it's an instance of the `expected` class.
#    This allows `actual` to be other types, such as strings, when it makes
#    sense to accept a raw id value.
# 2. When strict=True, `actual` must be an instance of the `expected` class.
def _check_resource(strict=False):
    def wrap(method):
        def check(self, expected, actual=None, *args, **kwargs):
            if (strict and actual is not None and not
               isinstance(actual, resource.Resource)):
                raise ValueError("A %s must be passed" % expected.__name__)
            elif (isinstance(actual, resource.Resource) and not
                  isinstance(actual, expected)):
                raise ValueError("Expected %s but received %s" % (
                                 expected.__name__, actual.__class__.__name__))

            return method(self, expected, actual, *args, **kwargs)
        return check
    return wrap

class Proxy(adapter.Adapter):
    """Represents a service."""

    retriable_status_codes = None
    """HTTP status codes that should be retried by default.

    The number of retries is defined by the configuration in parameters called
    ``<service-type>_status_code_retries``.
    """

    def __init__(
            self,
            session,
            statsd_client=None, statsd_prefix=None,
            prometheus_counter=None, prometheus_histogram=None,
            influxdb_config=None, influxdb_client=None,
            *args, **kwargs):
        # NOTE(dtantsur): keystoneauth defaults retriable_status_codes to None,
        # override it with a class-level value.
        kwargs.setdefault('retriable_status_codes',
                          self.retriable_status_codes)
        super(Proxy, self).__init__(session=session, *args, **kwargs)
        self._statsd_client = statsd_client
        self._statsd_prefix = statsd_prefix
        self._prometheus_counter = prometheus_counter
        self._prometheus_histogram = prometheus_histogram
        self._influxdb_client = influxdb_client
        self._influxdb_config = influxdb_config
        if self.service_type:
            log_name = 'openstack.{0}'.format(self.service_type)
        else:
            log_name = 'openstack'
        self.log = _log.setup_logging(log_name)

    def request(
            self, url, method, error_message=None,
            raise_exc=False, connect_retries=1,
            global_request_id=None, *args, **kwargs):
        if not global_request_id:
            conn = self._get_connection()
            if conn:
                # Per-request setting should take precedence
                global_request_id = conn._global_request_id
        try:
            response = super(Proxy, self).request(
                url, method,
                connect_retries=connect_retries, raise_exc=raise_exc,
                global_request_id=global_request_id,
                **kwargs)
            for h in response.history:
                self._report_stats(h)
            self._report_stats(response)
            return response
        except Exception as e:
            # If we want metrics to be generated we also need to generate some
            # in case of exceptions as well, so that timeouts and connection
            # problems (especially when called from ansible) are being
            # generated as well.
            self._report_stats(None, url, method, e)
            raise

    def _extract_name(self, url, service_type=None, project_id=None):
        '''Produce a key name to use in logging/metrics from the URL path.

        We want to be able to logic/metric sane general things, so we pull
        the url apart to generate names. The function returns a list because
        there are two different ways in which the elements want to be combined
        below (one for logging, one for statsd)

        Some examples are likely useful:

        /servers -> ['servers']
        /servers/{id} -> ['server']
        /servers/{id}/os-security-groups -> ['server', 'os-security-groups']
        /v2.0/networks.json -> ['networks']
        '''

        url_path = urllib.parse.urlparse(url).path.strip()
        # Remove / from the beginning to keep the list indexes of interesting
        # things consistent
        if url_path.startswith('/'):
            url_path = url_path[1:]

        # Special case for neutron, which puts .json on the end of urls
        if url_path.endswith('.json'):
            url_path = url_path[:-len('.json')]

        # Split url into parts and exclude potential project_id in some urls
        url_parts = [
            x for x in url_path.split('/') if (
                x != project_id
                and (
                    not project_id
                    or (project_id and x != 'AUTH_' + project_id)
                ))
        ]
        if url_parts[-1] == 'detail':
            # Special case detail calls
            # GET /servers/detail
            # returns ['servers', 'detail']
            name_parts = url_parts[-2:]
        else:
            # Strip leading version piece so that
            # GET /v2.0/networks
            # returns ['networks']
            if (url_parts[0]
                    and url_parts[0][0] == 'v'
                    and url_parts[0][1] and url_parts[0][1].isdigit()):
                url_parts = url_parts[1:]
            name_parts = self._extract_name_consume_url_parts(url_parts)

        # Keystone Token fetching is a special case, so we name it "tokens"
        # NOTE(gtema): there is no metric triggered for regular authorization
        # with openstack.connect(), since it bypassed SDK and goes directly to
        # keystoneauth1. If you need to measure performance of the token
        # fetching - trigger a separate call.
        if url_path.endswith('tokens'):
            name_parts = ['tokens']

        if not name_parts:
            name_parts = ['discovery']

        # Strip out anything that's empty or None
        return [part for part in name_parts if part]

    def _extract_name_consume_url_parts(self, url_parts):
        """Pull out every other URL portion - so that
        GET /servers/{id}/os-security-groups
        returns ['server', 'os-security-groups']

        """
        name_parts = []
        for idx in range(0, len(url_parts)):
            if not idx % 2 and url_parts[idx]:
                # If we are on first segment and it end with 's' stip this 's'
                # to differentiate LIST and GET_BY_ID
                if (len(url_parts) > idx + 1
                        and url_parts[idx][-1] == 's'
                        and url_parts[idx][-2:] != 'is'):
                    name_parts.append(url_parts[idx][:-1])
                else:
                    name_parts.append(url_parts[idx])

        return name_parts

    def _report_stats(self, response, url=None, method=None, exc=None):
        if self._statsd_client:
            self._report_stats_statsd(response, url, method, exc)
        if self._prometheus_counter and self._prometheus_histogram:
            self._report_stats_prometheus(response, url, method, exc)
        if self._influxdb_client:
            self._report_stats_influxdb(response, url, method, exc)

    def _report_stats_statsd(self, response, url=None, method=None, exc=None):
        if response is not None and not url:
            url = response.request.url
        if response is not None and not method:
            method = response.request.method
        name_parts = self._extract_name(url,
                                        self.service_type,
                                        self.session.get_project_id())
        key = '.'.join(
            [self._statsd_prefix, self.service_type, method]
            + name_parts)
        if response is not None:
            duration = int(response.elapsed.microseconds / 1000)
            self._statsd_client.timing(key, duration)
            self._statsd_client.incr(key)
        elif exc is not None:
            self._statsd_client.incr('%s.failed' % key)

    def _report_stats_prometheus(self, response, url=None, method=None,
                                 exc=None):
        if response is not None and not url:
            url = response.request.url
        if response is not None and not method:
            method = response.request.method
        if response is not None:
            labels = dict(
                method=method,
                endpoint=url,
                service_type=self.service_type,
                status_code=response.status_code,
            )
            self._prometheus_counter.labels(**labels).inc()
            self._prometheus_histogram.labels(**labels).observe(
                response.elapsed.microseconds / 1000)

    def _report_stats_influxdb(self, response, url=None, method=None,
                               exc=None):
        # NOTE(gtema): status_code is saved both as tag and field to give
        # ability showing it as a value and not only as a legend.
        # However Influx is not ok with having same name in tags and fields,
        # therefore use different names.
        if response is not None and not url:
            url = response.request.url
        if response is not None and not method:
            method = response.request.method
        tags = dict(
            method=method,
            name='_'.join(self._extract_name(
                url, self.service_type,
                self.session.get_project_id()))
        )
        fields = dict(
            attempted=1
        )
        if response is not None:
            fields['duration'] = int(response.elapsed.microseconds / 1000)
            tags['status_code'] = str(response.status_code)
            # Note(gtema): emit also status_code as a value (counter)
            fields[str(response.status_code)] = 1
            fields['%s.%s' % (method, response.status_code)] = 1
            # Note(gtema): status_code field itself is also very helpful on the
            # graphs to show what was the code, instead of counting its
            # occurences
            fields['status_code_val'] = response.status_code
        elif exc:
            fields['failed'] = 1
        if 'additional_metric_tags' in self._influxdb_config:
            tags.update(self._influxdb_config['additional_metric_tags'])
        measurement = self._influxdb_config.get(
            'measurement', 'openstack_api') \
            if self._influxdb_config else 'openstack_api'
        # Note(gtema) append service name into the measurement name
        measurement = '%s.%s' % (measurement, self.service_type)
        data = [dict(
            measurement=measurement,
            tags=tags,
            fields=fields
        )]
        try:
            self._influxdb_client.write_points(data)
        except Exception:
            self.log.exception('Error writing statistics to InfluxDB')

    def _version_matches(self, version):
        api_version = self.get_api_major_version()
        if api_version:
            return api_version[0] == version
        return False

    def _get_connection(self):
        """Get the Connection object associated with this Proxy.

        When the Session is created, a reference to the Connection is attached
        to the ``_sdk_connection`` attribute. We also add a reference to it
        directly on ourselves. Use one of them.
        """
        return getattr(
            self, '_connection', getattr(
                self.session, '_sdk_connection', None))

    def _get_resource(self, resource_type, value, **attrs):
        """Get a resource object to work on

        :param resource_type: The type of resource to operate on. This should
                              be a subclass of
                              :class:`~openstack.resource.Resource` with a
                              ``from_id`` method.
        :param value: The ID of a resource or an object of ``resource_type``
                      class if using an existing instance, or ``munch.Munch``,
                      or None to create a new instance.
        :param path_args: A dict containing arguments for forming the request
                          URL, if needed.
        """
        conn = self._get_connection()
        if value is None:
            # Create a bare resource
            res = resource_type.new(connection=conn, **attrs)
        elif (isinstance(value, dict)
              and not isinstance(value, resource.Resource)):
            res = resource_type._from_munch(
                value, connection=conn)
            res._update(**attrs)
        elif not isinstance(value, resource_type):
            # Create from an ID
            res = resource_type.new(
                id=value, connection=conn, **attrs)
        else:
            # An existing resource instance
            res = value
            res._update(**attrs)

        return res

    def _get_uri_attribute(self, child, parent, name):
        """Get a value to be associated with a URI attribute

        `child` will not be None here as it's a required argument
        on the proxy method. `parent` is allowed to be None if `child`
        is an actual resource, but when an ID is given for the child
        one must also be provided for the parent. An example of this
        is that a parent is a Server and a child is a ServerInterface.
        """
        if parent is None:
            value = getattr(child, name)
        else:
            value = resource.Resource._get_id(parent)
        return value

    def _find(self, resource_type, name_or_id, ignore_missing=True,
              **attrs):
        """Find a resource

        :param name_or_id: The name or ID of a resource to find.
        :param bool ignore_missing: When set to ``False``
                    :class:`~openstack.exceptions.ResourceNotFound` will be
                    raised when the resource does not exist.
                    When set to ``True``, None will be returned when
                    attempting to find a nonexistent resource.
        :param dict attrs: Attributes to be passed onto the
                           :meth:`~openstack.resource.Resource.find`
                           method, such as query parameters.

        :returns: An instance of ``resource_type`` or None
        """
        return resource_type.find(self, name_or_id,
                                  ignore_missing=ignore_missing,
                                  **attrs)

    @_check_resource(strict=False)
    def _delete(self, resource_type, value, ignore_missing=True, **attrs):
        """Delete a resource

        :param resource_type: The type of resource to delete. This should
                              be a :class:`~openstack.resource.Resource`
                              subclass with a ``from_id`` method.
        :param value: The value to delete. Can be either the ID of a
                      resource or a :class:`~openstack.resource.Resource`
                      subclass.
        :param bool ignore_missing: When set to ``False``
                    :class:`~openstack.exceptions.ResourceNotFound` will be
                    raised when the resource does not exist.
                    When set to ``True``, no exception will be set when
                    attempting to delete a nonexistent resource.
        :param dict attrs: Attributes to be passed onto the
                           :meth:`~openstack.resource.Resource.delete`
                           method, such as the ID of a parent resource.

        :returns: The result of the ``delete``
        :raises: ``ValueError`` if ``value`` is a
                 :class:`~openstack.resource.Resource` that doesn't match
                 the ``resource_type``.
                 :class:`~openstack.exceptions.ResourceNotFound` when
                 ignore_missing if ``False`` and a nonexistent resource
                 is attempted to be deleted.

        """
        res = self._get_resource(resource_type, value, **attrs)

        try:
            rv = res.delete(self)
        except exceptions.ResourceNotFound:
            if ignore_missing:
                return None
            raise

        return rv

    @_check_resource(strict=False)
    def _update(self, resource_type, value, base_path=None, **attrs):
        """Update a resource

        :param resource_type: The type of resource to update.
        :type resource_type: :class:`~openstack.resource.Resource`
        :param value: The resource to update. This must either be a
                      :class:`~openstack.resource.Resource` or an id
                      that corresponds to a resource.
        :param str base_path: Base part of the URI for updating resources, if
                              different from
                              :data:`~openstack.resource.Resource.base_path`.
        :param dict attrs: Attributes to be passed onto the
                           :meth:`~openstack.resource.Resource.update`
                           method to be updated. These should correspond
                           to either :class:`~openstack.resource.Body`
                           or :class:`~openstack.resource.Header`
                           values on this resource.

        :returns: The result of the ``update``
        :rtype: :class:`~openstack.resource.Resource`
        """
        res = self._get_resource(resource_type, value, **attrs)
        return res.commit(self, base_path=base_path)

    def _create(self, resource_type, base_path=None, **attrs):
        """Create a resource from attributes

        :param resource_type: The type of resource to create.
        :type resource_type: :class:`~openstack.resource.Resource`
        :param str base_path: Base part of the URI for creating resources, if
                              different from
                              :data:`~openstack.resource.Resource.base_path`.
        :param path_args: A dict containing arguments for forming the request
                          URL, if needed.
        :param dict attrs: Attributes to be passed onto the
                           :meth:`~openstack.resource.Resource.create`
                           method to be created. These should correspond
                           to either :class:`~openstack.resource.Body`
                           or :class:`~openstack.resource.Header`
                           values on this resource.

        :returns: The result of the ``create``
        :rtype: :class:`~openstack.resource.Resource`
        """
        conn = self._get_connection()
        res = resource_type.new(connection=conn, **attrs)
        return res.create(self, base_path=base_path)

    def _bulk_create(self, resource_type, data, base_path=None):
        """Create a resource from attributes

        :param resource_type: The type of resource to create.
        :type resource_type: :class:`~openstack.resource.Resource`
        :param list data: List of attributes dicts to be passed onto the
                          :meth:`~openstack.resource.Resource.create`
                          method to be created. These should correspond
                          to either :class:`~openstack.resource.Body`
                          or :class:`~openstack.resource.Header`
                          values on this resource.
        :param str base_path: Base part of the URI for creating resources, if
                              different from
                              :data:`~openstack.resource.Resource.base_path`.

        :returns: A generator of Resource objects.
        :rtype: :class:`~openstack.resource.Resource`
        """
        return resource_type.bulk_create(self, data, base_path=base_path)

    @_check_resource(strict=False)
    def _get(self, resource_type, value=None, requires_id=True,
             base_path=None, **attrs):
        """Fetch a resource

        :param resource_type: The type of resource to get.
        :type resource_type: :class:`~openstack.resource.Resource`
        :param value: The value to get. Can be either the ID of a
                      resource or a :class:`~openstack.resource.Resource`
                      subclass.
        :param str base_path: Base part of the URI for fetching resources, if
                              different from
                              :data:`~openstack.resource.Resource.base_path`.
        :param dict attrs: Attributes to be passed onto the
                           :meth:`~openstack.resource.Resource.get`
                           method. These should correspond
                           to either :class:`~openstack.resource.Body`
                           or :class:`~openstack.resource.Header`
                           values on this resource.

        :returns: The result of the ``fetch``
        :rtype: :class:`~openstack.resource.Resource`
        """
        res = self._get_resource(resource_type, value, **attrs)

        return res.fetch(
            self, requires_id=requires_id, base_path=base_path,
            error_message="No {resource_type} found for {value}".format(
                resource_type=resource_type.__name__, value=value))

    def _list(self, resource_type, value=None,
              paginated=True, base_path=None, **attrs):
        """List a resource

        :param resource_type: The type of resource to delete. This should
                              be a :class:`~openstack.resource.Resource`
                              subclass with a ``from_id`` method.
        :param value: The resource to list. It can be the ID of a resource, or
                      a :class:`~openstack.resource.Resource` object. When set
                      to None, a new bare resource is created.
        :param bool paginated: When set to ``False``, expect all of the data
                               to be returned in one response. When set to
                               ``True``, the resource supports data being
                               returned across multiple pages.
        :param str base_path: Base part of the URI for listing resources, if
                              different from
                              :data:`~openstack.resource.Resource.base_path`.
        :param dict attrs: Attributes to be passed onto the
            :meth:`~openstack.resource.Resource.list` method. These should
            correspond to either :class:`~openstack.resource.URI` values
            or appear in :data:`~openstack.resource.Resource._query_mapping`.

        :returns: A generator of Resource objects.
        :raises: ``ValueError`` if ``value`` is a
                 :class:`~openstack.resource.Resource` that doesn't match
                 the ``resource_type``.
        """
        return resource_type.list(
            self, paginated=paginated,
            base_path=base_path,
            **attrs)

    def _head(self, resource_type, value=None, base_path=None, **attrs):
        """Retrieve a resource's header

        :param resource_type: The type of resource to retrieve.
        :type resource_type: :class:`~openstack.resource.Resource`
        :param value: The value of a specific resource to retreive headers
                      for. Can be either the ID of a resource,
                      a :class:`~openstack.resource.Resource` subclass,
                      or ``None``.
        :param str base_path: Base part of the URI for heading resources, if
                              different from
                              :data:`~openstack.resource.Resource.base_path`.
        :param dict attrs: Attributes to be passed onto the
                           :meth:`~openstack.resource.Resource.head` method.
                           These should correspond to
                           :class:`~openstack.resource.URI` values.

        :returns: The result of the ``head`` call
        :rtype: :class:`~openstack.resource.Resource`
        """
        res = self._get_resource(resource_type, value, **attrs)
        return res.head(self, base_path=base_path)

    def _get_cleanup_dependencies(self):
        return None

    def _service_cleanup(self, dry_run=True, client_status_queue=None,
                         identified_resources=None, filters=None,
                         resource_evaluation_fn=None):
        return None

    def _service_cleanup_del_res(self, del_fn, obj, dry_run=True,
                                 client_status_queue=None,
                                 identified_resources=None,
                                 filters=None,
                                 resource_evaluation_fn=None):
        need_delete = False
        try:
            if (
                resource_evaluation_fn
                and callable(resource_evaluation_fn)
            ):
                # Ask a user-provided evaluation function if we need to delete
                # the resource
                need_del = resource_evaluation_fn(obj, filters,
                                                  identified_resources)
                if isinstance(need_del, bool):
                    # Just double check function returned bool
                    need_delete = need_del
            else:
                need_delete = \
                    self._service_cleanup_resource_filters_evaluation(
                        obj,
                        filters=filters)

            if need_delete:
                if client_status_queue:
                    # Put into queue for client status info
                    client_status_queue.put(obj)
                if identified_resources is not None:
                    # Put into internal dict shared between threads so that
                    # other services might know which other resources were
                    # identified
                    identified_resources[obj.id] = obj
                if not dry_run:
                    del_fn(obj)
        except Exception as e:
            self.log.exception('Cannot delete resource %s: %s', obj, str(e))
        return need_delete

    def _service_cleanup_resource_filters_evaluation(self, obj, filters=None):
        part_cond = []
        if filters is not None and isinstance(filters, dict):
            for k, v in filters.items():
                try:
                    res_val = None
                    if k == 'created_at' and hasattr(obj, 'created_at'):
                        res_val = getattr(obj, 'created_at')
                    if k == 'updated_at' and hasattr(obj, 'updated_at'):
                        res_val = getattr(obj, 'updated_at')
                    if res_val:
                        res_date = iso8601.parse_date(res_val)
                        cmp_date = iso8601.parse_date(v)
                        if res_date and cmp_date and res_date <= cmp_date:
                            part_cond.append(True)
                        else:
                            part_cond.append(False)
                    else:
                        # There are filters set, but we can't get required
                        # attribute, so skip the resource
                        self.log.debug('Requested cleanup attribute %s is not '
                                       'available on the resource' % k)
                        part_cond.append(False)
                except Exception:
                    self.log.exception('Error during condition evaluation')
        if all(part_cond):
            return True
        else:
            return False

def _json_response(response, result_key=None, error_message=None):
    """Temporary method to use to bridge from ShadeAdapter to SDK calls."""
    exceptions.raise_from_response(response, error_message=error_message)

    if not response.content:
        # This doesn't have any content
        return response

    # Some REST calls do not return json content. Don't decode it.
    if 'application/json' not in response.headers.get('Content-Type'):
        return response

    try:
        result_json = response.json()
    except JSONDecodeError:
        return response
    return result_json

class _ShadeAdapter(Proxy):
    """Wrapper for shade methods that expect json unpacking."""

    def request(self, url, method, error_message=None, **kwargs):
        response = super(_ShadeAdapter, self).request(url, method, **kwargs)
        return _json_response(response, error_message=error_message)