text:
#ifndef DATAPATH_H
#define DATAPATH_H 1

#include <asm/page.h>
#include <linux/kernel.h>
#include <linux/mutex.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/u64_stats_sync.h>

#include "flow.h"
#include "vport.h"

#define DP_MAX_PORTS           USHRT_MAX
#define DP_VPORT_HASH_BUCKETS  1024

#define SAMPLE_ACTION_DEPTH 3

/**
 * struct dp_stats_percpu - per-cpu packet processing statistics for a given
 * datapath.
 * @n_hit: Number of received packets for which a matching flow was found in
 * the flow table.
 * @n_miss: Number of received packets that had no matching flow in the flow
 * table.  The sum of @n_hit and @n_miss is the number of packets that have
 * been received by the datapath.
 * @n_lost: Number of received packets that had no matching flow in the flow
 * table that could not be sent to userspace (normally due to an overflow in
 * one of the datapath's queues).
 */
struct dp_stats_percpu {
	u64 n_hit;
	u64 n_missed;
	u64 n_lost;
	struct u64_stats_sync sync;
};

/**
 * struct datapath - datapath for flow-based packet switching
 * @rcu: RCU callback head for deferred destruction.
 * @list_node: Element in global 'dps' list.
 * @table: Current flow table.  Protected by ovs_mutex and RCU.
 * @ports: Hash table for ports.  %OVSP_LOCAL port always exists.  Protected by
 * ovs_mutex and RCU.
 * @stats_percpu: Per-CPU datapath statistics.
 * @net: Reference to net namespace.
 *
 * Context: See the comment on locking at the top of datapath.c for additional
 * locking information.
 */
struct datapath {
	struct rcu_head rcu;
	struct list_head list_node;

	/* Flow table. */
	struct flow_table __rcu *table;

	/* Switch ports. */
	struct hlist_head *ports;

	/* Stats. */
	struct dp_stats_percpu __percpu *stats_percpu;

#ifdef CONFIG_NET_NS
	/* Network namespace ref. */
	struct net *net;
#endif
};

/**
 * struct ovs_skb_cb - OVS data in skb CB
 * @flow: The flow associated with this packet.  May be %NULL if no flow.
 */
struct ovs_skb_cb {
	struct sw_flow		*flow;
};
#define OVS_CB(skb) ((struct ovs_skb_cb *)(skb)->cb)

/**
 * struct dp_upcall - metadata to include with a packet to send to userspace
 * @cmd: One of %OVS_PACKET_CMD_*.
 * @key: Becomes %OVS_PACKET_ATTR_KEY.  Must be nonnull.
 * @userdata: If nonnull, its variable-length value is passed to userspace as
 * %OVS_PACKET_ATTR_USERDATA.
 * @pid: Netlink PID to which packet should be sent.  If @pid is 0 then no
 * packet is sent and the packet is accounted in the datapath's @n_lost
 * counter.
 */
struct dp_upcall_info {
	u8 cmd;
	const struct sw_flow_key *key;
	const struct nlattr *userdata;
	u32 portid;
};

/**
 * struct ovs_net - Per net-namespace data for ovs.
 * @dps: List of datapaths to enable dumping them all out.
 * Protected by genl_mutex.
 */
struct ovs_net {
	struct list_head dps;
	struct work_struct dp_notify_work;
};

extern int ovs_net_id;
void ovs_lock(void);
void ovs_unlock(void);

#ifdef CONFIG_LOCKDEP
int lockdep_ovsl_is_held(void);
#else
#define lockdep_ovsl_is_held()	1
#endif

#define ASSERT_OVSL()		WARN_ON(unlikely(!lockdep_ovsl_is_held()))
#define ovsl_dereference(p)					\
	rcu_dereference_protected(p, lockdep_ovsl_is_held())

static inline struct net *ovs_dp_get_net(struct datapath *dp)
{
	return read_pnet(&dp->net);
}

static inline void ovs_dp_set_net(struct datapath *dp, struct net *net)
{
	write_pnet(&dp->net, net);
}

struct vport *ovs_lookup_vport(const struct datapath *dp, u16 port_no);

static inline struct vport *ovs_vport_rcu(const struct datapath *dp, int port_no)
{
	WARN_ON_ONCE(!rcu_read_lock_held());
	return ovs_lookup_vport(dp, port_no);
}

static inline struct vport *ovs_vport_ovsl_rcu(const struct datapath *dp, int port_no)
{
	WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_ovsl_is_held());
	return ovs_lookup_vport(dp, port_no);
}

static inline struct vport *ovs_vport_ovsl(const struct datapath *dp, int port_no)
{
	ASSERT_OVSL();
	return ovs_lookup_vport(dp, port_no);
}

extern struct notifier_block ovs_dp_device_notifier;
extern struct genl_multicast_group ovs_dp_vport_multicast_group;

void ovs_dp_process_received_packet(struct vport *, struct sk_buff *);
void ovs_dp_detach_port(struct vport *);
int ovs_dp_upcall(struct datapath *, struct sk_buff *,
		  const struct dp_upcall_info *);

const char *ovs_dp_name(const struct datapath *dp);
struct sk_buff *ovs_vport_cmd_build_info(struct vport *, u32 pid, u32 seq,
					 u8 cmd);

int ovs_execute_actions(struct datapath *dp, struct sk_buff *skb);
void ovs_dp_notify_wq(struct work_struct *work);
#endif /* datapath.h */


text:
package pkg

import (
	"log"
	"regexp"
)

const c1 = `[`
const c2 = `abc`

var re1 = regexp.MustCompile(`ab\yef`) // MATCH /error parsing regexp/
var re2 = regexp.MustCompile(c1)       // MATCH /error parsing regexp/
var re3 = regexp.MustCompile(c2)

func fn() {
	_, err := regexp.Compile(`foo(`) // MATCH /error parsing regexp/
	if err != nil {
		panic(err)
	}
	if re2.MatchString("foo(") {
		log.Println("of course 'foo(' matches 'foo('")
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.utabitwallet.tools.manager;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import com.utabitwallet.UtabitWalletApp;
import com.utabitwallet.presenter.entities.CurrencyEntity;
import com.utabitwallet.tools.adapter.CurrencyListAdapter;
import com.utabitwallet.tools.adapter.MiddleViewAdapter;
import com.utabitwallet.tools.animation.BRAnimator;
import com.utabitwallet.tools.util.JsonParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Observable;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

public class CurrencyManager extends Observable {
    private static final String TAG = CurrencyManager.class.getName();

    private static CurrencyManager instance;
    private Timer timer;
    private long BALANCE = 0;
    private TimerTask timerTask;

    private Handler handler;
    //    public static boolean separatorNeedsToBeShown = false;
    private final CurrencyListAdapter currencyListAdapter;
    private static Activity ctx;

    private CurrencyManager() {
        currencyListAdapter = new CurrencyListAdapter(ctx);
        handler = new Handler();
    }

    public static CurrencyManager getInstance(Activity context) {
        ctx = context;

        if (instance == null) {
            instance = new CurrencyManager();
        }
        return instance;
    }

    public void setBalance(long balance) {
        BALANCE = balance;
        setChanged();
        notifyObservers();
    }

    public long getBALANCE() {
        return BALANCE;
    }

    private Set<CurrencyEntity> getCurrencies(Activity context) {
        Set<CurrencyEntity> set = new LinkedHashSet<>();
        if (((UtabitWalletApp) ctx.getApplication()).hasInternetAccess()) {
            try {
                JSONArray arr = JsonParser.getJSonArray(context);
                JsonParser.updateFeePerKb(context);
//                Log.e(TAG, "JSONArray arr.length(): " + arr.length());
                if (arr != null) {
                    int length = arr.length();
                    for (int i = 1; i < length; i++) {
                        CurrencyEntity tmp = new CurrencyEntity();
                        try {
                            JSONObject tmpObj = (JSONObject) arr.get(i);
                            tmp.name = tmpObj.getString("name");
                            tmp.code = tmpObj.getString("code");
                            tmp.codeAndName = tmp.code + " - " + tmp.name;
                            tmp.rate = (float) tmpObj.getDouble("rate");
                            String selectedISO = SharedPreferencesManager.getIso(context);
//                        Log.e(TAG,"selectedISO: " + selectedISO);
                            if (tmp.code.equalsIgnoreCase(selectedISO)) {
//                            Log.e(TAG, "theIso : " + theIso);
//                                Log.e(TAG, "Putting the shit in the shared preffs");
                                SharedPreferencesManager.putIso(context, tmp.code);
                                SharedPreferencesManager.putCurrencyListPosition(context, i - 1);
//                            Log.e(TAG,"position set: " + (i - 1));
                                SharedPreferencesManager.putRate(context, tmp.rate);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        set.add(tmp);
                    }
                } else {
                    Log.e(TAG, "getCurrencies: failed to get currencies, response string: " + arr);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List tempList = new ArrayList<>(set);
        Collections.reverse(tempList);
        return new LinkedHashSet<>(set);
    }

    public class GetCurrenciesTask extends AsyncTask {
        Set<CurrencyEntity> tmp;

        @Override
        protected Object doInBackground(Object[] params) {
            tmp = getCurrencies(ctx);
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            if (tmp.size() > 0) {
                currencyListAdapter.clear();
                currencyListAdapter.addAll(tmp);
                currencyListAdapter.notifyDataSetChanged();
                SharedPreferencesManager.putExchangeRates(ctx, tmp);
                if (BRAnimator.level <= 2)
                    MiddleViewAdapter.resetMiddleView(ctx, null);
            } else {
                currencyListAdapter.clear();
                Set<CurrencyEntity> currencyEntitySet = SharedPreferencesManager.getExchangeRates(ctx);
                if (currencyEntitySet == null || currencyEntitySet.isEmpty()) return;
                currencyListAdapter.addAll(currencyEntitySet);
                currencyListAdapter.notifyDataSetChanged();
                Log.e(TAG, "Adapter Not Changed, data is empty");
            }
        }
    }

    public CurrencyListAdapter getCurrencyAdapterIfReady() {
//        new GetCurrenciesTask().execute();
        return currencyListAdapter;
    }

    private void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {
                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {
                        new GetCurrenciesTask().execute();
                    }
                });
            }
        };
    }

    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, 0, 60000); //
    }

    public void stopTimerTask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

}


text:
```python
scala_binary(
    name,
    srcs,
    deps,
    runtime_deps,
    data,
    main_class,
    resources,
    resource_strip_prefix,
    scalacopts,
    jvm_flags,
    scalac_jvm_flags,
    javac_jvm_flags,
    unused_dependency_checker_mode
)
```

`scala_binary` generates a Scala executable. It may depend on `scala_library`, `scala_macro_library`
and `java_library` rules.

A `scala_binary` requires a `main_class` attribute.

  <colgroup>
    <col class="col-param" />
    <col class="param-description" />
  </colgroup>

      Attributes

      name

Name, required

A unique name for this target

      srcs

List of labels, required

List of Scala .scala source files used to build the
        binary

      deps

List of labels, optional

List of other libraries to linked to this binary target.
        These must be jvm targets (scala_library, java_library, java_import, etc...)

      runtime_deps

List of labels, optional

List of other libraries to put on the classpath only at runtime. This is rarely needed in Scala.
        These must be jvm targets (scala_library, java_library, java_import, etc...)

      data

List of labels, optional

List of files needed by this rule at runtime.

      main_class

String, required

Name of class with main() method to use as an entry point

          The value of this attribute is a class name, not a source file. The
          class must be available at runtime: it may be compiled by this rule
          (from srcs) or provided by direct or transitive
          dependencies (through deps). If the class is unavailable,
          the binary will fail at runtime; there is no build-time check.

      resources

List of labels; optional

A list of data files to be included in the JAR.

      resource_strip_prefix

String; optional

          The path prefix to strip from Java resources. If specified,
          this path prefix is stripped from every file in the `resources` attribute.
          It is an error for a resource file not to be under this directory.

      scalacopts

List of strings; optional

          Extra compiler options for this binary to be passed to scalac. Subject to
          Make variable
          substitution and
          Bourne shell tokenization.

      jvm_flags

List of strings; optional

          List of JVM flags to be passed to the executing JVM. Subject to
          Make variable
          substitution and
          Bourne shell tokenization.

      scalac_jvm_flags

List of strings; optional

          List of JVM flags to be passed to scalac after the
          scalacopts. Subject to
          Make variable
          substitution and
          Bourne shell tokenization.

      javac_jvm_flags

List of strings; optional

          List of JVM flags to be passed to javac after the
          javacopts. Subject to
          Make variable
          substitution and
          Bourne shell tokenization.

      unused_dependency_checker_mode

String; optional

          Enable unused dependency checking (see Unused dependency checking).
          Possible values are: off, warn and error.


text:
import logging

from flask import render_template, request, session, url_for
from flask_wtf.csrf import CSRFError
from requests.exceptions import ConnectionError
from structlog import wrap_logger
from werkzeug.utils import redirect

from frontstage import app
from frontstage.common.session import Session
from frontstage.exceptions.exceptions import (
    ApiError,
    IncorrectAccountAccessError,
    InvalidEqPayLoad,
    JWTValidationError,
)

logger = wrap_logger(logging.getLogger(__name__))

@app.errorhandler(400)
def client_error(error):
    logger.info("Client error", url=request.url, status_code=error.code)
    return render_template("errors/400-error.html"), 400

@app.errorhandler(404)
def not_found_error(error):
    logger.info("Not found error", url=request.url, status_code=error.code)
    return render_template("errors/404-error.html"), 404

@app.errorhandler(CSRFError)
def handle_csrf_error(error):
    logger.warning("CSRF token has expired", error_message=error.description, status_code=error.code)

    session_key = request.cookies.get("authorization")
    session_handler = Session.from_session_key(session_key)
    encoded_jwt = session_handler.get_encoded_jwt()
    if not encoded_jwt:
        return render_template("errors/400-error.html"), 400
    else:
        session["next"] = request.url
        return redirect(url_for("sign_in_bp.logout", csrf_error=True))

@app.errorhandler(ApiError)
def api_error(error):
    logger.error(
        error.message or "Api failed to retrieve required data",
        url=request.url,
        status_code=500,
        api_url=error.url,
        api_status_code=error.status_code,
        **error.kwargs
    )
    return render_template("errors/500-error.html"), 500

@app.errorhandler(ConnectionError)
def connection_error(error):
    logger.error("Failed to connect to external service", url=request.url, status_code=500, api_url=error.request.url)
    return render_template("errors/500-error.html"), 500

@app.errorhandler(JWTValidationError)
def jwt_validation_error(error):
    logger.error("JWT validation error", url=request.url, status_code=403)
    return render_template("errors/403-error.html"), 403

@app.errorhandler(Exception)
def server_error(error):
    logger.error("Generic exception generated", exc_info=error, url=request.url, status_code=500)
    return render_template("errors/500-error.html"), getattr(error, "code", 500)

@app.errorhandler(InvalidEqPayLoad)
def eq_error(error):
    logger.error("Failed to generate EQ URL", error=error.message, url=request.url, status_code=500)
    return render_template("errors/500-error.html"), 500

@app.errorhandler(IncorrectAccountAccessError)
def secure_message_forbidden_error(error):
    logger.info(
        "Attempt to access secure message without correct session permission",
        url=request.url,
        message=error.message,
        thread_id=error.thread,
    )
    return render_template("errors/403-incorrect-account-error.html")


text:
package utility.delaunay;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

import utility.geom.Point;
import utility.geom.Rectangle;

public class Voronoi {

	private SiteList sites;
	private Dictionary<Point, Site> sitesIndexedByLocation;
	private List<Triangle> triangles;
	private List<Edge> edges;
	private Rectangle plotBounds;

	public Voronoi(List<Point> points, List<Integer> colors, Rectangle plotBounds) {
		sites = new SiteList();
		sitesIndexedByLocation = new Hashtable<Point, Site>();
		addSites(points, colors);
		this.plotBounds = plotBounds;
		triangles = new ArrayList<Triangle>();
		edges = new ArrayList<Edge>();
		fortunesAlgorithm();
	}

	private void addSites(List<Point> points, List<Integer> colors) {
		int length = points.size();
		for (int i = 0; i < length; ++i) {
			addSite(points.get(i), colors != null ? colors.get(i) : 0, i);
		}
	}

	private void addSite(Point p, int color, int index) {
		double weight = Math.random() * 100;
		Site site = Site.create(p, index, weight, color);
		sites.add(site);
		sitesIndexedByLocation.put(p, site);
	}

	public static int compareByYThenX(Site s1, Site s2) {
		if (s1.getY() < s2.getY())
			return -1;
		if (s1.getY() > s2.getY())
			return 1;
		if (s1.getX() < s2.getX())
			return -1;
		if (s1.getX() > s2.getX())
			return 1;
		return 0;
	}

	public static int compareByYThenX(Site s1, Point s2) {
		if (s1.getY() < s2.getY())
			return -1;
		if (s1.getY() > s2.getY())
			return 1;
		if (s1.getX() < s2.getX())
			return -1;
		if (s1.getX() > s2.getX())
			return 1;
		return 0;
	}

	private void fortunesAlgorithm() {
		Site newSite, bottomSite, topSite, tempSite;
		Vertex v, vertex;
		Point newintstar = null;
		LR leftRight;
		Halfedge lbnd, rbnd, llbnd, rrbnd, bisector;
		Edge edge;

		Rectangle dataBounds = sites.getSitesBounds();

		int sqrt_nsites = (int) (Math.sqrt(sites.size() + 4));
		HalfedgePriorityQueue heap = new HalfedgePriorityQueue(dataBounds.getY(), dataBounds.getHeight(), sqrt_nsites);
		EdgeList edgeList = new EdgeList(dataBounds.getX(), dataBounds.getWidth(), sqrt_nsites);
		List<Halfedge> halfEdges = new ArrayList<Halfedge>();
		List<Vertex> vertices = new ArrayList<Vertex>();

		Site bottomMostSite = sites.next();
		newSite = sites.next();

		while (true) {
			if (heap.isEmpty() == false) {
				newintstar = heap.min();
			}

			if (newSite != null && (heap.isEmpty() || compareByYThenX(newSite, newintstar) < 0)) {
				/* new site is smallest */
				// trace("smallest: new site " + newSite);

				// Step 8:
				lbnd = edgeList.edgeListLeftNeighbor(newSite.getCoord());
				// trace("lbnd: " + lbnd);
				rbnd = lbnd.getEdgeListRightNeighbor(); // the Halfedge just to
														// the right
				// trace("rbnd: " + rbnd);
				bottomSite = rightRegion(lbnd, bottomMostSite); // this is the
																// same as
																// leftRegion(rbnd)
				// this Site determines the region containing the new site
				// trace("new Site is in region of existing site: " +
				// bottomSite);

				// Step 9:
				edge = Edge.createBisectingEdge(bottomSite, newSite);
				// trace("new edge: " + edge);
				edges.add(edge);

				bisector = Halfedge.create(edge, LR.LEFT);
				halfEdges.add(bisector);
				// inserting two Halfedges into edgeList constitutes Step 10:
				// insert bisector to the right of lbnd:
				edgeList.insert(lbnd, bisector);

				// first half of Step 11:
				if ((vertex = Vertex.intersect(lbnd, bisector)) != null) {
					vertices.add(vertex);
					heap.remove(lbnd);
					lbnd.setVertex(vertex);
					lbnd.setYstar(vertex.getY() + Point.distance(newSite.getCoord(), vertex.getCoord()));
					heap.insert(lbnd);
				}

				lbnd = bisector;
				bisector = Halfedge.create(edge, LR.RIGHT);
				halfEdges.add(bisector);
				// second Halfedge for Step 10:
				// insert bisector to the right of lbnd:
				edgeList.insert(lbnd, bisector);

				// second half of Step 11:
				if ((vertex = Vertex.intersect(bisector, rbnd)) != null) {
					vertices.add(vertex);
					bisector.setVertex(vertex);
					bisector.setYstar(vertex.getY() + Point.distance(newSite.getCoord(), vertex.getCoord()));
					heap.insert(bisector);
				}

				newSite = sites.next();
			} else if (heap.isEmpty() == false) {
				/* intersection is smallest */
				lbnd = heap.extractMin();
				llbnd = lbnd.getEdgeListLeftNeighbor();
				rbnd = lbnd.getEdgeListRightNeighbor();
				rrbnd = rbnd.getEdgeListRightNeighbor();
				bottomSite = leftRegion(lbnd, bottomMostSite);
				topSite = rightRegion(rbnd, bottomMostSite);
				// these three sites define a Delaunay triangle
				// (not actually using these for anything...)
				// _triangles.push(new Triangle(bottomSite, topSite,
				// rightRegion(lbnd)));

				v = lbnd.getVertex();
				v.setIndex();
				lbnd.getEdge().setVertex(lbnd.getLeftRight(), v);
				rbnd.getEdge().setVertex(rbnd.getLeftRight(), v);
				edgeList.remove(lbnd);
				heap.remove(rbnd);
				edgeList.remove(rbnd);
				leftRight = LR.LEFT;
				if (bottomSite.getY() > topSite.getY()) {
					tempSite = bottomSite;
					bottomSite = topSite;
					topSite = tempSite;
					leftRight = LR.RIGHT;
				}
				edge = Edge.createBisectingEdge(bottomSite, topSite);
				edges.add(edge);
				bisector = Halfedge.create(edge, leftRight);
				halfEdges.add(bisector);
				edgeList.insert(llbnd, bisector);
				edge.setVertex(LR.other(leftRight), v);
				if ((vertex = Vertex.intersect(llbnd, bisector)) != null) {
					vertices.add(vertex);
					heap.remove(llbnd);
					llbnd.setVertex(vertex);
					llbnd.setYstar(vertex.getY() + Point.distance(bottomSite.getCoord(), vertex.getCoord()));
					heap.insert(llbnd);
				}
				if ((vertex = Vertex.intersect(bisector, rrbnd)) != null) {
					vertices.add(vertex);
					bisector.setVertex(vertex);
					bisector.setYstar(vertex.getY() + Point.distance(bottomSite.getCoord(), vertex.getCoord()));
					heap.insert(bisector);
				}
			} else {
				break;
			}
		}

		// heap should be empty now
		heap.dispose();
		edgeList.dispose();

		halfEdges.forEach(he -> {
			he.reallyDispose();
		});
		halfEdges = new ArrayList<Halfedge>();

		// we need the vertices to clip the edges
		edges.forEach(e -> {
			e.clipVertices(plotBounds);
		});
		// but we don't actually ever use them again!
		vertices.forEach(ver -> {
			ver.dispose();
		});
		vertices = new ArrayList<Vertex>();
	}

	Site rightRegion(Halfedge he, Site bottomMostSite) {
		Edge edge = he.getEdge();
		if (edge == null) {
			return bottomMostSite;
		}
		return edge.site(LR.other(he.getLeftRight()));
	}

	Site leftRegion(Halfedge he, Site bottomMostSite) {
		Edge edge = he.getEdge();
		if (edge == null) {
			return bottomMostSite;
		}
		return edge.site(he.getLeftRight());
	}

	public List<Point> region(Point p)
	{
		Site site = sitesIndexedByLocation.get(p);
		if (site == null)
		{
			return new ArrayList<Point>();
		}
		return site.region(plotBounds);
	}

	public List<Edge> getEdges() {
		return edges;
	}

}


text:
module KoiReferenceCompiler

  class FalseLiteral < SyntaxNode
    def compile
      [ PUSH_BOOL, false ]
    end
  end

end


text:
package com.siyeh.ig.junit;

import com.intellij.psi.PsiClass;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.MoveClassFix;
import com.siyeh.ig.psiutils.TestUtils;
import org.jetbrains.annotations.NotNull;

public class TestCaseInProductCodeInspection extends BaseInspection {

  @Override
  protected InspectionGadgetsFix buildFix(Object... infos) {
    return new MoveClassFix();
  }

  @Override
  @NotNull
  public String getID() {
    return "JUnitTestCaseInProductSource";
  }

  @Override
  @NotNull
  protected String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message(
      "test.case.in.product.code.problem.descriptor");
  }

  @Override
  protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
    return true;
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new TestCaseInProductCodeVisitor();
  }

  private static class TestCaseInProductCodeVisitor extends BaseInspectionVisitor {

    @Override
    public void visitClass(@NotNull PsiClass aClass) {
      if (TestUtils.isInTestSourceContent(aClass) || !TestUtils.isJUnitTestClass(aClass)) {
        return;
      }
      registerClassError(aClass);
    }
  }
}


text:
namespace Crate.Core
{
    public class Constants
    {
        /// <summary>
        /// The file extension
        /// </summary>
        public const string FileExtension = "txt";
        public const string PairsFileName = "crate_pairs";
    }
}


text:
@interface ViewController ()
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation ViewController

@synthesize progressView = _progressView;
@synthesize largeProgressView = _largeProgressView;
@synthesize largestProgressView = _largestProgressView;
@synthesize linearProgressView = _linearProgressView;
@synthesize stepper = _stepper;
@synthesize progressLabel = _progressLabel;
@synthesize continuousSwitch = _continuousSwitch;
@synthesize timer = _timer;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.progressView = [[DACircularProgressView alloc] initWithFrame:CGRectMake(140.0f, 50.0f, 40.0f, 40.0f)];
    self.progressView.roundedCorners = YES;
    self.progressView.trackTintColor = [UIColor clearColor];
    [self.view addSubview:self.progressView];

    self.largeProgressView.roundedCorners = NO;
    [self.view addSubview:self.largeProgressView];

    self.largestProgressView.trackTintColor = [UIColor blackColor];
    self.largestProgressView.progressTintColor = [UIColor yellowColor];
    self.largestProgressView.thicknessRatio = 1.0f;
    self.largestProgressView.clockwiseProgress = NO;

    // Labeled progress views
    self.labeledProgressView = [[DALabeledCircularProgressView alloc] initWithFrame:CGRectMake(200.0f, 40.0f, 60.0f, 60.0f)];
    self.labeledProgressView.roundedCorners = YES;
    [self.view addSubview:self.labeledProgressView];

    self.labeledLargeProgressView.roundedCorners = NO;
    [self.view addSubview:self.labeledLargeProgressView];

    [self startAnimation];
}

- (void)progressChange
{
    NSArray *progressViews = @[self.linearProgressView,
                               self.progressView,
                               self.largeProgressView,
                               self.largestProgressView];
    for (DACircularProgressView *progressView in progressViews) {
        CGFloat progress = ![self.timer isValid] ? self.stepper.value / 10.0f : progressView.progress + 0.01f;
        [progressView setProgress:progress animated:YES];

        if (progressView.progress >= 1.0f && [self.timer isValid]) {
            [progressView setProgress:0.f animated:YES];
        }

        self.progressLabel.text = [NSString stringWithFormat:@"%.2f", progressView.progress];
    }

    // Labeled progress views
    NSArray *labeledProgressViews = @[self.labeledProgressView,
                                      self.labeledLargeProgressView];
    for (DALabeledCircularProgressView *labeledProgressView in labeledProgressViews) {
        CGFloat progress = ![self.timer isValid] ? self.stepper.value / 10.0f : labeledProgressView.progress + 0.01f;
        [labeledProgressView setProgress:progress animated:YES];

        if (labeledProgressView.progress >= 1.0f && [self.timer isValid]) {
            [labeledProgressView setProgress:0.f animated:YES];
        }

        labeledProgressView.progressLabel.text = [NSString stringWithFormat:@"%.2f", labeledProgressView.progress];
    }

}

- (void)startAnimation
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.03
                                                  target:self
                                                selector:@selector(progressChange)
                                                userInfo:nil
                                                 repeats:YES];
    self.continuousSwitch.on = YES;
}

- (void)stopAnimation
{
    [self.timer invalidate];
    self.timer = nil;
    self.continuousSwitch.on = NO;
}

- (IBAction)toggleAnimation:(id)sender
{
    if (self.continuousSwitch.on) {
        [self startAnimation];
    } else {
        [self stopAnimation];
    }
}

- (IBAction)toggleIndeterminate:(id)sender
{
    NSArray *progressViews = @[self.progressView,
                               self.largeProgressView,
                               self.largestProgressView];
    for (DACircularProgressView *progressView in progressViews) {
        progressView.indeterminate = self.indeterminateSwitch.on;
    }
}

- (IBAction)step:(id)sender
{
    [self stopAnimation];
    [self progressChange];
}

@end


text:
'use strict';

angular.module('observatoryApp', [
  'ngRoute',
  'pageScholarship',
  'pageInstituition',
  'pageResearch',
  'pageEvents',
  'shortPage',
  'nvd3',
  'testDirective',
]);


text:
set -e
source .config/build
source $SCRIPTS_FOLDER/util.sh

STORYBOOK_DEST=$DEST/public/_designsystem

STORYBOOK_DEST=$STORYBOOK_DEST \
    .scripts/designsystem/build.sh

exit 0


text:
namespace Packets
{
class CGAskPrivateInfo : public Packet
{
public:
    CGAskPrivateInfo( ){}
    virtual ~CGAskPrivateInfo( ){}

    //公用继承接口
    virtual BOOL            Read( SocketInputStream& iStream ) ;
    virtual BOOL            Write( SocketOutputStream& oStream )const ;
    virtual UINT            Execute( Player* pPlayer ) ;

    virtual PacketID_t        GetPacketID()const { return PACKET_CG_ASKPRIVATEINFO ; }
    virtual UINT            GetPacketSize()const { return sizeof(ObjID_t) ; }

public:
    //使用数据接口
    ObjID_t                    GetPlayerID(VOID) { return m_PlayerID; }
    VOID                    SetPlayerID(ObjID_t PlayerID) { m_PlayerID = PlayerID; }

private:
    //数据
    ObjID_t                    m_PlayerID;
};

class CGAskPrivateInfoFactory : public PacketFactory
{
public:
    Packet*        CreatePacket() { return new CGAskPrivateInfo() ; }
    PacketID_t    GetPacketID()const { return PACKET_CG_ASKPRIVATEINFO; }
    UINT        GetPacketMaxSize()const { return sizeof(ObjID_t) ; }
};

class CGAskPrivateInfoHandler
{
public:
    static UINT Execute( CGAskPrivateInfo* pPacket, Player* pPlayer ) ;
};

}

using namespace Packets;

#endif


text:
import six

from anvil import exceptions as excp
from anvil import log as logging
from anvil import patcher
from anvil import settings
from anvil import shell as sh
from anvil import trace as tr
from anvil import type_utils as tu
from anvil import utils

LOG = logging.getLogger(__name__)

class Component(object):
    def __init__(self, name, subsystems, instances, options, siblings, distro, **kwargs):
        # Subsystems this was requested with
        self.subsystems = subsystems

        # The component name (from config)
        self.name = name

        # Any component options
        self.options = options

        # All the other active instances
        self.instances = instances

        # All the other class names that can be used alongside this class
        self.siblings = siblings

        # The distribution 'interaction object'
        self.distro = distro

        # Turned on and off as phases get activated
        self.activated = False

        # Where our binaries will be located
        self.bin_dir = "/usr/bin/"

        # Where configuration will be written
        self.cfg_dir = sh.joinpths("/etc/", self.name)

    def get_password(self, option):
        pw_val = self.passwords.get(option)
        if pw_val is None:
            raise excp.PasswordException("Password asked for option %s but none was pre-populated!" % (option))
        return pw_val

    def get_interpolated_option(self, option, default_value=None):
        tried = [option]
        while True:
            option_value = utils.get_deep(self.options, [option])
            if option_value is None:
                return default_value
            else:
                if not isinstance(option_value, six.string_types):
                    return option_value
                if option_value.startswith("$"):
                    maybe_option = option_value[1:]
                    if maybe_option in tried:
                        tried.append(maybe_option)
                        raise excp.ConfigException("Option loop %s detected" % tried)
                    else:
                        tried.append(maybe_option)
                        option = maybe_option
                else:
                    return option_value

    def get_option(self, option, *options, **kwargs):
        option_value = utils.get_deep(self.options, [option] + list(options))
        if option_value is None:
            return kwargs.get('default_value')
        else:
            return option_value

    def get_bool_option(self, option, *options, **kwargs):
        if 'default_value' not in kwargs:
            kwargs['default_value'] = False
        return tu.make_bool(self.get_option(option, *options, **kwargs))

    def get_int_option(self, option, *options, **kwargs):
        if 'default_value' not in kwargs:
            kwargs['default_value'] = 0
        return int(self.get_option(option, *options, **kwargs))

    @property
    def env_exports(self):
        return {}

    def verify(self):
        pass

    def __str__(self):
        return "%s@%s" % (tu.obj_name(self), self.name)

    @property
    def params(self):
        # Various params that are frequently accessed
        return {
            'APP_DIR': self.get_option('app_dir'),
            'COMPONENT_DIR': self.get_option('component_dir'),
            'TRACE_DIR': self.get_option('trace_dir'),
        }

    def warm_configs(self):
        # Before any actions occur you get the chance to
        # warmup the configs u might use (ie for prompting for passwords
        # earlier rather than later)
        pass

    def subsystem_names(self):
        return self.subsystems.keys()

    @property
    def packages(self):
        return []

    def package_names(self):
        """Return a set of names of all packages for this component."""
        names = set()
        for pack in self.packages:
            try:
                names.add(pack["name"])
            except KeyError:
                pass
        daemon_to_package = self.get_option("daemon_to_package")
        if not daemon_to_package:
            daemon_to_package = {}
        for key in self.subsystem_names():
            try:
                names.add(daemon_to_package[key])
            except KeyError:
                names.add("openstack-%s-%s" % (self.name, key))
        return names

class BasicComponent(Component):
    def __init__(self, *args, **kargs):
        super(BasicComponent, self).__init__(*args, **kargs)
        trace_fn = tr.trace_filename(self.get_option('trace_dir'), 'created')
        self.tracewriter = tr.TraceWriter(trace_fn, break_if_there=False)

    def download(self):
        return []

    def list_patches(self, section):
        what_patches = self.get_option('patches', section)
        if not what_patches:
            what_patches = [sh.joinpths(settings.CONFIG_DIR, 'patches',
                                        self.name, section)]
        canon_what_patches = []
        for path in what_patches:
            if sh.isdir(path):
                patches = sorted(fn for fn in sh.listdir(path, files_only=True)
                                 if fn.endswith('patch'))
                canon_what_patches.extend(patches)
            elif sh.isfile(path):
                canon_what_patches.append(path)
        return canon_what_patches

    def patch(self, section):
        canon_what_patches = self.list_patches(section)
        if canon_what_patches:
            target_dir = self.get_option('app_dir')
            patcher.apply_patches(canon_what_patches, target_dir)


text:
namespace foundation    { class IAbortSwitch; }

using namespace foundation;
using namespace std;

namespace renderer
{

namespace
{
    //
    // OSL closure tree -> appleseed BSDFs adapter.
    //

    class OSLBSDFImpl
      : public BSDF
    {
      public:
        OSLBSDFImpl(
            const char*                 name,
            const ParamArray&           params)
          : BSDF(name, AllBSDFTypes, ScatteringMode::All, params)
        {
            memset(m_all_bsdfs, 0, sizeof(BSDF*) * NumClosuresIDs);

            m_ashikhmin_shirley_brdf = create_and_register_bsdf(AshikhminShirleyID, "ashikhmin_brdf");
            m_blinn_brdf = create_and_register_bsdf(BlinnID, "blinn_brdf");
            m_diffuse_btdf = create_and_register_bsdf(TranslucentID, "diffuse_btdf");
            m_disney_brdf = create_and_register_bsdf(DisneyID, "disney_brdf");

            m_glass_beckmann_bsdf = create_and_register_glass_bsdf(GlassBeckmannID, "beckmann");
            m_glass_ggx_bsdf = create_and_register_glass_bsdf(GlassGGXID, "ggx");
            m_glass_std_bsdf = create_and_register_glass_bsdf(GlassSTDID, "std");

            m_glossy_beckmann_brdf = create_and_register_glossy_brdf(GlossyBeckmannID, "beckmann");
            m_glossy_ggx_brdf = create_and_register_glossy_brdf(GlossyGGXID, "ggx");
            m_glossy_std_brdf = create_and_register_glossy_brdf(GlossySTDID, "std");

            m_metal_beckmann_brdf = create_and_register_metal_brdf(MetalBeckmannID, "beckmann");
            m_metal_ggx_brdf = create_and_register_metal_brdf(MetalGGXID, "ggx");
            m_metal_std_brdf = create_and_register_metal_brdf(MetalSTDID, "std");

            m_orennayar_brdf = create_and_register_bsdf(OrenNayarID, "orennayar_brdf");

            m_plastic_beckmann_brdf = create_and_register_plastic_brdf(PlasticBeckmannID, "beckmann");
            m_plastic_ggx_brdf = create_and_register_plastic_brdf(PlasticGGXID, "ggx");
            m_plastic_gtr1_brdf = create_and_register_plastic_brdf(PlasticGTR1ID, "gtr1");
            m_plastic_std_brdf = create_and_register_plastic_brdf(PlasticSTDID, "std");

            m_sheen_brdf = create_and_register_bsdf(SheenID, "sheen_brdf");
        }

        void release() override
        {
            delete this;
        }

        const char* get_model() const override
        {
            return "osl_bsdf";
        }

        bool on_frame_begin(
            const Project&              project,
            const BaseGroup*            parent,
            OnFrameBeginRecorder&       recorder,
            IAbortSwitch*               abort_switch) override
        {
            if (!BSDF::on_frame_begin(project, parent, recorder, abort_switch))
                return false;

            for (int i = 0; i < NumClosuresIDs; ++i)
            {
                if (BSDF* bsdf = m_all_bsdfs[i])
                {
                    if (!bsdf->on_frame_begin(project, parent, recorder, abort_switch))
                        return false;
                }
            }

            return true;
        }

        void* evaluate_inputs(
            const ShadingContext&       shading_context,
            const ShadingPoint&         shading_point) const override
        {
            Arena& arena = shading_context.get_arena();

            CompositeSurfaceClosure* c =
                arena.allocate_noinit<CompositeSurfaceClosure>();

            new (c) CompositeSurfaceClosure(
                Basis3f(shading_point.get_shading_basis()),
                shading_point.get_osl_shader_globals().Ci,
                arena);

            for (size_t i = 0, e = c->get_closure_count(); i < e; ++i)
            {
                bsdf_from_closure_id(c->get_closure_type(i))
                    .prepare_inputs(
                        arena,
                        shading_point,
                        c->get_closure_input_values(i));
            }

            return c;
        }

        void sample(
            SamplingContext&            sampling_context,
            const void*                 data,
            const bool                  adjoint,
            const bool                  cosine_mult,
            const int                   modes,
            BSDFSample&                 sample) const override
        {
            const CompositeSurfaceClosure* c = static_cast<const CompositeSurfaceClosure*>(data);

            float pdfs[CompositeSurfaceClosure::MaxClosureEntries];
            const int num_matching_closures = c->compute_pdfs(modes, pdfs);

            if (num_matching_closures == 0)
                return;

            sampling_context.split_in_place(1, 1);
            const size_t closure_index = c->choose_closure(
                sampling_context.next2<float>(),
                num_matching_closures,
                pdfs);
            const Basis3f& modified_basis = c->get_closure_shading_basis(closure_index);

            sample.m_shading_basis = modified_basis;
            sample.m_shading_point->set_shading_basis(Basis3d(modified_basis));

            bsdf_from_closure_id(c->get_closure_type(closure_index))
                .sample(
                    sampling_context,
                    c->get_closure_input_values(closure_index),
                    adjoint,
                    false,
                    modes,
                    sample);
            sample.m_value *= c->get_closure_weight(closure_index);

            if (sample.m_mode == ScatteringMode::Specular || sample.m_probability == 0.0f)
                return;

            sample.m_probability *= pdfs[closure_index];
            pdfs[closure_index] = 0.0f;

            // Evaluate the closures we didn't sample.
            for (size_t i = 0, e = c->get_closure_count(); i < e; ++i)
            {
                if (pdfs[i] > 0.0f)
                {
                    DirectShadingComponents s;
                    const float pdf =
                        bsdf_from_closure_id(c->get_closure_type(i))
                            .evaluate(
                                c->get_closure_input_values(i),
                                adjoint,
                                false,
                                sample.m_geometric_normal,
                                c->get_closure_shading_basis(closure_index),
                                sample.m_outgoing.get_value(),
                                sample.m_incoming.get_value(),
                                modes,
                                s)  * pdfs[i];

                    if (pdf > 0.0f)
                    {
                        madd(sample.m_value, s, c->get_closure_weight(i));
                        sample.m_probability += pdf;
                    }
                }
            }
        }

        float evaluate(
            const void*                 data,
            const bool                  adjoint,
            const bool                  cosine_mult,
            const Vector3f&             geometric_normal,
            const Basis3f&              shading_basis,
            const Vector3f&             outgoing,
            const Vector3f&             incoming,
            const int                   modes,
            DirectShadingComponents&    value) const override
        {
            const CompositeSurfaceClosure* c = static_cast<const CompositeSurfaceClosure*>(data);

            float pdfs[CompositeSurfaceClosure::MaxClosureEntries];
            c->compute_pdfs(modes, pdfs);

            float prob = 0.0f;

            for (size_t i = 0, e = c->get_closure_count(); i < e; ++i)
            {
                if (pdfs[i] > 0.0f)
                {
                    DirectShadingComponents s;
                    const float pdf =
                        bsdf_from_closure_id(c->get_closure_type(i))
                            .evaluate(
                                c->get_closure_input_values(i),
                                adjoint,
                                false,
                                geometric_normal,
                                c->get_closure_shading_basis(i),
                                outgoing,
                                incoming,
                                modes,
                                s) * pdfs[i];

                    if (pdf > 0.0f)
                    {
                        madd(value, s, c->get_closure_weight(i));
                        prob += pdf;
                    }
                }
            }

            return prob;
        }

        float evaluate_pdf(
            const void*                 data,
            const bool                  adjoint,
            const Vector3f&             geometric_normal,
            const Basis3f&              shading_basis,
            const Vector3f&             outgoing,
            const Vector3f&             incoming,
            const int                   modes) const override
        {
            const CompositeSurfaceClosure* c = static_cast<const CompositeSurfaceClosure*>(data);

            float pdfs[CompositeSurfaceClosure::MaxClosureEntries];
            c->compute_pdfs(modes, pdfs);

            float prob = 0.0f;

            for (size_t i = 0, e = c->get_closure_count(); i < e; ++i)
            {
                if (pdfs[i] > 0.0f)
                {
                    prob +=
                        bsdf_from_closure_id(c->get_closure_type(i))
                            .evaluate_pdf(
                                c->get_closure_input_values(i),
                                adjoint,
                                geometric_normal,
                                c->get_closure_shading_basis(i),
                                outgoing,
                                incoming,
                                modes) * pdfs[i];
                }
            }

            return prob;
        }

        float sample_ior(
            SamplingContext&            sampling_context,
            const void*                 data) const override
        {
            const CompositeSurfaceClosure* c = static_cast<const CompositeSurfaceClosure*>(data);
            sampling_context.split_in_place(1, 1);
            return c->choose_ior(sampling_context.next2<float>());
        }

        void compute_absorption(
            const void*                 data,
            const float                 distance,
            Spectrum&                   absorption) const override
        {
            const CompositeSurfaceClosure* c = static_cast<const CompositeSurfaceClosure*>(data);

            absorption.set(1.0f);

            for (size_t i = 0, e = c->get_closure_count(); i < e; ++i)
            {
                const ClosureID cid = c->get_closure_type(i);
                if (cid > GlassID && cid <= LastGlassClosure)
                {
                    const float w = c->get_closure_scalar_weight(i);
                    Spectrum a;
                    bsdf_from_closure_id(cid)
                        .compute_absorption(
                            c->get_closure_input_values(i),
                            distance * w,
                            a);
                    absorption *= a;
                }
            }
        }

      private:
        BSDF*                       m_all_bsdfs[NumClosuresIDs];
        auto_release_ptr<BSDF>      m_ashikhmin_shirley_brdf;
        auto_release_ptr<BSDF>      m_blinn_brdf;
        auto_release_ptr<BSDF>      m_diffuse_btdf;
        auto_release_ptr<BSDF>      m_disney_brdf;
        auto_release_ptr<BSDF>      m_glass_beckmann_bsdf;
        auto_release_ptr<BSDF>      m_glass_ggx_bsdf;
        auto_release_ptr<BSDF>      m_glass_std_bsdf;
        auto_release_ptr<BSDF>      m_glossy_beckmann_brdf;
        auto_release_ptr<BSDF>      m_glossy_ggx_brdf;
        auto_release_ptr<BSDF>      m_glossy_std_brdf;
        auto_release_ptr<BSDF>      m_metal_beckmann_brdf;
        auto_release_ptr<BSDF>      m_metal_ggx_brdf;
        auto_release_ptr<BSDF>      m_metal_std_brdf;
        auto_release_ptr<BSDF>      m_orennayar_brdf;
        auto_release_ptr<BSDF>      m_plastic_beckmann_brdf;
        auto_release_ptr<BSDF>      m_plastic_ggx_brdf;
        auto_release_ptr<BSDF>      m_plastic_gtr1_brdf;
        auto_release_ptr<BSDF>      m_plastic_std_brdf;
        auto_release_ptr<BSDF>      m_sheen_brdf;

        auto_release_ptr<BSDF> create_and_register_bsdf(
            const ClosureID         cid,
            const char*             model)
        {
            auto_release_ptr<BSDF> bsdf =
                BSDFFactoryRegistrar().lookup(model)->create(model, ParamArray());

            m_all_bsdfs[cid] = bsdf.get();

            return bsdf;
        }

        auto_release_ptr<BSDF> create_and_register_glass_bsdf(
            const ClosureID         cid,
            const char*             mdf_name)
        {
            auto_release_ptr<BSDF> bsdf =
                GlassBSDFFactory().create(
                    "glass_bsdf",
                    ParamArray()
                        .insert("mdf", mdf_name)
                        .insert("volume_parameterization", "transmittance"));

            m_all_bsdfs[cid] = bsdf.get();

            return bsdf;
        }

        auto_release_ptr<BSDF> create_and_register_glossy_brdf(
            const ClosureID         cid,
            const char*             mdf_name)
        {
            auto_release_ptr<BSDF> bsdf =
                GlossyBRDFFactory().create(
                    "glossy_brdf",
                    ParamArray().insert("mdf", mdf_name));

            m_all_bsdfs[cid] = bsdf.get();

            return bsdf;
        }

        auto_release_ptr<BSDF> create_and_register_metal_brdf(
            const ClosureID         cid,
            const char*             mdf_name)
        {
            auto_release_ptr<BSDF> bsdf =
                MetalBRDFFactory().create(
                    "metal_brdf",
                    ParamArray().insert("mdf", mdf_name));

            m_all_bsdfs[cid] = bsdf.get();

            return bsdf;
        }

        auto_release_ptr<BSDF> create_and_register_plastic_brdf(
            const ClosureID         cid,
            const char*             mdf_name)
        {
            auto_release_ptr<BSDF> bsdf =
                PlasticBRDFFactory().create(
                    "plastic_brdf",
                    ParamArray().insert("mdf", mdf_name));

            m_all_bsdfs[cid] = bsdf.get();

            return bsdf;
        }

        const BSDF& bsdf_from_closure_id(const ClosureID cid) const
        {
            const BSDF* bsdf = m_all_bsdfs[cid];
            assert(bsdf);
            return *bsdf;
        }

        BSDF& bsdf_from_closure_id(const ClosureID cid)
        {
            BSDF* bsdf = m_all_bsdfs[cid];
            assert(bsdf);
            return *bsdf;
        }
    };

    typedef BSDFWrapper<OSLBSDFImpl, false> OSLBSDF;
}

//
// OSLBSDFFactory class implementation.
//

auto_release_ptr<BSDF> OSLBSDFFactory::create() const
{
    return auto_release_ptr<BSDF>(new OSLBSDF("osl_bsdf", ParamArray()));
}

}   // namespace renderer


text:
..
      Copyright 2011-2012 OpenStack, LLC
      All Rights Reserved.

      Licensed under the Apache License, Version 2.0 (the "License"); you may
      not use this file except in compliance with the License. You may obtain
      a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
      WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
      License for the specific language governing permissions and limitations
      under the License.

========
Backends
========

Keystone supports multiple types of data stores for things like users, tenants, and
tokens, including SQL, LDAP, and memcache.

SQL
===

In the default backend configuration (SQL-only), Keystone depends on the following database tables.

``users``
---------

``id``
    Auto-incremented primary key.
``name``
    Unqiue username used for authentication via ``passwordCredentials``.
``password``
    Password used for authentication via ``passwordCredentials``.

    Salted and hashed using ``passlib``.
``email``
    Email address (uniqueness is expected, but not enforced).
``enabled``
    If false, the user is unable to authenticate and the user's tokens will fail validation.
``tenant_id``
    Default tenant for the user.

``tokens``
----------

``id``
    The actual token provided after successful authentication (*plaintext*).
``user_id``
    References the user who owns the token.
``tenant_id``
    (*optional*) References the tenant the token is scoped to.
``expires``
    Indicates the expiration date of the token, after which the token can no longer be validated successfully.

``tenants``
-----------

``id``
    Auto-incremented primary key.
``name``
    Unique string identifying the tenant.
``desc``
    Description of the tenant.
``enabled``
    If false, users are unable to scope to the tenant.

``roles``
---------

``id``
    Auto-incremented primary key.
``name``
    Name of the role.

    If the role is owned by a service, the role name **must** follow the convention::

        serviceName:roleName
``desc``
    Description of the role.
``service_id``
    (*optional*) References the service that owns the role.

``user_roles``
--------------

Maps users to the roles that have been granted to them (*optionally*, within the scope of a tenant).

``id``
    Auto-incremented primary key.
``user_id``
    References the user the role is granted to.
``role_id``
    References the granted role.
``tenant_id``
    (*optional*) References a tenant upon which this grant is applies.

``services``
------------

``id``
    Auto-incremented primary key.
``name``
    Unique name of the service.
``type``
    Indicates the type of service (e.g. ``compute``, ``object``, ``identity``, etc).

    This can also be extended to support non-core services. Extended services
    follow the naming convention ``extension:type`` (e.g. ``dnsextension:dns``).
``desc``
    Describes the service.
``owner_id``
    (*optional*) References the user who owns the service.

``credentials``
---------------

Currently only used for Amazon EC2 credential storage, this table is designed to support multiple
types of credentials in the future.

``id``
    Auto-incremented primary key.
``user_id``
    References the user who owns the credential.
``tenant_id``
    References the tenant upon which the credential is valid.
``types``
    Indicates the type of credential (e.g. ``Password``, ``APIKey``, ``EC2``).
``key``
    Amazon EC2 access key.
``secret``
    Amazon EC2 secret key.

``endpoints``
-------------

Tenant-specific endpoints map endpoint templates to specific tenants.
The ``tenant_id`` which appears here replaces the
``%tenant_id%`` template variable in the specified endpoint template.

``id``
    Auto-incremented primary key.
``tenant_id``
    References the tenant this endpoint applies to.
``endpoint_template_id``
    The endpoint template to appear in the user's service catalog.

``endpoint_templates``
----------------------

A multi-purpose model for the service catalog which can be:

- Provided to users of a specific tenants via ``endpoints``, when ``is_global`` is false.
- Provided to all users as-is, when ``is_global`` is true.

``id``
    Auto-incremented primary key.
``region``
    Identifies the geographic region the endpoint is physically located within.
``service_id``
    TODO: References the service which owns the endpoints?
``public_url``
    Appears in the service catalog [#first]_.

    Represents an endpoint available on the public Internet.
``admin_url``
    Appears in the service catalog [#first]_.

    Users of this endpoint must have an Admin or ServiceAdmin role.
``internal_url``
    Appears in the service catalog [#first]_.

    Represents an endpoint on an internal, unmetered network.
``enabled``
    If false, this endpoint template will not appear in the service catalog.
``is_global``
    If true, this endpoint can not be mapped to tenant-specific endpoints, and ``%tenant_id%`` will not be substituted in endpoint URL's. Additionally, this endpoint will appear for all users.
``version_id``
    Identifies the version of the API contract that endpoint supports.
``version_list``
    A URL which lists versions supported by the endpoint.
``version_info``
    A URL which provides detailed version info regarding the service.

.. [#first] ``%tenant_id%`` may be replaced by actual tenant references, depending on the value of ``is_global`` and the existence of a corresponding ``endpoints`` record.


text:
package io.reactivesocket.websocket.rxnetty;

import static rx.Observable.*;

import org.junit.Test;
import static io.reactivesocket.websocket.rxnetty.TestUtil.*;

import io.netty.buffer.ByteBuf;
import io.reactivesocket.websocket.rxnetty.ReactiveSocketWebSocketServer;
import io.reactivex.netty.protocol.http.client.HttpClient;
import io.reactivex.netty.protocol.http.server.HttpServer;
import rx.Single;

public class ReactiveSocketWebSocketServerTest {

    @Test
    public void test() {
        // create protocol with handlers
        ReactiveSocketWebSocketServer handler = ReactiveSocketWebSocketServer.create(
        		requestResponsePayload -> {
                	String requestResponse = byteToString(requestResponsePayload.getData());
                    return Single.just(utf8EncodedPayloadData("hello" + requestResponse));
                } ,
        		requestStreamPayload -> {
                	String requestStream = byteToString(requestStreamPayload.getData());
                    return just("a_" + requestStream, "b_" + requestStream).map(n -> utf8EncodedPayloadData(n));
                } , null, null, null);

        // start server with protocol
        HttpServer<ByteBuf, ByteBuf> server = HttpServer.newServer();
        int port = server.getServerPort();
        server.start((request, response) -> {
            return response.acceptWebSocketUpgrade(handler::acceptWebsocket);
        });

        // TODO send actual requests
        HttpClient.newClient("localhost", server.getServerPort())
                .createGet("/")
                .requestWebSocketUpgrade();

        server.shutdown();
    }
}


text:
One of the features of this library is to validate the YAML file in addition to the JSON. In fact, the main use case for this library is to be part of the light-4j framework to validate the request/response at runtime against the OpenAPI specification file openapi.yaml. If you are not using light-4j, you need to load the YAML with https://github.com/FasterXML/jackson-dataformats-text first, and then everything is the same as JSON.

### Usage

Add the dependency

```xml
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.10.1</version>
</dependency>
```

and create object mapper using yaml factory i.e `ObjectMapper objMapper =new ObjectMapper(new YAMLFactory());`

#### Example
```java
JsonSchemaFactory factory = JsonSchemaFactory.builder(JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V7)).objectMapper(mapper).build(); /* Using draft-07. You can choose anyother draft.*/
JsonSchema schema = factory.getSchema(YamlOperations.class.getClassLoader().getResourceAsStream("your-schema.json"));

JsonNode jsonNode = mapper.readTree(YamlOperations.class.getClassLoader().getResourceAsStream("your-file.yaml"));
Set<ValidationMessage> validateMsg = schema.validate(jsonNode);
```


text:
/**
 * @fileoverview Stylish reporter
 * @author Sindre Sorhus
 */
"use strict";

const chalk = require("chalk"),
    stripAnsi = require("strip-ansi"),
    table = require("text-table");

var fs = require("fs");
var path = require("path");
var SourceMapConsumer = require("source-map").SourceMapConsumer;

var reSourceMappingURL = /\/\/# sourceMappingURL=(.*)/g;

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Given a word and a count, append an s if count is not one.
 * @param {string} word A word in its singular form.
 * @param {int} count A number controlling whether word should be pluralized.
 * @returns {string} The original word with an s on the end if count is not one.
 */
function pluralize(word, count) {
    return count === 1 ? word : `${word}s`;
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = function (results) {
    var len = results.length;
    var str = "";
    var prevfile;
    var prevorig;
    var smc;

    let output = "\n",
        errorCount = 0,
        warningCount = 0,
        fixableErrorCount = 0,
        fixableWarningCount = 0,
        summaryColor = "yellow";

    results.forEach((result) => {
        const messages = result.messages;

        if (messages.length === 0) {
            return;
        }

        errorCount += result.errorCount;
        warningCount += result.warningCount;
        fixableErrorCount += result.fixableErrorCount;
        fixableWarningCount += result.fixableWarningCount;

        output += `${chalk.underline(result.filePath)}\n`;

        output += `${table(
            messages.map((message) => {
                let messageType;

                if (message.fatal || message.severity === 2) {
                    messageType = chalk.red("error");
                    summaryColor = "red";
                } else {
                    messageType = chalk.yellow("warning");
                }

                let file = result.filePath;
                let line = message.line;
                let col = message.column;

                if (prevfile !== file) {
                    smc = null;
                    var js = fs.readFileSync(file, { encoding: "utf8" });
                    var match,
                        smf = null;
                    while ((match = reSourceMappingURL.exec(js)) !== null) smf = match[1];
                    if (smf) {
                        smf = path.resolve(path.dirname(file), smf);
                        var smt = fs.readFileSync(smf, { encoding: "utf8" });
                        smc = new SourceMapConsumer(smt);
                    }
                }
                prevfile = file;

                if (smc && line >= 1) {
                    var orig = smc.originalPositionFor({
                        line: line,
                        column: col,
                    });
                    if (orig.source) {
                        file = orig.source;
                        file = file.replace(/^\.\.\/\.\.\/src\/js\//, "");
                        line = orig.line;
                        col = orig.column;
                    }
                }
                if (prevorig && prevorig !== file) {
                    str += "\n";
                }

                return [
                    "",
                    file,
                    `line: ${line}`,
                    `column: ${col}`,
                    messageType,
                    message.message.replace(/([^ ])\.$/u, "$1"),
                    chalk.dim(message.ruleId || ""),
                ];
            }),
            {
                align: ["", "l", "l"],
                stringLength(str) {
                    return stripAnsi(str).length;
                },
            }
        )
            .split("\n")
            .map((el) => el.replace(/(\d+)\s+(\d+)/u, (m, p1, p2) => chalk.dim(`${p1}:${p2}`)))
            .join("\n")}\n\n`;
    });

    const total = errorCount + warningCount;

    if (total > 0) {
        output += chalk[summaryColor].bold(
            [
                "\u2716 ",
                total,
                pluralize(" problem", total),
                " (",
                errorCount,
                pluralize(" error", errorCount),
                ", ",
                warningCount,
                pluralize(" warning", warningCount),
                ")\n",
            ].join("")
        );

        if (fixableErrorCount > 0 || fixableWarningCount > 0) {
            output += chalk[summaryColor].bold(
                [
                    "  ",
                    fixableErrorCount,
                    pluralize(" error", fixableErrorCount),
                    " and ",
                    fixableWarningCount,
                    pluralize(" warning", fixableWarningCount),
                    " potentially fixable with the `--fix` option.\n",
                ].join("")
            );
        }
    }

    // Resets output color, for prevent change on top level
    return total > 0 ? chalk.reset(output) : "";
};


text:
<?php

namespace Secure;
use Exception;

class SecureHash {

	private $value;
	private $text;
	private $algo;
	private $algos;

	/**
	 * Initializes a Hash object and assigns both hash algorithm and value
	 * or file name to be hashed. $algo is modified to a lower case string prior to assignment.
	 * Throws an Exception if the first argument is not a string
	 *
	 * @param  string  $algo The algorithm to be used (default md5)
	 * @param  mixed   $val  The data or file name(including the route) to be hashed (default '')
	 * @throws Exception if algorithm given is not a string
	 */

	public function __construct($algo = 'md5', $val = ''){

		if(!is_string($algo)){
			throw new Exception('The algorithm must be a string');
		}

		$this->algo  = trim(strtolower($algo));
		$this->value = $val;
		$this->algos = $this->getAlgorithms();
	}

	public function __toString(){
		return $this->value;
	}

	/**
	 * Returns the current value/file name to be hashed
	 *
	 * @return string The value to be hashed
	 */

	public function getValue(){
		return $this->value;
	}

	/**
	 * Returns the current algorithm
	 *
	 * @return string The hashing algorithm
	 */

	public function getAlgo(){
		return $this->algo;
	}

	/**
	 * Returns the encoding used by the Stringy object.
	 *
	 * @return array All the PHP available hash functions
	 */

	public function getAlgorithms(){
		return hash_algos();
	}

	/**
	 * Change the current value or file to other
	 * if the given value is not a string then serialize the data
	 *
	 * @param mixed $val The new value
	 * @return void
	 */

	public function setValue($val){
		$this->value = $val;
	}

	/**
	 * Change the current hash algorithm to other and set it in lowercase
	 *
	 * @param string $algo The new hash algorithm
	 * @return void
	 */

	public function setAlgo($algo){
		$this->algo = trim(strtolower($algo));
	}

	/**
	 * Returns the encoding used by the Stringy object.
	 *
	 * @return string The current value of the $encoding property
	 */

	private function hasAlgorithms(){

		$this->algo = strtolower($this->algo);
		$algorithmsLength = count($this->algos) - 1;
		$find = false;

		while(!$find && $algorithmsLength >= 0){
			if(($this->algo == $this->algos[$algorithmsLength])){
				$find = true;
			}else{
				$algorithmsLength--;
			}
		}

		return ($algorithmsLength >= 0) ? true : false;
	}

	/**
	 * Returns the hashed value.
	 *
	 * @param void
	 * @return string The hash value
	 */

	public function cifrate(){
		if(!$this->hasAlgorithms()){
			return false;
		}

		if(is_array($this->value) || is_object($this->value)){
			return hash($this->algo, serialize($this->value));
		}

		return hash($this->algo, $this->value);
	}

	/**
	 * Returns the hashed file.
	 *
	 * @param void
	 * @return string The hash value
	 * @throws Exception message if the file requested does not exists
	 */

	public function cifrateFile(){
		if(!$this->hasAlgorithms()){
			return false;
		}

		try{
			if(!file_exists($this->value)){
				throw new Exception('The file requested does not exists');
			}else{
				$fileHandler = fopen($this->value, 'rb');
				$this->text = fread($fileHandler, filesize($this->value));
				fclose($fileHandler);
				return hash($this->algo, $this->text);
			}
		}catch(Exception $e){
			exit($e->getMessage() ."\n");
		}
	}

	/**
	 * Returns the hashed url data downloaded.
	 *
	 * @param void
	 * @return string The hash value
	 * @throws Exception message if the file requested does not exists
	 *			or if the $file variable is not a string
	 */

	public function cifrateUrl(){
		if(!$this->hasAlgorithms()){
			return false;
		}

		try{

			if(!is_string($this->value)){
				throw new Exception('String parameters only');
			}

			if(!filter_var($this->value, FILTER_VALIDATE_URL)){
				throw new Exception('The url requested seems to be invalid');
			}else{
				$this->text = file_get_contents($this->value);

				return hash($this->algo, $this->text);
			}
		}catch(Exception $e){
			exit($e->getMessage() ."\n");
		}
	}

	/**
	 * Returns the hashed values or only or a hashed value
	 * in case of the array.
	 *
	 * @param mixed $values An array containing diffent types of variables
	 * 				to be hashed or a string(not recommended)
	 * @return mixed $data array if there is at least more than one
	 *			array element or a string if pass a string variable
	 * @throws Exception message if pass an empty array
	 */

	public function cifrateMultiple($values){
		try{
			if(is_array($values) && count($values) > 1){

				$data = array();
				$result = null;

				foreach ($values as $value) {
					$this->setValue($value);
					$result = $this->cifrate();
					if(is_string($result)){
						$data[] = $result;
					}else{
						return false;
					}
				}

				return $data;
			}elseif(is_array($values) && count($values) == 1){
				$this->setValue($values[0]);
				return $this->cifrate();
			}elseif(is_array($values) && empty($values)){
				throw new Exception('You must provide a non empty array');
			}else{
				$this->setValue($values);
				return $this->cifrate();
			}
		}catch(Exception $e){
			exit($e->getMessage() ."\n");
		}
	}

	/**
	 * Returns the hashed array of files.
	 *
	 * @param mixed  $files The files (including the directory) to be hashed
	 *					or a string if a string was passed(not recommended)
	 * @return mixed The hash value
	 * @throws Exception message if the file requested does not exists
	 *			or if the $files variable is a string
	 */

	public function cifrateMultipleFiles($files){
		try{
			if(is_array($files) && count($files) > 1){

				$data = array();
				$result = null;

				foreach($files as $file){
					if(!is_file($file)){
						return false;
					}
					$this->setValue($file);
					$result = $this->cifrateFile();
					if(is_string($result) && !empty($result)){
						$data[] = $result;
					}else{
						return false;
					}
				}

				return $data;
			}elseif(is_array($files) && count($files) == 1){
				$this->setValue($files[0]);
				return $this->cifrateFile();
			}elseif(is_array($files) && empty($files)){
				throw new Exception('You must provide a non empty array');
			}else{
				$this->setValue($files);
				return $this->cifrateFile($files);
			}
		}catch(Exception $e){
			exit($e->getMessage() ."\n");
		}

	}

	/**
	 * Returns the hashed array of urls.
	 *
	 * @param mixed  $urls The urls to be hashed
	 *					or a string if a string was passed(not recommended)
	 * @return mixed The hash value
	 * @throws Exception message if the url requested seems to be invalid
	 */

	public function cifrateMultipleUrls($urls){
		try{
			if(is_array($urls) && count($urls) > 1){

				$data = array();
				$result = null;

				foreach($urls as $url){
					$this->setValue($url);
					$result = $this->cifrateUrl();
					if(is_string($result) && !empty($result)){
						$data[] = $result;
					}else{
						return false;
					}
				}

				return $data;
			}elseif(is_array($urls) && count($urls) == 1){
				$this->setValue($urls[0]);
				return $this->cifrateUrl();
			}elseif(is_array($urls) && empty($urls)){
				throw new Exception('You must provide a non empty array');
			}else{
				$this->setValue($urls);
				return $this->cifrateUrl($urls);
			}
		}catch(Exception $e){
			exit($e->getMessage() ."\n");
		}
	}

	/**
	 * Compare two variables and check if they are equal or not
	 *
	 * @param mixed  $val1		The first value to compare
	 * @param mixed  $val2		The second value to compare
	 * @param string $algorithm The algorithm to use
	 * @return bool true if the variables are equals or false if not
	 */

	public function compare($val1, $val2, $algorithm = ''){
		if(!empty($algorithm)){
			$this->setAlgo($algorithm);
		}

		$this->setValue($val1);
		$val1 = $this->cifrate();
		$this->setValue($val2);
		$val2 = $this->cifrate();

		return ($val1 == $val2) ? true : false;
	}

	/**
	 * Compare two files and check if they are equal or not
	 *
	 * @param string  $file1		The first file to compare
	 * @param string  $file2		The second file to compare
	 * @param string  $algorithm 	The algorithm to use
	 * @return bool true if the files are equals or false if not
	 */

	public function compareFiles($file1, $file2, $algorithm = ''){
		if(!empty($algorithm)){
			$this->setAlgo($algorithm);
		}

		$this->setValue($file1);
		$file1 = $this->cifrateFile();
		$this->setValue($file2);
		$file2 = $this->cifrateFile();

		return ($file1 == $file2) ? true : false;
	}

	/**
	 * Compare two Urls and check if they are equal or not
	 *
	 * @param string  $val1		 The first url to compare
	 * @param string  $val2		 The second url to compare
	 * @param string  $algorithm The algorithm to use
	 * @return bool true if the urls are equals or false if not
	 */

	public function compareUrls($url1, $url2, $algorithm = ''){
		if(!empty($algorithm)){
			$this->setAlgo($algorithm);
		}

		$this->setValue($url1);
		$url1 = $this->cifrateUrl();
		$this->setValue($url2);
		$url2 = $this->cifrateUrl();

		return ($url1 == $url2) ? true : false;
	}

}


text:
import requests

from dnb_direct.exceptions import DnbAuthenticationError, DnbError

class DirectClient(object):
    """
    Client library object for DnB Direct API
    """

    # Cached storage of the authentication token
    _token = None

    api_url = "https://direct.dnb.com"
    api_version = "2.0"

    allowed_methods = ['GET', 'POST']

    def __init__(self, username, password, **kwargs):
        """
        Create the API client instance.  Requires a username and password which is used to
        authenticate API requests.

        :param username: DNB API Username
        :param password: DNB API Password
        :param kwargs:
        :return:
        """
        self.username = username
        self.password = password

        self.debug = kwargs.get('debug', False)

        super().__init__()

    def _authenticate(self):
        """
        Makes the appropriate API request for authentication and stores the token.

        The URL structure of Authentication requests differs from other API endpoints, so
        there is some special request handling here that differs from DirectClient.call_api()
        """
        # We must first authenticate and retrieve a token for accessing the API
        # see:  https://docs.dnb.com/direct/2.0/en-US/quick-rest-API
        headers = {
            'x-dnb-user': self.username,
            'x-dnb-pwd': self.password,
        }

        # The authenticate enpoint differs in structure from other calls, and specifies the endpoint
        # before the version.
        request_url = "{0}/{1}/V{2}/".format(self.api_url, 'Authentication', self.api_version)
        response = requests.post(request_url, headers=headers)

        # Authentication was successful
        if response.status_code == 200:
            response_json = response.json()
            authentication_detail = response_json.get('AuthenticationDetail', False)
            # Authentication successful.  Return the token
            if authentication_detail:
                return authentication_detail['Token']

        # Authentication failed
        elif response.status_code == 401:
            response_json = response.json()
            raise DnbAuthenticationError(
                response_json['TransactionResult']['ResultMessage']['ResultDescription'])

        raise DnbError("Unexpected response received from Authenticate endpoint.  "
                        "Response was: {response}".format(response=response.text))

    def call_api(self, endpoint, version=None, method='GET', **parameters):
        """
        Method to call an API endpoint.  It will first authenticate the client to retrieve a token
        if one has not been retrieved already.

        This method can be used directly for low-level access, but it is intended to be consumed by
        per-endpoint wrapper methods to enforce parameter validation, service version handling, etc.

        :param endpoint: API endpoint to be called
        :param version: Version of the API to Call.  DnB API SERVICE.  Each service has a different
            version number and multiple endpoints.  See the API docs for more info.
        :param method: HTTP Method to use.
        :param parameters: kwargs to be passed as parameters to the
        :return: object
        """
        # Authenticate if we do not have a token
        if self._token is None:
            self._token = self._authenticate()

        # Add athentication headers
        headers = {
            'Authorization': self._token,
        }

        request_url = "{api_base}/V{version}/{endpoint}".format(
            api_base=self.api_url,
            endpoint=endpoint,
            version=self.api_version if version is None else version,
        )

        # Request the endpoint with the passed parameters.  Use the appropriate method
        if method not in self.allowed_methods:
            raise DnbError("API request method must be one of {methods}".format(
                methods=", ".join(self.allowed_methods)
            ))

        # Get some terminal output going if Debug is on
        if self.debug:
            print("{method} {url}".format(method=method, url=request_url))
            print("Headers: {0}".format(str(headers)))
            print("Parameters: {0}".format(str(parameters)))

        if method == 'GET':
            response = requests.get(request_url, params=parameters, headers=headers)
        elif method == 'POST':
            response = requests.post(request_url, json=parameters, headers=headers)

        try:
            return response.json()
        except ValueError:
            # We got a non JSON reponse here, which means we hit an invalid endpoint.
            raise DnbError("Attempted to request an invalid endpoint, {endpoint}".format(
                endpoint=endpoint))

    ####################
    # API Endpoints
    ####################

    def match(self, ApplicationTransactionID=None, TransactionTimestamp=None,
              SubmittingOfficeID=None, DUNSNumber=None, SubjectName=None, StreetAddressLine=[],
              PrimaryTownName=None, CountryISOAlpha2Code=None, TerritoryName=None,
              FullPostalCode=None, TelephoneNumber=None, InternationalDialingCode=None,
              OrganizationIdentificationNumber=None, CandidateMaximumQuantity=None,
              ConfidenceLowerLevelThresholdValue=None, ExclusionCriteria=[], OrderReasonCode=None,
              MatchTypeText=None, CustomerReferenceText=None, CustomerBillingEndorsementText=None):

        """
        Makes a call to the Match endpoint as defined by the docs at:
        https://docs.dnb.com/direct/2.0/en-US/company/latest/match/rest-API

        Two input variables, StreetAddressLine and ExclusionCriteria accept mutiple values and are
        cast as empty lists by default.  These get translated to StreetAddressLine-n (where n is a
        a numerical sequence (1-indexed) of the passed in values.  See the "-n" designation info at:
        https://docs.dnb.com/direct/2.0/en-US/company/latest/match/rest-API#Specification

        All other inputs are passed to the API endpoint if supplied.

        :param ApplicationTransactionID:
        :param TransactionTimestamp:
        :param SubmittingOfficeID:
        :param DUNSNumber:
        :param SubjectName:
        :param StreetAddressLine:
        :param PrimaryTownName:
        :param CountryISOAlpha2Code:
        :param TerritoryName:
        :param FullPostalCode:
        :param TelephoneNumber:
        :param InternationalDialingCode:
        :param OrganizationIdentificationNumber:
        :param CandidateMaximumQuantity:
        :param ConfidenceLowerLevelThresholdValue:
        :param ExclusionCriteria:
        :param OrderReasonCode:
        :param MatchTypeText:
        :param CustomerReferenceText:
        :param CustomerBillingEndorsementText:
        :return: object
        """

        # This specifies a match call
        parameters = {'match': 'true'}

        # Check the -n values.
        # StreetAddressLine
        if len(StreetAddressLine) > 2:
            raise DnbError("StreetAddressLine can contain at most 2 values.")
        else:
            parameters.update({"StreetAddressLine-{0}".format(i + 1): v
                               for i, v in enumerate(StreetAddressLine)})

        # ExclusionCriteria
        if len(ExclusionCriteria) > 6:
            raise DnbError("ExclusionCriteria can contain at most 6 values.")
        else:
            parameters.update({"ExclusionCriteria-{0}".format(i + 1): v
                               for i, v in enumerate(ExclusionCriteria)})

        # All other values should be included verbatim if not None
        single_params = ['ApplicationTransactionID', 'TransactionTimestamp', 'SubmittingOfficeID',
                         'DUNSNumber', 'SubjectName', 'PrimaryTownName',
                         'CountryISOAlpha2Code', 'TerritoryName', 'FullPostalCode',
                         'TelephoneNumber', 'InternationalDialingCode',
                         'OrganizationIdentificationNumber', 'CandidateMaximumQuantity',
                         'ConfidenceLowerLevelThresholdValue', 'OrderReasonCode', 'MatchTypeText',
                         'CustomerReferenceText', 'CustomerBillingEndorsementText']

        # Pack the non-None values into the parameters dict
        # Dict comprehension does not work here because they execute under a new scope, and
        # therefore do not have access to our function's variables
        for name in single_params:
            value = locals()[name]
            if value is not None:
                parameters.update({name: value})

        # Make the match call
        return self.call_api('organizations', '5.0', **parameters)

    def company_profile(self, DUNS, product, version='5.1', ApplicationTransactionID=None,
                        TransactionTimestamp=None, SubmittingOfficeID=None,
                        CountryISOAlpha2Code=None, LanguagePreferenceCode=None,
                        OrderReasonCode=None, TradeUpIndicator=None,
                        ArchiveProductOptOutIndicatior=None, ExtendArchivePeriodIndicator=None,
                        PortfolioAssetContainerID=None, CustomerReferenceText=None,
                        CustomerBillingEndorsementText=None):
        """
        Makes a call to the Company Profile endpoint as defined by the docs at:
        https://docs.dnb.com/direct/2.0/en-US/firmographic/latest/orderproduct/marketing-rest-API#DetailedCompanyProfile

        :param DUNS:  Required, DUNS number of company
        :param product:  Required, a valid Dnb profile product code (DCP_STD, DCP_ENH, DCP_PREM)
        :param ApplicationTransactionID:
        :param TransactionTimestamp:
        :param SubmittingOfficeID:
        :param CountryISOAlpha2Code:
        :param LanguagePreferenceCode:
        :param OrderReasonCode:
        :param TradeUpIndicator:
        :param ArchiveProductOptOutIndicatior:
        :param ExtendArchivePeriodIndicator:
        :param PortfolioAssetContainerID:
        :param CustomerReferenceText:
        :param CustomerBillingEndorsementText:
        :return:
        """

        parameters = {}

        # Validate a correct product was requested
        assert product in ['DCP_STD', 'DCP_ENH', 'DCP_PREM', 'DCP_WB1784']

        # All other values should be included verbatim if not None
        single_params = ['ApplicationTransactionID',
                         'TransactionTimestamp', 'SubmittingOfficeID',
                         'CountryISOAlpha2Code', 'LanguagePreferenceCode',
                         'OrderReasonCode', 'TradeUpIndicator',
                         'ArchiveProductOptOutIndicatior', 'ExtendArchivePeriodIndicator',
                         'PortfolioAssetContainerID', 'CustomerReferenceText',
                         'CustomerBillingEndorsementText']

        # Pack the non-None values into the parameters dict
        # Dict comprehension does not work here because they execute under a new scope, and
        # therefore do not have access to our function's variables
        for name in single_params:
            value = locals()[name]
            if value is not None:
                parameters.update({name: value})

        # Make the profile call
        return self.call_api('organizations/{DUNS}/products/{product}'.format(
            DUNS=DUNS, product=product), version, **parameters)


text:
<?php
$function = function () use ($di) {
    $dispatcher = new \Phalcon\Mvc\Dispatcher();
    $dispatcher->setDefaultNamespace('Controllers');
    if( !defined("DEBUG_MODE") && !DEBUG_MODE )
    {
        $evManager = $di->getShared('eventsManager');

        $evManager->attach(
            "dispatch:beforeException",
            function($event, $dispatcher, $exception)
            {
                $dispatcher->forward(
                    array(
                        'controller' => 'error',
                        'action'     => 'show404',
                    )
                );
                return false;
            }
        );
        $dispatcher->setEventsManager($evManager);
    }

    return $dispatcher;
};
return $function;


text:
class ModelItem;

class Library : public QObject {
    Q_OBJECT
public:
    static Library * instance();
    static void close() {
        if (self != 0) {
            self -> timer -> stop();
            self -> save();
            delete self;
        }
    }

    void clearRemote();
    void removeRemoteItem(ModelItem * item);
    void initItem(ModelItem * item, const QObject * caller, const char * slot);
    bool addItem(ModelItem * item, int state);
    void restoreItemState(ModelItem * item);

    QString filenameFilter(QString title);

    void setRemoteItemMax(int newMax);

private slots:
    void saveCatalogs();
    void startRemoteInfoProc();

private:
    static Library *self;

    Library() : QObject() {
        catalogs = new QHash<QChar,  QHash<QString, int>* >();
        catalogs_state = QHash<QChar, QList<QString> *>();
        catsSaveResult = QFuture<void>();

        timer = new QTimer();
        QObject::connect(timer, SIGNAL(timeout()), this, SLOT(saveCatalogs()));
        timer -> start(10000);

        QObject::connect(&remoteTimer, SIGNAL(timeout()), this, SLOT(startRemoteInfoProc()));
        remoteTimer.start(2000);

        QDir dir(libraryPath());
        if (!dir.exists()) {
            dir.mkpath(".");
        }
    }

    ~Library() {
        delete catalogs;
        delete timer;
    }

    ModelItem * procRemoteInfo(ModelItem * item);
    ModelItem * itemsInit(ModelItem * item);

    QString sitesFilter(QString title);
    QString forwardNumberPreFilter(QString title);
    QString spacesFilter(QString title);
    QString forwardNumberFilter(QString title);

    QString libraryPath();

    QString prepareName(QString gipoTitle, bool additional = false);
    bool proceedItemNames(QList<QString> * names, int state);

    QChar getCatalogChar(QString name);

    QHash<QString, int> * getCatalog(QChar letter);
    QHash<QString, int> * getCatalog(QString name);

    void initItemInfo(ModelItem * item);
//    QList<QString> * getNamesForObject(QString path, QString name);
//    QList<QString> * getNamesForItem(ModelItem * item);
//    QList<QString> * getNamesForItem(QString path);

    QHash<QString, int> * load(const QChar letter);
    void save();
    bool fileDump(QChar key, QList<QString> & keysList, QFlags<QIODevice::OpenModeFlag> openFlags);

    QHash<QChar, QHash<QString, int>* > * catalogs;
    QHash<QChar, QList<QString> *> catalogs_state;
    QHash<ModelItem *, FuncContainer> remote_collations;
    QList<ModelItem *> remote_items;
    int remote_items_max = 10;

    ModelItem * currRemote;
    QTimer * timer;
    QTimer remoteTimer;
    QMutex saveBlock;

    QFuture<void> catsSaveResult;
};

#endif // LIBRARY_H


text:
@(q: lila.qa.Question, answers: List[lila.qa.Answer], popular: List[lila.qa.Question], related: List[lila.qa.Question], answerForm: Option[Form[_]], captcha: Option[lila.common.Captcha])(implicit ctx: Context)

@side = {
@if(!related.isEmpty){@relatedBox(related)}
@popularBox(popular)
}

@layout(
title = s"${q.title} • ${trans.questionsAndAnswers()}",
side = side.some,
openGraph = lila.app.ui.OpenGraph(
title = q.title,
url = s"$netBaseUrl${routes.QaQuestion.show(q.id, q.slug).url}",
description = shorten(q.body.replace("\n", ""), 152).body).some) {

      @q.title

      @if(lila.qa.QaAuth canEdit q) {
       Edit question
      }
      @nope("Delete", routes.QaQuestion.remove(q.id))

          Asked
          @momentFromNow(q.createdAt) by @userIdLink(q.userId.some)

        @if(q.tags.nonEmpty) {

          Tags
          @tags(q.tags)

        }

          Activity
          Viewed @q.views times, last updated @momentFromNow(q.updatedAt)

        @views.html.qa.vote(routes.QaQuestion.vote(q.id).url, q.vote)

          @autoLink(q.body)

          @views.html.qa.commentList(q, q.comments, routes.QaComment.question(q.id).url)

    @answerList(q, answers)
    @if(ctx.me.fold(true)(lila.qa.QaAuth.isN00b)) {

      Only registered members with one week of lichess activity can contribute to the Q&A.

    } else {
    @(answerForm, captcha) match {
    case (Some(form), Some(captcha)) => {

      @if(answers.nonEmpty) {

Your answer

      }
      <form class="wide" action="@routes.QaAnswer.create(q.id).url#your-answer" method="post">
        <textarea class="answer-body" name="@form("body").name">@form("body").value</textarea>
        @errMsg(form("body"))
        @base.captcha(form("move"), form("gameId"), captcha)
        <button class="pure submit button" type="submit">Post your answer</button>
      </form>

    }
    case _ => {
    You cannot answer this question.
    }
    }
    }

}


text:
class UnclassifiedSelector
  def run
    file_set = Set.new
    files = Medium.all
    files.each do |file|
      if file.relations.empty?
      	file_set << file.filename
      end
    end
    file_set
  end
end


text:
<?php

if (!defined('PHPUnit_MAIN_METHOD')) {
    define('PHPUnit_MAIN_METHOD', 'Zend_Application_Resource_LayoutTest::main');
}

/**
 * Zend_Loader_Autoloader
 */
require_once 'Zend/Loader/Autoloader.php';

/**
 * @category   Zend
 * @package    Zend_Application
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Application
 */
class Zend_Application_Resource_LayoutTest extends PHPUnit_Framework_TestCase
{
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite(__CLASS__);
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    public function setUp()
    {
        // Store original autoloaders
        $this->loaders = spl_autoload_functions();
        if (!is_array($this->loaders)) {
            // spl_autoload_functions does not return empty array when no
            // autoloaders registered...
            $this->loaders = array();
        }

        Zend_Loader_Autoloader::resetInstance();
        $this->autoloader = Zend_Loader_Autoloader::getInstance();

        $this->application = new Zend_Application('testing');

        $this->bootstrap = new Zend_Application_Bootstrap_Bootstrap($this->application);

        Zend_Controller_Front::getInstance()->resetInstance();
    }

    public function tearDown()
    {
        // Restore original autoloaders
        $loaders = spl_autoload_functions();
        foreach ($loaders as $loader) {
            spl_autoload_unregister($loader);
        }

        foreach ($this->loaders as $loader) {
            spl_autoload_register($loader);
        }

        // Reset autoloader instance so it doesn't affect other tests
        Zend_Loader_Autoloader::resetInstance();
    }

    public function testInitializationInitializesLayoutObject()
    {
        $resource = new Zend_Application_Resource_Layout(array());
        $resource->setBootstrap($this->bootstrap);
        $resource->init();
        $this->assertTrue($resource->getLayout() instanceof Zend_Layout);
    }

    public function testInitializationReturnsLayoutObject()
    {
        $resource = new Zend_Application_Resource_Layout(array());
        $resource->setBootstrap($this->bootstrap);
        $test = $resource->init();
        $this->assertTrue($test instanceof Zend_Layout);
    }

    public function testOptionsPassedToResourceAreUsedToSetLayoutState()
    {
        $options = array(
            'layout'     => 'foo.phtml',
            'layoutPath' => dirname(__FILE__),
        );

        $resource = new Zend_Application_Resource_Layout($options);
        $resource->setBootstrap($this->bootstrap);
        $resource->init();
        $layout   = $resource->getLayout();
        $test     = array(
            'layout'     => $layout->getLayout(),
            'layoutPath' => $layout->getLayoutPath(),
        );
        $this->assertEquals($options, $test);
    }
}

if (PHPUnit_MAIN_METHOD == 'Zend_Application_Resource_LayoutTest::main') {
    Zend_Application_Resource_LayoutTest::main();
}