text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<title>  DOM Builder - The Web Standards Project</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="The Web Standards Project is a grassroots coalition fighting for standards which ensure simple, affordable access to web technologies for all." />
<meta name="MSSmartTagsPreventParsing" content="true" />

<link rel="stylesheet" type="text/css" media="screen, projection" href="/wp/wp-content/themes/web-standards-project/styles.css" />
<link rel="stylesheet" type="text/css" media="print" href="/wp/wp-content/themes/web-standards-project/print.css" />
<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="/feed/index.html" />
<link rel="alternate" type="text/xml" title="RSS .92" href="/feed/rss/index.html" />
<link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="/feed/atom/index.html" />
<link rel="pingback" href="/wp/xmlrpc.php" />
<link rel="Shortcut Icon" type="image/ico" href="/files/theme/wasp.ico" />
<link rel="home" title="Web Standards Project Home" href="/index.html" />
	<link rel='archives' title='March 2013' href='/2013/03/index.html' />
	<link rel='archives' title='February 2012' href='/2012/02/index.html' />
	<link rel='archives' title='December 2011' href='/2011/12/index.html' />
	<link rel='archives' title='November 2011' href='/2011/11/index.html' />
	<link rel='archives' title='March 2011' href='/2011/03/index.html' />
	<link rel='archives' title='February 2011' href='/2011/02/index.html' />
	<link rel='archives' title='January 2011' href='/2011/01/index.html' />
	<link rel='archives' title='August 2010' href='/2010/08/index.html' />
	<link rel='archives' title='June 2010' href='/2010/06/index.html' />
	<link rel='archives' title='March 2010' href='/2010/03/index.html' />
	<link rel='archives' title='February 2010' href='/2010/02/index.html' />
	<link rel='archives' title='January 2010' href='/2010/01/index.html' />
	<link rel='archives' title='November 2009' href='/2009/11/index.html' />
	<link rel='archives' title='June 2009' href='/2009/06/index.html' />
	<link rel='archives' title='May 2009' href='/2009/05/index.html' />
	<link rel='archives' title='April 2009' href='/2009/04/index.html' />
	<link rel='archives' title='March 2009' href='/2009/03/index.html' />
	<link rel='archives' title='February 2009' href='/2009/02/index.html' />
	<link rel='archives' title='January 2009' href='/2009/01/index.html' />
	<link rel='archives' title='December 2008' href='/2008/12/index.html' />
	<link rel='archives' title='November 2008' href='/2008/11/index.html' />
	<link rel='archives' title='October 2008' href='/2008/10/index.html' />
	<link rel='archives' title='September 2008' href='/2008/09/index.html' />
	<link rel='archives' title='August 2008' href='/2008/08/index.html' />
	<link rel='archives' title='July 2008' href='/2008/07/index.html' />
	<link rel='archives' title='June 2008' href='/2008/06/index.html' />
	<link rel='archives' title='May 2008' href='/2008/05/index.html' />
	<link rel='archives' title='April 2008' href='/2008/04/index.html' />
	<link rel='archives' title='March 2008' href='/2008/03/index.html' />
	<link rel='archives' title='February 2008' href='/2008/02/index.html' />
	<link rel='archives' title='January 2008' href='/2008/01/index.html' />
	<link rel='archives' title='December 2007' href='/2007/12/index.html' />
	<link rel='archives' title='November 2007' href='/2007/11/index.html' />
	<link rel='archives' title='October 2007' href='/2007/10/index.html' />
	<link rel='archives' title='September 2007' href='/2007/09/index.html' />
	<link rel='archives' title='August 2007' href='/2007/08/index.html' />
	<link rel='archives' title='June 2007' href='/2007/06/index.html' />
	<link rel='archives' title='May 2007' href='/2007/05/index.html' />
	<link rel='archives' title='April 2007' href='/2007/04/index.html' />
	<link rel='archives' title='March 2007' href='/2007/03/index.html' />
	<link rel='archives' title='February 2007' href='/2007/02/index.html' />
	<link rel='archives' title='January 2007' href='/2007/01/index.html' />
	<link rel='archives' title='December 2006' href='../../../12/index.html' />
	<link rel='archives' title='November 2006' href='../../../11/index.html' />
	<link rel='archives' title='October 2006' href='../../../10/index.html' />
	<link rel='archives' title='September 2006' href='../../../09/index.html' />
	<link rel='archives' title='August 2006' href='../../../08/index.html' />
	<link rel='archives' title='July 2006' href='../../../07/index.html' />
	<link rel='archives' title='June 2006' href='../../../06/index.html' />
	<link rel='archives' title='May 2006' href='../../../05/index.html' />
	<link rel='archives' title='April 2006' href='../../index.html' />
	<link rel='archives' title='March 2006' href='../../../03/index.html' />
	<link rel='archives' title='February 2006' href='../../../02/index.html' />
	<link rel='archives' title='January 2006' href='../../../01/index.html' />
	<link rel='archives' title='December 2005' href='/2005/12/index.html' />
	<link rel='archives' title='November 2005' href='/2005/11/index.html' />
	<link rel='archives' title='October 2005' href='/2005/10/index.html' />
	<link rel='archives' title='September 2005' href='/2005/09/index.html' />
	<link rel='archives' title='August 2005' href='/2005/08/index.html' />
	<link rel='archives' title='July 2005' href='/2005/07/index.html' />
	<link rel='archives' title='June 2005' href='/2005/06/index.html' />
	<link rel='archives' title='May 2005' href='/2005/05/index.html' />
	<link rel='archives' title='April 2005' href='/2005/04/index.html' />
	<link rel='archives' title='March 2005' href='/2005/03/index.html' />
	<link rel='archives' title='February 2005' href='/2005/02/index.html' />
	<link rel='archives' title='January 2005' href='/2005/01/index.html' />
	<link rel='archives' title='December 2004' href='/2004/12/index.html' />
	<link rel='archives' title='November 2004' href='/2004/11/index.html' />
	<link rel='archives' title='October 2004' href='/2004/10/index.html' />
	<link rel='archives' title='September 2004' href='/2004/09/index.html' />
	<link rel='archives' title='August 2004' href='/2004/08/index.html' />
	<link rel='archives' title='July 2004' href='/2004/07/index.html' />
	<link rel='archives' title='June 2004' href='/2004/06/index.html' />
	<link rel='archives' title='May 2004' href='/2004/05/index.html' />
	<link rel='archives' title='April 2004' href='/2004/04/index.html' />
	<link rel='archives' title='March 2004' href='/2004/03/index.html' />
	<link rel='archives' title='February 2004' href='/2004/02/index.html' />
	<link rel='archives' title='January 2004' href='/2004/01/index.html' />
	<link rel='archives' title='December 2003' href='/2003/12/index.html' />
	<link rel='archives' title='November 2003' href='/2003/11/index.html' />
	<link rel='archives' title='October 2003' href='/2003/10/index.html' />
	<link rel='archives' title='September 2003' href='/2003/09/index.html' />
	<link rel='archives' title='August 2003' href='/2003/08/index.html' />
	<link rel='archives' title='July 2003' href='/2003/07/index.html' />
	<link rel='archives' title='June 2003' href='/2003/06/index.html' />
	<link rel='archives' title='May 2003' href='/2003/05/index.html' />
	<link rel='archives' title='April 2003' href='/2003/04/index.html' />
	<link rel='archives' title='March 2003' href='/2003/03/index.html' />
	<link rel='archives' title='February 2003' href='/2003/02/index.html' />
	<link rel='archives' title='January 2003' href='/2003/01/index.html' />
	<link rel='archives' title='December 2002' href='/2002/12/index.html' />
	<link rel='archives' title='November 2002' href='/2002/11/index.html' />
	<link rel='archives' title='October 2002' href='/2002/10/index.html' />
	<link rel='archives' title='September 2002' href='/2002/09/index.html' />
	<link rel='archives' title='August 2002' href='/2002/08/index.html' />
	<link rel='archives' title='July 2002' href='/2002/07/index.html' />
	<link rel='archives' title='June 2002' href='/2002/06/index.html' />
	<link rel='archives' title='April 2002' href='/2002/04/index.html' />
	<link rel='archives' title='March 2002' href='/2002/03/index.html' />
	<link rel='archives' title='December 2001' href='/2001/12/index.html' />
	<link rel='archives' title='September 2001' href='/2001/09/index.html' />
	<link rel='archives' title='November 2000' href='/2000/11/index.html' />
	<link rel='archives' title='July 2000' href='/2000/07/index.html' />
	<link rel='archives' title='April 2000' href='/2000/04/index.html' />
	<link rel='archives' title='March 1999' href='/1999/03/index.html' />
	<link rel='archives' title='October 1998' href='/1998/10/index.html' />
	<link rel='archives' title='August 1998' href='/1998/08/index.html' />
<link rel="alternate" type="application/rss+xml" title="The Web Standards Project » DOM Builder Comments Feed" href="feed/index.html" />
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="/wp/xmlrpc0db0.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="/wp/wp-includes/wlwmanifest.xml" />
<link rel='prev' title='Notre Dame Web Group' href='../../12/notre-dame-web-group/index.html' />
<link rel='next' title='Painless Node Creation with DOM Builder' href='../../14/painless-node-creation-with-dom-builder/index.html' />
<meta name="generator" content="WordPress 3.3.1" />
<link rel='canonical' href='index.html' />
<link rel='shortlink' href='../../../../indexefa2.html?p=818' />

Working together for standards  The Web Standards Project

		Skip to content

				<form id="fm-search" method="get" action="http://www.webstandards.org/index.php">
			<fieldset>
				<legend>Search</legend>
				Search WaSP
				<input id="s" name="s" class="search" value="" />
				<input type="submit" class="submit" name="submit" value="Go!" />
			</fieldset>
		</form>

Home

About

Learn

Action

Buzz

Press

DOM Builder

By Jeremy Keith | April 13th, 2006 | Filed in DOM, DOM Scripting TF

Now here’s a script we can get behind… Dan Webb’s DOM Builder combines the ease of innerHTML with the precision of DOM methods.

				Skip to comment form

Dan Webb is a standards-savvy JavaScript developer who has run into a dilemma familiar to many of us…

Suppose you want to generate and insert some markup using JavaScript. You’ve got two options:

You can use the non-standard innerHTML which is quick and easy but proprietary or

You can use standards: DOM methods like createElement and createTextNode which carry the W3C’s stamp of approval but which can be finicky and repetitive to use.

Dan has resolved this conundrum by creating an elegant lightweight script to take the pain out of creating markup with JavaScript. He has provided documentation and he explains his reasons for writing the script.

Like all the best solutions, it does one thing really well instead of trying to be all things to all people. This 1K file will prove invaluable to anyone who’s been faced with the same dilemma. It’s a guilt-free way of painlessly adding nodes to the DOM tree.

Your Replies

#1 On April 13th, 2006 8:33 pm Pig Pen - Web Standards Compliant Web Design Blog » Blog Archive » DOM Builder replied:

[...] DOM Builder – a script by Dan Webb which is, as Jeremy Keith writes, a guilt-free way of painlessly adding nodes to the DOM tree [...]

#2 On April 14th, 2006 12:45 am Dustin Diaz replied:

Guilt free? Is that the only reason we should use it? Why not work toward standarizing innerHTML, eh? Really man, what’s wrong with it? Hey, just so we don’t feel bad, we can call it innerXML, yea? I have to admit though, surely Dan’s DOM builder is real slick and cool. But seriously speaking, c’mon now… can’t the W3C just work on creating some  sort of standard innerXML? It’s just too easy to ignore it. We can’t seriously be swayed to use “Dan’s DOM Builder” just because it is  “stamped with W3C approval” Surely someone else feels the same.

Jeremy, just last december you mentioned the innerHTML love-hate relationship you have?

With the emmergence of ajax and xmlHttpRequest… what are we supposed to do about that? Surely we’re not going to stop using xmlHttpRequest just because it’s non-standard. So like I mentioned, why not just standardize innerXML?

#3 On April 14th, 2006 3:44 am Stephanie replied:

Dustin the  W3 approval is all I need to know that it is trustworthy and reliable, still I agree with all the other technologies out there why use this when they are plenty of other great choices. But it is still a great script and time saver no doubt.

#4 On April 14th, 2006 6:54 am WaSP Member Jeremy Keith replied:

Dustin, did I say there was anything wrong with innerHTML?

I simply described it as being quick, easy, and proprietary. I didn’t say it was evil. I didn’t say it was bad. I simply said it was proprietary. That is a fact, not an opinion. Don’t conflate objective fact with subjective opinion.

Now, as for whether “proprietary” automatically equals “bad”… that’s a matter for very strong subjective opinion.

#5 On April 14th, 2006 3:16 pm Dustin Diaz replied:

Ya gotta love comments on the wasp site now :) – indeed it helps conversations like these get out into the open.

Anyway, back to the matter. No doubt indeed that I’ve found Dan’s Builder to be quite useful and it keeps your structure looking real nice and readable. But on innerHTML. No, Jeremy, you didn’t say anything was wrong with it. As a matter of information, it’s cool to know now that the W3 is working on standardizing xmlHttpRequest. Do you suppose it’s possible to get in something like innerHTML? or rather, innerXML? It’s seems entirely too useful to just tag it as being ‘bad’ (and again, I know you didn’t say it was bad).

#6 On April 14th, 2006 3:51 pm innerHTML and DOM Methods replied:

[...] Keith on DOM Builder (Wasp) [...]

#7 On April 15th, 2006 5:27 pm Johnny Scrutchins replied:

Need to update my Internet.         B

 Browsen

#8 On April 16th, 2006 10:32 am Dan Webb replied:

I’m not too sure myself on what method is best to use from a practical point of view.  I actually wrote the DOM Builder because I thought it was cleaner to deal with in a script compared to long strings full of quoted ” characters rather than the fact that it was necessarily better to use the DOM API over innerHTML.  With DOM Builder, the code is even more compact than the HTML it generates.  That’s it’s strongest point for me.

I actually toyed with the idea of having it build HTML strings rather than DOM nodes or maybe have it include the option to do either but that could bloat the script a bit.  I’ll look into it.

Too me the only thing that stops me using the DOM API for everything is how slow IE’s implementation is.

#9 On April 18th, 2006 12:35 pm Chris Heilmann replied:

Dustin, the reason it is called innerHTML is that it is not innerXML, but an attribute that is only applicable in a browser and HTML environment. A lot of web standards go beyond this scope and rightfully so.

XML is a standard very much in use – outside the traditional web design world due to lack of browser support. There the DOM also applies and many .NET, JAVA or PHP programmers use the DOM methods defined in the W3C standards. Muddling these standards because of a speed issue with browsers would not really help.

That innerHTML can be the better solution for some applications and scenarios is not even a debate, it is a fact. However, it does not make it a standard and IMHO it does allow for sloppy coding. I cannot generate unclosed tags with the DOM, but I can write whatever I please inside innerHTML.

#10 On April 21st, 2006 12:24 pm Dave Bleeker replied:

Hi all,

I have to admit that the use of innerHTML  method can save a lot of time and headache in some cases, but I agree with Chris Heilmann and I think the idea nothing is wrong with it is a mistake. Please correct me if I’m wrong, but basicly there are 2 major problems when using the innerHTML method:

1. All previously DOM nodes will be lost. Therefore you need to reinitialize them if any code depends on those nodes. Not really sophisticated in my opinion.

2. All content is rendered again, regardless whether the content was already rendered.

Therefore I think it is better to use the W3C compliant way of adding nodes to your document, and I wouldn’t recommend using innerHTML when it comes to scalabillity and  OOP programming.

#11 On April 30th, 2006 5:25 am M. Gozler replied:

I made–and have been from time to time revising (fixing code)—what I call the ‘DOM1.js’ library of functions a long time ago to handle exactly that problem either of nonconformance to W3C “recommendations” (even they are not willing to declare them standards!—such as the MSIE abence of the document.createDocumentFragment() method, as well as to handle pseudo-methods such as making document fragments out of setting “properties” like .innerHTML.

Should anyone be interested in this library of functions, email me.

You are warned that these have only been barely tested by me, and they worked for my purposes.

The principal function “makeHTMLDocFrag(string)” takes a string of HTML-formatted code just like setting .innerHTML, and it returns a document fragment (except under IE, in which it returns the tree under a DIV root, I think).  Moreover my functions do syntax/code checking:  they check what elements can be contained inside and outside them, so that a legal document fragment is created.

#12 On June 19th, 2006 6:52 pm Garrett replied:

This set of functions is really only to address a small handful of IE specific DOM bugs.

innerHTML is faster and sometimes cleaner. It is sometimes more appropriate than using DOM creational methods.

createDocumentFragment is supported in IE.

#13 On July 29th, 2006 3:11 am lehman replied:

David, interesting concept, although it is a bit like putting the carriage before the horse. What DOM methods teach developers is to stop seeing the HTML page as a massive string but as a set of nodes.

#14 On September 22nd, 2006 7:08 am der_simon replied:

I’m writing on a substitute for innerHTML calles innerDOM. It just works on most strings you type in.

Some things are net yet implemted and have to be writen.

So see the script and test it: http://innerdom.sourceforge.net/

Der Simon

#15 On October 8th, 2006 8:36 pm Tony Blacker replied:

Thank you, been searching for ages for a concept such as this, very very helpful! Cheers.

#16 On January 27th, 2007 11:33 pm Charles Ulrich replied:

The links to the scripts return a 404…

			Return to top

Post a Reply

Comments are closed.

Back to Top

All of the entries posted in WaSP Buzz express the opinions of their individual authors. They do not necessarily reflect the plans or positions of the Web Standards Project as a group.

This site is valid XHTML 1.0 Strict, CSS | Get Buzz via RSS or Atom | Colophon | Legal


text:
package org.librairy.boot.storage.executor;

import lombok.Getter;

/**
 * Created by cbadenes on 09/03/16.
 */
public class QueryTask implements Runnable {

    private final Runnable task;

    @Getter
    private final Integer priority;

    @Getter
    private final Long delay;

    public QueryTask(Runnable task, Integer priority, Long delay){
        this.task = task;
        this.priority = priority;
        this.delay = delay;
    }

    @Override
    public void run() {
        this.task.run();
    }
}

redpajama_set_name: RedPajamaGithub


text:
#region Using

using System;
using System.Collections.Generic;
using System.IO;
using Ini4Net;

#endregion

namespace Demo_Project
{
    internal class Program
    {
        /// <summary>
        ///     Example for processing an INI file from the INI class
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            var ini = new Ini();
            if (File.Exists("Demo1.ini"))
            {
                // setup the syntax
                ini.Syntax.CommentTokens = new[] {'#', ';'};
                ini.Syntax.SectionHeaderStartToken = '[';
                ini.Syntax.SectionHeaderEndToken = ']';
                ini.Syntax.ValueSeparatorToken = '=';

                // Read the INI
                if (ini.Read("Demo1.ini"))
                {
                    Console.WriteLine("Using Connection String {0}", ini["Database"]["Connection String"]);
                    Console.WriteLine("Logging is {0} at a level of {1}", ini["Logging"]["Enabled"],
                        ini["Logging"]["Log Level"]);

                    //
                    // Show using IEnum
                    //
                    Console.WriteLine();
                    Console.WriteLine("Iterating over all sections and keys....");
                    Console.WriteLine();
                    foreach (IniSection section in ini)
                    {
                        Console.WriteLine("[{0}]", section.Name);
                        foreach (KeyValuePair<string, string> kvp in section)
                        {
                            Console.WriteLine("{0} = {1}", kvp.Key, kvp.Value);
                        }
                        Console.WriteLine();
                    }

                    //
                    // Show exceptions
                    //
                    try
                    {
                        Console.WriteLine();
                        Console.WriteLine("Dump Complete. Attempt to read an invalid section");
                        Console.WriteLine("Not Exists: {0}", ini["Not Exist"]);
                    }
                    catch (IniSectionNotFoundException ex)
                    {
                        Console.WriteLine("Section not exist exception caught successfully");
                    }
                    catch
                    {
                        Console.WriteLine("Some other exception thrown. Error!");
                    }

                    //
                    // Show when no section or no keys
                    //
                    var tries = new List<string>();
                    tries.Add("Database");
                    tries.Add("Not Exist");

                    foreach (var section in tries)
                    {
                        try
                        {
                            Console.WriteLine("{0}: {1}", ini[section]["Not a key"]);
                        }
                        catch (IniKeyNotFoundException ex)
                        {
                            Console.WriteLine("Key not exist exception caught successfully when section does exist");
                        }
                        catch (IniSectionNotFoundException ex)
                        {
                            Console.WriteLine(
                                "Key not exist exception caught successfully when section does not exist");
                        }
                        catch
                        {
                            Console.WriteLine("Some other exception thrown. Error!");
                        }
                    }

                    //
                    // Show writing an INI
                    //
                    ini.Write("Output.ini", true);
                }
            }

            // try to create an INI file from scratch
            var syntax = new IniSyntax();
            syntax.AllowAddingSections = true;
            var myIni = new Ini(syntax);
            myIni["My Section"]["My Key"] = "One";
            myIni["Other Section"]["Key1"] = "1";
            myIni["Other Section"]["Key2"] = "2";
            myIni["Other Section"]["Key3"] = "true";
            myIni.Write("myini.ini", true);
            Console.WriteLine(myIni.Get<bool>("Other Section", "Key3"));
            myIni.Set("Other Section", "Key2", DateTime.Now);
            Console.WriteLine(myIni["Other Section"]["Key2"]);
            Console.WriteLine();
            Console.WriteLine("Press any key when ready.....");
            Console.ReadKey();
        }
    }
}


text:
#include<iostream>
#include<algorithm>
#include<iterator>
#include<opencv2/opencv.hpp>
#include<opencv2/core/core.hpp>
#include<list>
#include"opencv/highgui.h"
#include"encoder/encode.hpp"
#include"common/common.hpp"
#include"decoder/decode.hpp"
#include"test/test.hpp"
#include"namespace/namespace.hpp"

list<Mat> frame_list;
list<Mat>:: iterator frame_it;

int main(int argc, char** argv){
	//test_delta();
	//huffman_u_test();
	printf("\n");
	cout<<"-----------------------------"<<endl;
	//huffman_s_test();*/
	CvCapture *capture = cvCaptureFromFile("Megamind.avi");
	if (!capture) {
    std::cout << "COULD NOT OPEN CAPTURE\n";
		exit(0);
	}

	IplImage * frame = NULL;
	while((frame = cvQueryFrame(capture))!=NULL){
		Mat frame_mat(frame, true);
		frame_list.push_back(frame_mat);
	}

	cvReleaseImage(&frame);
	cvReleaseCapture(&capture);

	/*unsigned long long elements = 0;
	for(frame_it = frame_list.begin(); frame_it!= frame_list.end(); frame_it++){
		elements = (*frame_it).cols*(*frame_it).rows*(*frame_it).channels();
		//cout<<(*frame_it).cols<<" "<<(*frame_it).rows<<" "<<(*frame_it).channels()<<" "<<(*frame_it).type()<<endl;
	}

	cout<<"elements"<<elements<<endl;*/

	//Frist frame in the video is totally black. It is ignored for the latter reason.
	//frame_list.pop_front();

	cout<<"Total Frame Count "<<frame_list.size()<<endl;
	if(frame_list.empty()){
		cout<<"Frame list is empty"<<endl;
		return -1;
	}

	Mat max, min, rec_img;

	encode(frame_list, max, min);

	huffman_u_test(1140480);

	frame_it = frame_list.begin();

	int frame_rows = (*frame_it).rows;
	int frame_cols = (*frame_it).cols;
	int frame_channels = (*frame_it).channels();

	while(!video_codec.empty()){
			recover_frame(max, min, rec_img, video_codec.front(), frame_rows, frame_cols, frame_channels);
			validate_dif(rec_img, (*frame_it), frame_rows, frame_cols, frame_channels, max, min);
			frame_it++;
			video_codec.pop();
			cvNamedWindow("Video", WINDOW_AUTOSIZE);
			imshow("Video", rec_img);
			cvWaitKey(33);
	}

	cvDestroyWindow("Video");

	if(frame_it != frame_list.end()){
		cout<<"One or more frames are missing from Video Codec"<<endl;
	}

	frame_list.clear();

return 0;
}


text:
<?php

namespace WebinoAppLib\Service;

use WebinoAppLib\Application;
use WebinoAppLib\Event\AppEvent;
use WebinoAppLib\Feature\Config;
use WebinoAppLib\Log;
use WebinoConfigLib\Feature\ConfigCacheEnabled;
use Zend\ServiceManager\Config as ServicesConfig;

/**
 * Application bootstrap
 */
class Bootstrap
{
    /**
     * Application configuration cache key
     */
    const CACHE_KEY = 'config';

    /**
     * @var Application
     */
    private $app;

    /**
     * @var string
     */
    private $cacheKey;

    /**
     * @param object|Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * @return string
     */
    private function getCacheKey()
    {
        return $this::CACHE_KEY . '_' . $this->cacheKey;
    }

    /**
     * @param string $key
     * @return $this
     */
    public function setCacheKey($key)
    {
        $this->cacheKey .= md5($key);
        return $this;
    }

    /**
     * Configures the application
     *
     * Returns cached early if any.
     *
     * @triggers configure
     * @return $this
     */
    public function configure()
    {
        $config   = $this->app->getConfig();
        $useCache = $this->app->getConfig(ConfigCacheEnabled::KEY);

        if ($useCache) {
            $cached = $this->app->getCache($this->getCacheKey());
            if ($cached) {
                $this->app->setConfig($cached);
                $this->configureServices();
                $this->app->log(Log\LoadCachedAppConfig::class);
                return $this;
            }
        }

        $this->app->emit(AppEvent::CONFIGURE, [], [$this->app, 'mergeConfig']);
        $this->configureServices();
        $this->app->log(Log\ConfigureApp::class);

        $useCache and $this->app->setCache($this->getCacheKey(), $config);

        return $this;
    }

    /**
     * Configure application services
     *
     * @return $this
     */
    protected function configureServices()
    {
        $services = $this->app->getConfig(Config::SERVICES);
        if (null === $services) {
            return $this;
        }

        $config = $services->toArray();
        (new ServicesConfig($config))->configureServiceManager($this->app->getServices());
        return $this;
    }

    /**
     * Attach core listeners
     *
     * @return $this
     */
    public function attachCoreListeners()
    {
        $this->eachCoreListener([$this, 'attachListener']);
        return $this;
    }

    /**
     * Detach core listeners
     *
     * @return $this
     */
    public function detachCoreListeners()
    {
        $this->eachCoreListener([$this, 'detachListener']);
        return $this;
    }

    /**
     * Attach application listeners
     *
     * @return $this
     */
    public function attachListeners()
    {
        $this->eachListener([$this, 'attachListener']);
        return $this;
    }

    /**
     * @param $listener
     */
    protected function attachListener($listener)
    {
        $service = $this->app->get($listener);
        $service and $this->app->bind($service);
    }

    /**
     * @param $listener
     */
    protected function detachListener($listener)
    {
        $service = $this->app->get($listener);
        $service and $this->app->unbind($service);
    }

    /**
     * @param callable $callback
     */
    protected function eachCoreListener(callable $callback)
    {
        $listeners = $this->app->getCoreConfig(Config::LISTENERS);
        if (empty($listeners)) {
            return;
        }

        foreach ($listeners as $listener) {
            call_user_func($callback, $listener);
        }
    }

    /**
     * @param callable $callback
     */
    protected function eachListener(callable $callback)
    {
        $listeners = $this->app->getConfig(Config::LISTENERS);
        if (empty($listeners)) {
            return;
        }

        foreach ($listeners as $listener) {
            call_user_func($callback, $listener);
        }
    }
}


text:
package com.farmerbb.taskbar.ui;

import android.graphics.PixelFormat;
import android.view.WindowManager;

import com.farmerbb.taskbar.util.U;

import java.lang.reflect.Field;

public class ViewParams {
    public int width;
    public int height;
    public int gravity;
    public int flags;
    public int bottomMargin;

    public ViewParams(int width, int height, int gravity, int flags, int bottomMargin) {
        this.width = width;
        this.height = height;
        this.gravity = gravity;
        this.flags = flags;
        this.bottomMargin = bottomMargin;
    }

    public WindowManager.LayoutParams toWindowManagerParams() {
        final WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams(
                width,
                height,
                U.getOverlayType(),
                flags,
                PixelFormat.TRANSLUCENT
        );

        if(gravity > -1)
            wmParams.gravity = gravity;

        if(bottomMargin > -1)
            wmParams.y = bottomMargin;

        U.allowReflection();
        try {
            Class<?> layoutParamsClass = Class.forName("android.view.WindowManager$LayoutParams");

            Field privateFlags = layoutParamsClass.getField("privateFlags");
            Field noAnim = layoutParamsClass.getField("PRIVATE_FLAG_NO_MOVE_ANIMATION");

            int privateFlagsValue = privateFlags.getInt(wmParams);
            int noAnimFlag = noAnim.getInt(wmParams);
            privateFlagsValue |= noAnimFlag;

            privateFlags.setInt(wmParams, privateFlagsValue);
        } catch (Exception ignored) {}

        return wmParams;
    }

    public ViewParams updateWidth(int width) {
        return new ViewParams(width, height, gravity, flags, bottomMargin);
    }

    public ViewParams updateHeight(int height) {
        return new ViewParams(width, height, gravity, flags, bottomMargin);
    }

    public ViewParams updateBottomMargin(int bottomMargin) {
        return new ViewParams(width, height, gravity, flags, bottomMargin);
    }
}


text:
namespace starboard {
namespace shared {
namespace starboard {
namespace player {
namespace filter {

AudioRendererSinkImpl::AudioRendererSinkImpl()
    : create_audio_sink_func_(
          [](SbTime start_media_time,
             int channels,
             int sampling_frequency_hz,
             SbMediaAudioSampleType audio_sample_type,
             SbMediaAudioFrameStorageType audio_frame_storage_type,
             SbAudioSinkFrameBuffers frame_buffers,
             int frame_buffers_size_in_frames,
             SbAudioSinkUpdateSourceStatusFunc update_source_status_func,
             SbAudioSinkPrivate::ConsumeFramesFunc consume_frames_func,
             SbAudioSinkPrivate::ErrorFunc error_func,
             void* context) {
            return SbAudioSinkPrivate::Create(
                channels, sampling_frequency_hz, audio_sample_type,
                audio_frame_storage_type, frame_buffers,
                frame_buffers_size_in_frames, update_source_status_func,
                consume_frames_func, error_func, context);
          }) {}

AudioRendererSinkImpl::AudioRendererSinkImpl(
    CreateAudioSinkFunc create_audio_sink_func)
    : create_audio_sink_func_(create_audio_sink_func) {
  SB_DCHECK(create_audio_sink_func_);
}

AudioRendererSinkImpl::~AudioRendererSinkImpl() {
  SB_DCHECK(thread_checker_.CalledOnValidThread());

  Stop();
}

bool AudioRendererSinkImpl::IsAudioSampleTypeSupported(
    SbMediaAudioSampleType audio_sample_type) const {
  return SbAudioSinkIsAudioSampleTypeSupported(audio_sample_type);
}

bool AudioRendererSinkImpl::IsAudioFrameStorageTypeSupported(
    SbMediaAudioFrameStorageType audio_frame_storage_type) const {
  return SbAudioSinkIsAudioFrameStorageTypeSupported(audio_frame_storage_type);
}

int AudioRendererSinkImpl::GetNearestSupportedSampleFrequency(
    int sampling_frequency_hz) const {
  return SbAudioSinkGetNearestSupportedSampleFrequency(sampling_frequency_hz);
}

bool AudioRendererSinkImpl::HasStarted() const {
  return SbAudioSinkIsValid(audio_sink_);
}

void AudioRendererSinkImpl::Start(
    SbTime media_start_time,
    int channels,
    int sampling_frequency_hz,
    SbMediaAudioSampleType audio_sample_type,
    SbMediaAudioFrameStorageType audio_frame_storage_type,
    SbAudioSinkFrameBuffers frame_buffers,
    int frames_per_channel,
    RenderCallback* render_callback) {
  SB_DCHECK(thread_checker_.CalledOnValidThread());
  SB_DCHECK(!HasStarted());
  SB_DCHECK(channels > 0 && channels <= SbAudioSinkGetMaxChannels());
  SB_DCHECK(sampling_frequency_hz > 0);
  SB_DCHECK(SbAudioSinkIsAudioSampleTypeSupported(audio_sample_type));
  SB_DCHECK(
      SbAudioSinkIsAudioFrameStorageTypeSupported(audio_frame_storage_type));
  SB_DCHECK(frame_buffers);
  SB_DCHECK(frames_per_channel > 0);

  Stop();
  render_callback_ = render_callback;
  audio_sink_ = create_audio_sink_func_(
      media_start_time, channels, sampling_frequency_hz, audio_sample_type,
      audio_frame_storage_type, frame_buffers, frames_per_channel,
      &AudioRendererSinkImpl::UpdateSourceStatusFunc,
      &AudioRendererSinkImpl::ConsumeFramesFunc,
      &AudioRendererSinkImpl::ErrorFunc, this);
  if (!SbAudioSinkIsValid(audio_sink_)) {
    return;
  }
  // TODO: Remove SetPlaybackRate() support from audio sink as it only need to
  // support play/pause.
  audio_sink_->SetPlaybackRate(playback_rate_);
  audio_sink_->SetVolume(volume_);
}

void AudioRendererSinkImpl::Stop() {
  SB_DCHECK(thread_checker_.CalledOnValidThread());

  if (HasStarted()) {
    SbAudioSinkDestroy(audio_sink_);
    audio_sink_ = kSbAudioSinkInvalid;
    render_callback_ = NULL;
  }
}

void AudioRendererSinkImpl::SetVolume(double volume) {
  SB_DCHECK(thread_checker_.CalledOnValidThread());

  volume_ = volume;
  if (HasStarted()) {
    audio_sink_->SetVolume(volume);
  }
}

void AudioRendererSinkImpl::SetPlaybackRate(double playback_rate) {
  SB_DCHECK(thread_checker_.CalledOnValidThread());
  SB_DCHECK(playback_rate == 0.0 || playback_rate == 1.0)
      << "Playback rate on audio sink can only be set to 0 or 1, "
      << "but is now set to " << playback_rate;

  playback_rate_ = playback_rate;
  if (HasStarted()) {
    // TODO: Remove SetPlaybackRate() support from audio sink as it only need to
    // support play/pause.
    audio_sink_->SetPlaybackRate(playback_rate);
  }
}

// static
void AudioRendererSinkImpl::UpdateSourceStatusFunc(int* frames_in_buffer,
                                                   int* offset_in_frames,
                                                   bool* is_playing,
                                                   bool* is_eos_reached,
                                                   void* context) {
  AudioRendererSinkImpl* audio_renderer_sink =
      static_cast<AudioRendererSinkImpl*>(context);
  SB_DCHECK(audio_renderer_sink);
  SB_DCHECK(audio_renderer_sink->render_callback_);
  SB_DCHECK(frames_in_buffer);
  SB_DCHECK(offset_in_frames);
  SB_DCHECK(is_playing);
  SB_DCHECK(is_eos_reached);

  audio_renderer_sink->render_callback_->GetSourceStatus(
      frames_in_buffer, offset_in_frames, is_playing, is_eos_reached);
}

// static
void AudioRendererSinkImpl::ConsumeFramesFunc(int frames_consumed,
                                              SbTime frames_consumed_at,
                                              void* context) {
  AudioRendererSinkImpl* audio_renderer_sink =
      static_cast<AudioRendererSinkImpl*>(context);
  SB_DCHECK(audio_renderer_sink);
  SB_DCHECK(audio_renderer_sink->render_callback_);

  audio_renderer_sink->render_callback_->ConsumeFrames(frames_consumed,
                                                       frames_consumed_at);
}

// static
void AudioRendererSinkImpl::ErrorFunc(bool capability_changed,
                                      const std::string& error_message,
                                      void* context) {
  AudioRendererSinkImpl* audio_renderer_sink =
      static_cast<AudioRendererSinkImpl*>(context);
  SB_DCHECK(audio_renderer_sink);
  SB_DCHECK(audio_renderer_sink->render_callback_);

  audio_renderer_sink->render_callback_->OnError(capability_changed,
                                                 error_message);
}

}  // namespace filter
}  // namespace player
}  // namespace starboard
}  // namespace shared
}  // namespace starboard


text:
title: Dashboard
menu: Dashboard
onpage_menu: false
body_classes: 'modular header-image fullwidth'
content:
    items: '@self.modular'
    order:
        by: default
        dir: asc
        custom:
            - _welcome-section
            - _content
---


text:
package org.emmalanguage
package api.emma

import compiler.FlinkMacro

import scala.language.experimental.macros

object onFlink {

  final def apply[T](e: T): T = macro FlinkMacro.onFlinkImpl1[T]

  final def apply[T](config: String)(e: T): T = macro FlinkMacro.onFlinkImpl2[T]
}


text:
package org.maera.plugin.servlet.util;

/**
 * This utility provides a thread local stack of {@link ClassLoader}s.
 * The current "top" of the stack is the thread's current context class loader.
 * This can be used when implementing delegating plugin {@link java.util.logging.Filter}s or {@link javax.servlet.Servlet}s
 * that need to set the {@link ClassLoader} to the {@link org.maera.plugin.classloader.PluginClassLoader} the filter
 * or servlet is declared in.
 *
 * @since 2.1.0
 * @deprecated Moved to maera-plugins-core: org.maera.plugin.util.ClassLoaderStack. This impl delegates to the new impl.
 */
@Deprecated
public class ClassLoaderStack {
    /**
     * Makes the given classLoader the new ContextClassLoader for this thread, and pushes the current ContextClassLoader
     * onto a ThreadLocal stack so that we can do a {@link #pop} operation later to return to that ContextClassLoader.
     *

     *

     * Passing null is allowed and will act as a no-op. This means that you can safely {@link #pop} a ClassLoader and {@link #push} it back in
     * and it will work safely whether the stack was empty at time of {@link #pop} or not.
     *
     * @param loader The new ClassLoader to set as ContextClassLoader.
     */
    public static void push(ClassLoader loader) {
        org.maera.plugin.util.ClassLoaderStack.push(loader);
    }

    /**
     * Pops the current ContextClassLoader off the stack, setting the new ContextClassLoader to the previous one on the stack.
     *

     *
If the stack is not empty, then the current ClassLoader is replaced by the previous one on the stack, and then returned.

     *
If the stack is empty, then null is returned and the current ContextClassLoader is not changed.

     *

     *
     * @return the previous ContextClassLoader that was just replaced, or null if the stack is empty.
     */
    public static ClassLoader pop() {
        return org.maera.plugin.util.ClassLoaderStack.pop();
    }
}


text:
package org.jboss.hal.client.configuration.subsystem.messaging;

import java.util.Map;

import javax.inject.Inject;

import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest;
import org.jboss.hal.ballroom.form.Form;
import org.jboss.hal.ballroom.form.Form.FinishReset;
import org.jboss.hal.core.CrudOperations;
import org.jboss.hal.core.finder.Finder;
import org.jboss.hal.core.finder.FinderPath;
import org.jboss.hal.core.finder.FinderPathFactory;
import org.jboss.hal.core.mvp.ApplicationFinderPresenter;
import org.jboss.hal.core.mvp.HalView;
import org.jboss.hal.core.mvp.HasPresenter;
import org.jboss.hal.core.mvp.SupportsExpertMode;
import org.jboss.hal.dmr.ModelNode;
import org.jboss.hal.dmr.Property;
import org.jboss.hal.dmr.ResourceAddress;
import org.jboss.hal.dmr.dispatch.Dispatcher;
import org.jboss.hal.meta.MetadataRegistry;
import org.jboss.hal.meta.SelectionAwareStatementContext;
import org.jboss.hal.meta.StatementContext;
import org.jboss.hal.meta.token.NameTokens;
import org.jboss.hal.resources.Ids;
import org.jboss.hal.resources.Names;
import org.jboss.hal.resources.Resources;
import org.jboss.hal.spi.Message;
import org.jboss.hal.spi.MessageEvent;
import org.jboss.hal.spi.Requires;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.jboss.hal.client.configuration.subsystem.messaging.AddressTemplates.*;
import static org.jboss.hal.dmr.ModelDescriptionConstants.HA_POLICY;
import static org.jboss.hal.dmr.ModelDescriptionConstants.MESSAGING_ACTIVEMQ;
import static org.jboss.hal.dmr.ModelDescriptionConstants.SERVER;

public class HaPolicyPresenter
        extends ApplicationFinderPresenter<HaPolicyPresenter.MyView, HaPolicyPresenter.MyProxy>
        implements SupportsExpertMode {

    private static final Logger logger = LoggerFactory.getLogger(HaPolicyPresenter.class);

    private final Dispatcher dispatcher;
    private final CrudOperations crud;
    private final FinderPathFactory finderPathFactory;
    private final MetadataRegistry metadataRegistry;
    private final StatementContext statementContext;
    private final Resources resources;
    private String serverName;
    private HaPolicy haPolicy; // the 'top-level' policy selected in the wizard - not one of the *_COLOCATED_(MASTER|SLAVE) policies

    @Inject
    public HaPolicyPresenter(EventBus eventBus,
            HaPolicyPresenter.MyView view,
            HaPolicyPresenter.MyProxy proxy_,
            Finder finder,
            Dispatcher dispatcher,
            CrudOperations crud,
            FinderPathFactory finderPathFactory,
            MetadataRegistry metadataRegistry,
            StatementContext statementContext,
            Resources resources) {
        super(eventBus, view, proxy_, finder);
        this.dispatcher = dispatcher;
        this.crud = crud;
        this.finderPathFactory = finderPathFactory;
        this.metadataRegistry = metadataRegistry;
        this.statementContext = new SelectionAwareStatementContext(statementContext, () -> serverName);
        this.resources = resources;
    }

    @Override
    protected void onBind() {
        super.onBind();
        getView().setPresenter(this);
    }

    @Override
    public void prepareFromRequest(PlaceRequest request) {
        super.prepareFromRequest(request);
        serverName = request.getParameter(SERVER, null);
    }

    @Override
    public ResourceAddress resourceAddress() {
        return SELECTED_SERVER_TEMPLATE.resolve(statementContext);
    }

    @Override
    public FinderPath finderPath() {
        return finderPathFactory.configurationSubsystemPath(MESSAGING_ACTIVEMQ)
                .append(Ids.MESSAGING_CATEGORY, Ids.asId(Names.SERVER),
                        resources.constants().category(), Names.SERVER)
                .append(Ids.MESSAGING_SERVER_CONFIGURATION, Ids.messagingServer(serverName),
                        Names.SERVER, serverName)
                .append(Ids.MESSAGING_SERVER_SETTINGS, Ids.MESSAGING_SERVER_HA_POLICY,
                        resources.constants().settings(), Names.HA_POLICY);
    }

    @Override
    protected void reload() {
        ResourceAddress address = SELECTED_SERVER_TEMPLATE.resolve(statementContext);
        crud.readChildren(address, HA_POLICY, 2, children -> {
            if (children.isEmpty()) {
                haPolicy = null;
                getView().empty();
            } else {
                Property child = children.get(0);
                haPolicy = HaPolicy.fromResourceName(child.getName());
                getView().update(haPolicy, child.getValue());
            }
        });
    }

    void addHaPolicy() {
        new HaPolicyWizard(resources, (wizard, context) -> context.haPolicy.add(dispatcher, statementContext,
                () -> {
                    MessageEvent.fire(getEventBus(),
                            Message.success(resources.messages().addSingleResourceSuccess(context.haPolicy.type)));
                    reload();
                })).show();
    }

    void saveHaPolicy(HaPolicy haPolicy, Map<String, Object> changedValues) {
        haPolicy.save(changedValues, metadataRegistry, statementContext, crud, this::reload);
    }

    void resetHaPolicy(HaPolicy haPolicy, Form<ModelNode> form) {
        haPolicy.reset(form, metadataRegistry, statementContext, crud, new FinishReset<ModelNode>(form) {
            @Override
            public void afterReset(Form<ModelNode> form) {
                reload();
            }
        });
    }

    void resetHaPolicy() {
        if (haPolicy != null) {
            haPolicy.remove(dispatcher, statementContext, resources, () -> {
                MessageEvent.fire(getEventBus(),
                        Message.success(resources.messages().removeSingletonSuccess(haPolicy.type)));
                reload();
            });
        } else {
            logger.error("Unable to remove HA policy: presenter.haPolicy == null");
        }
    }

    // @formatter:off
    @ProxyCodeSplit
    @Requires({LIVE_ONLY_ADDRESS,
            REPLICATION_COLOCATED_ADDRESS,
            REPLICATION_COLOCATED_MASTER_ADDRESS,
            REPLICATION_COLOCATED_SLAVE_ADDRESS,
            REPLICATION_MASTER_ADDRESS,
            REPLICATION_SLAVE_ADDRESS,
            SHARED_STORE_COLOCATED_ADDRESS,
            SHARED_STORE_COLOCATED_MASTER_ADDRESS,
            SHARED_STORE_COLOCATED_SLAVE_ADDRESS,
            SHARED_STORE_MASTER_ADDRESS,
            SHARED_STORE_SLAVE_ADDRESS})
    @NameToken(NameTokens.MESSAGING_SERVER_HA_POLICY)
    public interface MyProxy extends ProxyPlace<HaPolicyPresenter> {
    }

    public interface MyView extends HalView, HasPresenter<HaPolicyPresenter> {
        void empty();
        void update(HaPolicy haPolicy, ModelNode modelNode);
    }
    // @formatter:on
}


text:
using System.Threading;

namespace Spring.Scheduling
{
	/// <summary>
	///
	/// </summary>
	public interface ITaskExecutor
	{
		/// <summary>
		/// Executes this instance.
		/// </summary>
		void Execute(ThreadStart runnable);
	}
}


text:
require 'goliath/validation/standard_http_errors'
require 'goliath/validation/error'
require 'gorillib/metaprogramming/class_attribute'

module Goliath
  module Validation

    #
    # Style guide:
    #
    # * be careful about interpolating messages into the error response.
    #   Escape anything that might lead to an injection attack.
    # * To quote text, use {}. For example,
    #      raise Apeyeye::ApiCallNotFoundError, "There is no api call at {#{request.path}}. Check the catalog at http://infochimps.com/api to ensure the path is correct. If there is a mismatch, please email help@infochimps.com."
    #   which leads eventually to
    #      {"error":"ApiCallNotFoundError","message":"There is no api call at {/describe/encyclopedic/freebase/list}. Check the catalog at http://infochimps.com/api to ensure the path is correct. If there is a mismatch, please email help@infochimps.com.","status":404}
    #   This is less likely to result in an injection attack, and means that the error is directly parseable.
    #
    # Good error messages have
    #
    # * A problem. States that a problem occurred.
    # * A cause. Explains why the problem occurred.
    # * A solution. Provides a solution so that users can fix the problem.
    #
    # * Relevant      - The message presents a problem that users care about.
    # * Actionable    - Users should either perform an action or change their behavior as the result of the message.
    # * User-centered - The message describes the problem in terms of target user actions or goals, not in terms of what the code is unhappy with.
    # * Brief         - The message is as short as possible, but no shorter.
    # * Clear         - The message uses plain language so that the target users can easily understand problem and solution.
    # * Specific      - The message describes the problem using specific language, giving specific names, locations, and values of the objects involved.
    # * Courteous     - Users shouldn't be blamed or made to feel stupid.
    # * Rare          - Displayed infrequently. Frequently displayed error messages are a sign of bad design.
    #

    # All endpoints must succeed (the given value is
    # returned), or fail (with the
    class Error
      class_attribute :description
      self.description = "Unspecified internal error"
    end

    #
    # Not Found (404) errors
    #
    #
    # Requested item not found:
    # * item isn't in the database, and thus doesn't exist.
    # * item isn't in the database, but might exist
    # Some calls distinguis

    class NotFoundMightBeThereThoughError < NotFoundError
      self.description = "Might not exist, or we might not have it yet. We'll have our robomonkey scrapers check it out."
    end

    #
    # Bad Request (400) Errors
    #
    # Request is ill-formed. Why?
    # * Route doesn't exist
    # * Wrong method (POST, GET, etc)
    # * Validations:
    #   - missing one or more required params
    #   - wrong type for one or more params

    # The request was valid, everything about *handling* the call seemed to go
    # right, but the call itself failed: eg api call to parse the date "Feb 31
    # 2013"
    class RequestProcessError   < BadRequestError
      self.description = "The request was valid, everything about *handling* the call seemed to go right, but the call itself failed. Missing parameters - please check the documentation at http://infochimps.com/api or email help@infochimps.com"
    end

    # Supplied parameters fail validation
    class RequestValidationError < BadRequestError
      self.description = "Invalid parameters - please check the documentation at http://infochimps.com/api or email help@infochimps.com"
    end

    # User did not provide all the of the necessary parameters to complete the call
    class RequiredParamMissingError < RequestValidationError
      self.description = "Missing parameters - please check the documentation at http://infochimps.com/api or email help@infochimps.com"
    end

    class ApiCallNotFoundError < BadRequestError
      self.description = "No endpoint listening at that path. See listing at http://infochimps.com/api"
    end

    #
    # Unauthorized (401) Errors
    #
    # User isn't authorized for this call. Why?
    #
    # * No API key provided.
    # * API key isn't found
    # * API key is found, but disabled or expired
    #
    # Spec says: "Similar to 403 Forbidden, but specifically for use when
    # authentication is possible but has failed or not yet been provided." Even
    # not specifically stated in HTTP spec, the common practice is 401 - For
    # authentication error 403 - For authorization error.
    #
    # We do NOT respond with unauthorized for the following:
    #
    # * API key is fine, but user needs to agree to the license for this call (this is a 403)
    # * Access to eg a protected twitter user (the data is scrubbed from our DB)
    #

    class MissingApikeyError < UnauthorizedError
      self.description = "No _apikey parameter supplied"
    end

    class ApikeyNotFoundError < UnauthorizedError
      self.description = "The _apikey supplied is not in our records. Visit http://infochimps.com/api to register, or email help@infochimps.com"
    end

    #
    # Payment Required (402) Errors
    #
    #

    class AccountBalanceError < PaymentRequiredError
      self.description = "Account limit hit. Please visit your user dashboard on http://infochimps.com or email help@infochimps.com"
    end

    #
    # Forbidden / Rate Limit / NeedsLicense (403) Errors
    #
    #   "The request was a legal request, but the server is refusing to respond to
    #   it. Unlike a 401 Unauthorized response, authenticating will make no
    #   difference."
    #

    # Too many calls for their account level
    class RateLimitExceededError < ForbiddenError
      self.description = "Rate limit exceeded. Please visit http://infochimps.com to increase your user plan, or email help@infochimps.com"
    end

    # Too many ip addresses for their account level
    class IpLimitExceededError < ForbiddenError
      self.description = "Remote host limit exceeded: too many distinct IPs this hour. Please visit http://infochimps.com to increase your user plan, or email help@infochimps.com"
    end

    # apikey is valid, but user needs to click a license or put some $$ down to use this call
    class UserNeedsLicenseError < ForbiddenError
      self.description = "This api call requires a license agreement. Visit http://infochimps.com/api to register, or email help@infochimps.com"
    end

    #
    # Not Acceptable Errors (406)
    #
    # The resource identified by the request is only capable of generating
    # response entities which have content characteristics not acceptable
    # according to the accept headers sent in the request.

    class BogusFormatError < NotAcceptableError
      self.description = "Bad response format specified"
    end

    #
    # Internal Server Errors (500)
    #
    # Errors that are not the fault of the user. Apologize and give them the
    # emergency contact info.

    # The database is not responding, or something. Not the user's fault.
    class DatabaseOnFireError  < InternalServerError
      self.description = "Database on fire! This call failed -- but it's us, not you. Please email help@infochimps.com if this keeps happening."
    end

    # The request succeeded but processing it failed
    class MethodFailedError  < InternalServerError
      self.description = "Request failed"
    end

  end

  #
  # Maps each standard HTTP error code (4xx and 5xx) to a subclass of
  # Goliath::Validation::Error. The error will have the status_code and
  # message correct for that response:
  #
  #     HTTP_ERRORS[400]
  #     # Goliath::Validation::NotFoundError
  #
  # Each class is named for the standard HTTP message, so 504 'Gateway Time-out'
  # becomes a Goliath::Validation::GatewayTimeoutError (except 'Internal Server
  # Error', which becomes InternalServerError not InternalServerErrorError). All non-alphanumeric
  # characters are smushed together, with no upcasing or
  # downcasing.
  #
  HTTP_ERRORS = {}

  HTTP_ERROR_CODES.each do |code, msg|
    klass_name = "#{msg.gsub(/\W+/, '')}Error".gsub(/ErrorError$/, "Error")
    klass = Goliath::Validation.const_get(klass_name)
    HTTP_ERRORS[code] = klass
    klass.description = msg
  end

end


text:
package org.motechproject.event.osgi;

import org.motechproject.commons.api.ApplicationContextServiceReferenceUtils;
import org.motechproject.event.listener.EventListenerRegistryService;
import org.motechproject.event.listener.proxy.EventAnnotationBeanPostProcessor;
import org.motechproject.osgi.web.ApplicationContextTracker;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

/**
 * Tracks the application contexts that are published as OSGi services. These contexts are then scanned for beans annotated
 * as event listeners and registers them in the registry.
 */
public class BlueprintApplicationContextTracker extends ApplicationContextTracker {

    private static final Logger LOGGER = LoggerFactory.getLogger(BlueprintApplicationContextTracker.class);

    private EventAnnotationBeanPostProcessor eventAnnotationBeanPostProcessor;

    /**
     *
     * @param bundleContext the bundle's execution context within the Framework
     * @param listenerRegistryService the service for event listeners.
     */
    public BlueprintApplicationContextTracker(BundleContext bundleContext, EventListenerRegistryService listenerRegistryService) {
        super(bundleContext);
        this.eventAnnotationBeanPostProcessor = new EventAnnotationBeanPostProcessor(listenerRegistryService);
    }

    /**
     * {@inheritDoc}. Additionally it processes event annotations.
     */
    @Override
    public Object addingService(ServiceReference serviceReference) {
        ApplicationContext applicationContext = (ApplicationContext) super.addingService(serviceReference);
        LOGGER.debug("Staring to process " + applicationContext.getDisplayName());

        synchronized (getLock()) {
            if (contextInvalidOrProcessed(serviceReference, applicationContext)) {
                return applicationContext;
            }
            markAsProcessed(applicationContext);
        }

        eventAnnotationBeanPostProcessor.processAnnotations(applicationContext);

        LOGGER.debug("Processed " + applicationContext.getDisplayName());

        return applicationContext;
    }

    /**
     * {@inheritDoc}. Additionally it removes all event listeners registered
     * in the ApplicationContext
     */
    @Override
    public void removedService(ServiceReference reference, Object service) {
        super.removedService(reference, service);
        ApplicationContext applicationContext = (ApplicationContext) service;

        if (ApplicationContextServiceReferenceUtils.isValid(reference)) {
            eventAnnotationBeanPostProcessor.clearListeners(applicationContext);
            synchronized (getLock()) {
                removeFromProcessed(applicationContext);
            }
        }
    }
}


text:
package luddite

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/dimfeld/httptreemux"
	"golang.org/x/tools/godoc/vfs/httpfs"
	"golang.org/x/tools/godoc/vfs/mapfs"
)

const (
	sampleJSONSchema = "{\"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"birthday\": { \"type\": \"string\", \"format\": \"date\"}"
	sampleYAMLSchema = "type: object\nproperties:\n  name: {type: string}\n  birthday: {type: string, format: date}"
)

func TestSchemaHandlerDefaultContentType(t *testing.T) {
	fakeFS := httpfs.New(mapfs.New(map[string]string{
		"v1/schema.json": sampleJSONSchema,
	}))
	v := make(map[string]string)
	v["version"] = "v1"
	v["filepath"] = "schema.json"

	ctx := httptreemux.AddParamsToContext(context.Background(), v)
	req, _ := http.NewRequest("GET", "/", nil)
	req = req.WithContext(ctx)
	rw := httptest.NewRecorder()
	rw.Header().Set(HeaderContentType, ContentTypeJson)

	s := newSchemaHandler(fakeFS)
	s.ServeHTTP(rw, req)
	if ct := rw.Header().Get(HeaderContentType); ct != ContentTypeJson {
		t.Errorf("incorrrect content type negotiated: %s", ct)
	}

	if body := string(rw.Body.String()); body != sampleJSONSchema {
		t.Errorf("JSON serialization failed, got: %s, expected: %s\n", body, sampleJSONSchema)
	}
}

func TestSchemaHandlerOctetStreamContentType(t *testing.T) {
	fakeFS := httpfs.New(mapfs.New(map[string]string{
		"v1/schema.yml": sampleYAMLSchema,
	}))
	v := make(map[string]string)
	v["version"] = "v1"
	v["filepath"] = "schema.yml"

	ctx := httptreemux.AddParamsToContext(context.Background(), v)
	req, _ := http.NewRequest("GET", "/", nil)
	req = req.WithContext(ctx)
	rw := httptest.NewRecorder()
	rw.Header().Set(HeaderContentType, ContentTypeJson)

	s := newSchemaHandler(fakeFS)
	s.ServeHTTP(rw, req)

	if ct := rw.Header().Get(HeaderContentType); ct != ContentTypeOctetStream {
		t.Errorf("incorrrect content type negotiated: %s", ct)
	}

	if body := string(rw.Body.String()); body != sampleYAMLSchema {
		t.Errorf("YAML serialization failed, got: %s, expected: %s\n", body, sampleYAMLSchema)
	}
}

func TestSchemaHandlerGivenInvalidVersionStringLength(t *testing.T) {
	v := make(map[string]string)
	v["version"] = "v"
	ctx := httptreemux.AddParamsToContext(context.Background(), v)
	req, _ := http.NewRequest("GET", "/", nil)
	req = req.WithContext(ctx)
	rw := httptest.NewRecorder()
	rw.Header().Set(HeaderContentType, ContentTypeJson)

	s := newSchemaHandler(nil)
	s.ServeHTTP(rw, req)

	if rw.Code != http.StatusNotFound {
		t.Error("expected 400/Not found")
	}
}

func TestSchemaHandlerGivenInvalidVersionValue(t *testing.T) {
	v := make(map[string]string)
	v["version"] = "w1"
	ctx := httptreemux.AddParamsToContext(context.Background(), v)
	req, _ := http.NewRequest("GET", "/", nil)
	req = req.WithContext(ctx)
	rw := httptest.NewRecorder()
	rw.Header().Set(HeaderContentType, ContentTypeJson)

	s := newSchemaHandler(nil)
	s.ServeHTTP(rw, req)

	if rw.Code != http.StatusNotFound {
		t.Error("expected 400/Not found")
	}
}

func TestSchemaHandlerGivenInvalidVersionNumber(t *testing.T) {
	v := make(map[string]string)
	v["version"] = "v0"
	ctx := httptreemux.AddParamsToContext(context.Background(), v)
	req, _ := http.NewRequest("GET", "/", nil)
	req = req.WithContext(ctx)
	rw := httptest.NewRecorder()
	rw.Header().Set(HeaderContentType, ContentTypeJson)

	s := newSchemaHandler(nil)
	s.ServeHTTP(rw, req)

	if rw.Code != http.StatusNotFound {
		t.Error("expected 400/Not found")
	}
}


text:
/** Teleporter.java
 * 27/giu/2012 14:02:54
 * Last edit: 27/giu/2012 14:02:54
 *
 */

package object.thing;

/**
 * Questa è un'interfaccia di facciata per pillola e telefono.
 */
public interface Teleporter {
	public object.location.Location getLocation();
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.Search.Documents.Indexes.Models
{
    public partial class SearchIndexerCache : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(StorageConnectionString))
            {
                writer.WritePropertyName("storageConnectionString");
                writer.WriteStringValue(StorageConnectionString);
            }
            if (Optional.IsDefined(EnableReprocessing))
            {
                if (EnableReprocessing != null)
                {
                    writer.WritePropertyName("enableReprocessing");
                    writer.WriteBooleanValue(EnableReprocessing.Value);
                }
                else
                {
                    writer.WriteNull("enableReprocessing");
                }
            }
            writer.WriteEndObject();
        }

        internal static SearchIndexerCache DeserializeSearchIndexerCache(JsonElement element)
        {
            Optional<string> storageConnectionString = default;
            Optional<bool?> enableReprocessing = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("storageConnectionString"))
                {
                    storageConnectionString = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("enableReprocessing"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        enableReprocessing = null;
                        continue;
                    }
                    enableReprocessing = property.Value.GetBoolean();
                    continue;
                }
            }
            return new SearchIndexerCache(storageConnectionString.Value, Optional.ToNullable(enableReprocessing));
        }
    }
}


text:
package cn.wayne.mamypoko.cache;

/**
 * Created by Lumia on 2015/4/21.
 */
public interface CacheManager {

    String getString(String url);

    void putString(String url,String value);
}


text:
package com.idea4j.framework.util;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * map utility
 *
 * @author andaicheng
 */
public final class MapUtils {

    private MapUtils() {
    }

    public static boolean isEmpty(final Map<?, ?> map) {
        return map == null || map.isEmpty();
    }

    public static boolean isNotEmpty(final Map<?, ?> map) {
        return !isEmpty(map);
    }

    /**
     *
Reverses a Map<K, V> to Map<V, K>.

     */
    public static <K, V> Map<V, K> reverse(Map<K, V> source) {
        Map<V, K> target = null;
        if (isNotEmpty(source)) {
            target = new LinkedHashMap<>(source.size());
            for (Map.Entry<K, V> entry : source.entrySet()) {
                target.put(entry.getValue(), entry.getKey());
            }
        }
        return target;
    }
}


text:
'use strict';

var path        = require('path');
var jBinary     = require('jbinary');
var audioFormat = require('../format/audio');

var loadAudio = function(audioPath, callback) {
  jBinary.load(audioPath, audioFormat, function(err, jb) {
    if(err) {
      return callback(err);
    }

    var audio;

    try {
      audio = jb.readAll();
    }
    catch(err) {
      return callback(err);
    }

    callback(null, audio);
  });
};

module.exports = loadAudio;

loadAudio(path.resolve(__dirname, '../../data/MAIN.SFX'));


text:
package edu.psu.cse.siis.coal;

/**
 * A fatal analysis exception. This should cause the analysis to stop but it can be caught at a
 * higher level to allow some processing before terminating (closing files, etc.).
 */
public class FatalAnalysisException extends AnalysisException {
  private static final long serialVersionUID = -4890708762379522641L;

  public FatalAnalysisException() {
    super();
  }

  public FatalAnalysisException(String message) {
    super(message);
  }

  public FatalAnalysisException(String message, Throwable cause) {
    super(message, cause);
  }

  public FatalAnalysisException(Throwable cause) {
    super(cause);
  }
}


text:
package org.apache.flink.runtime.minicluster;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.blob.BlobServer;
import org.apache.flink.runtime.dispatcher.DispatcherGateway;
import org.apache.flink.runtime.dispatcher.MemoryArchivedExecutionGraphStore;
import org.apache.flink.runtime.entrypoint.component.DispatcherResourceManagerComponent;
import org.apache.flink.runtime.entrypoint.component.SessionDispatcherResourceManagerComponentFactory;
import org.apache.flink.runtime.heartbeat.HeartbeatServices;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.metrics.MetricRegistry;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.webmonitor.retriever.MetricQueryServiceRetriever;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Supplier;

/**
 * {@link MiniCluster} extension which allows to set a custom {@link HighAvailabilityServices}.
 */
public class TestingMiniCluster extends MiniCluster {

	private final int numberDispatcherResourceManagerComponents;

	private final boolean localCommunication;

	@Nullable
	private final Supplier<HighAvailabilityServices> highAvailabilityServicesSupplier;

	public TestingMiniCluster(
			TestingMiniClusterConfiguration miniClusterConfiguration,
			@Nullable Supplier<HighAvailabilityServices> highAvailabilityServicesSupplier) {
		super(miniClusterConfiguration);
		this.numberDispatcherResourceManagerComponents = miniClusterConfiguration.getNumberDispatcherResourceManagerComponents();
		this.highAvailabilityServicesSupplier = highAvailabilityServicesSupplier;
		this.localCommunication = miniClusterConfiguration.isLocalCommunication();
	}

	public TestingMiniCluster(TestingMiniClusterConfiguration miniClusterConfiguration) {
		this(miniClusterConfiguration, null);
	}

	@Nonnull
	@Override
	public Collection<DispatcherResourceManagerComponent<?>> getDispatcherResourceManagerComponents() {
		return super.getDispatcherResourceManagerComponents();
	}

	@Nonnull
	@Override
	public CompletableFuture<Void> terminateTaskExecutor(int index) {
		return super.terminateTaskExecutor(index);
	}

	@Override
	public void startTaskExecutor() throws Exception {
		super.startTaskExecutor();
	}

	@Override
	protected boolean useLocalCommunication() {
		return localCommunication;
	}

	@Override
	protected HighAvailabilityServices createHighAvailabilityServices(Configuration configuration, Executor executor) throws Exception {
		if (highAvailabilityServicesSupplier != null) {
			return highAvailabilityServicesSupplier.get();
		} else {
			return super.createHighAvailabilityServices(configuration, executor);
		}
	}

	@Override
	protected Collection<? extends DispatcherResourceManagerComponent<?>> createDispatcherResourceManagerComponents(
			Configuration configuration,
			RpcServiceFactory rpcServiceFactory,
			HighAvailabilityServices haServices,
			BlobServer blobServer,
			HeartbeatServices heartbeatServices,
			MetricRegistry metricRegistry,
			MetricQueryServiceRetriever metricQueryServiceRetriever,
			FatalErrorHandler fatalErrorHandler) throws Exception {
		SessionDispatcherResourceManagerComponentFactory dispatcherResourceManagerComponentFactory = createTestingDispatcherResourceManagerComponentFactory();

		final List<DispatcherResourceManagerComponent<?>> result = new ArrayList<>(numberDispatcherResourceManagerComponents);

		for (int i = 0; i < numberDispatcherResourceManagerComponents; i++) {
			result.add(
				dispatcherResourceManagerComponentFactory.create(
					configuration,
					rpcServiceFactory.createRpcService(),
					haServices,
					blobServer,
					heartbeatServices,
					metricRegistry,
					new MemoryArchivedExecutionGraphStore(),
					metricQueryServiceRetriever,
					fatalErrorHandler));
		}

		return result;
	}

	@Override
	public CompletableFuture<DispatcherGateway> getDispatcherGatewayFuture() {
		return super.getDispatcherGatewayFuture();
	}

	private SessionDispatcherResourceManagerComponentFactory createTestingDispatcherResourceManagerComponentFactory() {
		return new SessionDispatcherResourceManagerComponentFactory(
			SessionDispatcherWithUUIDFactory.INSTANCE,
			StandaloneResourceManagerWithUUIDFactory.INSTANCE);
	}
}


text:
package com.amihaiemil.eoyaml;

import java.util.UUID;

import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.mockito.Mockito;

/**
 * Unit tests for {@link EmptyYamlMapping}.
 *
 * @author Andrew Newman
 * @version $Id$
 * @since 5.1.17
 */
public final class EmptyYamlMappingTest {

    /**
     * Random comment.
     */
    public static final String ANY_COMMENT = UUID.randomUUID().toString();

    /**
     * Random key.
     */
    public static final String ANY_KEY = UUID.randomUUID().toString();

    /**
     * Able to get comment.
     */
    @Test
    public void returnsCommentFromDecoratedObject() {
        final YamlMapping mapping = Mockito.mock(YamlMapping.class);
        final YamlNode node = Mockito.mock(YamlNode.class);
        final Comment comment = new BuiltComment(node, ANY_COMMENT);
        Mockito.when(mapping.comment()).thenReturn(comment);
        YamlMapping emptyMapping = new EmptyYamlMapping(mapping);
        MatcherAssert.assertThat(
                emptyMapping.comment().value(),
                Matchers.equalTo(ANY_COMMENT)
        );
    }

    /**
     * Has no elements in the mapping - no keys.
     */
    @Test
    public void hasEmptyKeys() {
        final YamlMapping mapping = Mockito.mock(YamlMapping.class);
        YamlMapping emptyMapping = new EmptyYamlMapping(mapping);
        MatcherAssert.assertThat(
                emptyMapping.keys().size(),
                Matchers.is(0)
        );
    }

    /**
     * Has no elements in the mapping - no values.
     */
    @Test
    public void hasNoValues() {
        final YamlMapping mapping = Mockito.mock(YamlMapping.class);
        YamlMapping emptyMapping = new EmptyYamlMapping(mapping);
        MatcherAssert.assertThat(
                emptyMapping.value(ANY_KEY),
                Matchers.is(Matchers.nullValue())
        );
    }
}


text:
class TransactionData;

class ReconcileItem : public BStringItem
{
public:
	ReconcileItem(const TransactionData &trans);
	~ReconcileItem(void);
	void DrawItem(BView *owner, BRect frame, bool complete = false);
	TransactionData *GetTransaction(void) { return &fTransaction; }
	void SetReconciled(bool value);
	bool IsReconciled(void) const;

	void SyncToTransaction(void);
	void RevertTransaction(void) { fTransaction.SetStatus(TRANS_OPEN); }
private:
	TransactionData fTransaction;
	uint8 fValue;
};

#endif


text:
package org.apache.arrow.vector.ipc.message;

/**
 * Interface for Arrow IPC messages (https://arrow.apache.org/docs/format/IPC.html).
 */
public interface ArrowMessage extends FBSerializable, AutoCloseable {

  int computeBodyLength();

  <T> T accepts(ArrowMessageVisitor<T> visitor);

  /** Returns the flatbuffer enum value indicating the type of the message. */
  byte getMessageType();

  /**
   * Visitor interface for implementations of {@link ArrowMessage}.
   *
   * @param <T> The type of value to return after visiting.
   */
  interface ArrowMessageVisitor<T> {
    T visit(ArrowDictionaryBatch message);

    T visit(ArrowRecordBatch message);
  }
}


text:
@implementation GBTypedefBlockData

+(id)typedefBlockWithName:(NSString *)name returnType: (NSString *) returnType parameters:(NSArray *)parameters
{
    return [[self alloc] initWithName:name returnType: (NSString *) returnType parameters: parameters];
}

-(id)initWithName:(NSString *)name returnType: (NSString *) returnType parameters: (NSArray *) parameters
{
    self = [super init];
    if(self)
    {
        _blockName = [name copy];
        _parameters = parameters;
        _returnType = returnType;
    }
    return self;
}

- (NSString *)description {
    return self.nameOfBlock;
}

- (BOOL)isTopLevelObject {
    return self.parentObject == nil;
}

- (NSString *)debugDescription {
    return [NSString stringWithFormat:@"block %@%@\n%@", _returnType, _blockName, _parameters.debugDescription];
}

- (NSString *) htmlParameterList {
    __block NSString *output = @"";
    for (GBTypedefBlockArgument *param in self.parameters) {
        NSString *formattedClassName = param.className;
        if ([param.href length] > 0) {
            formattedClassName = [NSString stringWithFormat: @"%@", param.href, formattedClassName];
        }
        output = [output stringByAppendingFormat: @"%@%@ %@", ([output length] > 0 ? @", " : @""), formattedClassName, param.name];
    }
    return output;
}

@synthesize nameOfBlock = _blockName;
@synthesize parameters = _parameters;
@synthesize returnType = _returnType;

@end


text:
django_import_excel
===================

The goal of this module is to import excel data into multiple tables.  The first row of an excel sheet that will be
imported serves as field identifier.  It is possible to generate multiple database records in different tables from one single
excel data row.

The module expects the following data structures and callback function in order to be able to correctly map excel fields
to database fields.

1. Indication which excel fields are mandatory (set_excelfield_mandatory)

It is a simple dictionary with as key the excel field name and as data True (info is mandatory) or False (info is not mandatory)

2. Field validation rules

Again a dictionary with as key the excel field name and as data a function with the following signature :

callback (self,row,val)

self is the conversion object itself (see later), row is a list with values of the current excel row and val is the value of the
current excel cell.

3. Mapping rules

The mapping rules have to expressed in the form a list variable with 5 elements :

- First element : path name to application e.g. auth
- Second element : name of the table e.g. User
- Third element : is again a list of two elements, first element is again a list of key mapping elements and ssecond element is a list of non key mapping elements (see further)
- Fourth element : creation callback
- Fifth element : set to False if a record maybe created (if record with the key(s) is not found or to True if a record may not be created.

mapping elements are always a list of 3 items, the first item is the excel filename, the second element is the callback function to translate excel field to database field and the third element is the field name in the database.

key mapping elements are use to determine whether a record already exists in the database or not (AND function applies if multiple are given)

The callback function takes 3 arguments : self, row (list of values) and val (the value from excel) and return the value as it has to be written into the database.

The create callback takes 3 arguments : self, the model reference and the row (list of values) and has to return the created record instance.  The callback can return None in case of an error.


text:
//
//  UIView+Circle.h
//  testCircle
//
//  Created by yanghaha on 15/12/4.
//  Copyright © 2015年 yanghaha. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIView (Circle)

#if TARGET_INTERFACE_BUILDER
#else
#endif

/**
 是否显示为圆圈
 */
@property (nonatomic) IBInspectable BOOL circle;
/**
 圆圈半径
 */
@property (nonatomic) IBInspectable CGFloat cornerRadius;
/**
 边框的宽度
 */
@property (nonatomic) IBInspectable CGFloat borderWidth;
/**
 边框的颜色
 */
@property (nonatomic) IBInspectable UIColor *borderColor;

@end


text:
import logging
import os
import re
import subprocess

LOGGER = logging.getLogger(__package__)

class PgError(subprocess.CalledProcessError):
    def __init__(self, returncode=None, cmd=None, output=None, msg=None):
        self.returncode = returncode
        self.cmd = cmd
        self.output = output
        self.msg = msg

    def __str__(self):
        if self.msg:
            return self.msg
        else:
            return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)

def _make_cmd(*args):
    """Normalize args list that may contain empty values or tuples.

    Flatten tuples and lists in the args list and remove any values that are
    None or the empty string.

    :param args:
    :return: processed list of command arguments
    """
    cmd = []
    for a in args:
        if type(a) == tuple or type(a) == list:
            for sub_a in a:
                cmd.append(sub_a)
        else:
            cmd.append(a)
    return [a for a in cmd if a != '' and a is not None]

def _optional(*args):
    """Return *args if no element is the empty string or None.

    Otherwise, return an empty string.

    :param args:
    :return: *args or ''
    """
    for a in args:
        if a == '' or a is None:
            return ''
    return args

def run_pg_command(cmd, database, conn_info):
    """Wrapper around subprocess.checkout_output to report errors properly.

    database and conn_info are used only for error-reporting.

    Raises a PgError exception if the command fails.

    :return: output of cmd as a str
    """
    LOGGER.info('Will run: {}'.format(' '.join(cmd)))
    try:
        result = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        if not conn_info:
            conn_info_str = 'conn_info: none'
        else:
            conn_info_str = 'conn_info: {}'.format(conn_info)
        if not database:
            database_str = 'database: none'
        else:
            database_str = 'database: {}'.format(database)
        context_str = '{}, {}'.format(database_str, conn_info_str)
        msg = ('Subprocess failed, cmd was `{cmd}` ({ctx}), '
               'result was `{code}`, output was `{output}`')
        raise PgError(msg=msg.format(cmd=' '.join(cmd), ctx=context_str,
                                     code=e.returncode, output=e.output),
                      cmd=cmd, returncode=e.returncode)

    return result.decode('utf-8')

def psql(stmt, database=None, conn_info={}):
    """Execute a statement against a PostgreSQL database; return output.

    The `psql` command can be overridden via the `PSQL_CMD` environment
    variable (but take a look at the switches that are used, below). N.B.: the
    overriding command is split on whitespace before use.

    If the statement terminates with an error, an exception is raised.

    :param stmt: SQL statement
    :param database: database to connect to (else same as user)
    :param conn_info: dict of 'hostname', 'port', and 'username'
    :return: raw stdout from psql as a unicode str
    """
    if '"' in stmt:
        raise ValueError('Double-quote not allowed ')

    cmd = _make_cmd(os.environ.get('PSQL_CMD', 'psql').split(),
                    '-t',  # tuples only
                    '-v', 'ON_ERROR_STOP=1',
                    _optional('-U', conn_info.get('username', None)),
                    _optional('-h', conn_info.get('hostname', None)),
                    _optional('-p', conn_info.get('port', None)),
                    _optional('-d', database or conn_info.get('username',
                                                              None)),
                    '-c', '{}'.format(stmt))

    return run_pg_command(cmd, database, conn_info)

def pg_dump(database, filename, schemas=None, conn_info={}, empty=False):
    """Execute pg_dump command.

    If the `schemas` collection is present and non-empty, then for all
    non-None schemas in the collection, the database dump is
    restricted to those schemas; otherwise, there is no restriction by
    schema.

    If the `empty` parameter is True, the dump will be almost entirely
    empty, because all schemas will be excluded. I.e. the backup will be
    usable only for reconstituting a database with nothing in it, the idea
    being that schema-containing backups can be subsequently loaded into it.

    The `pg_dump` command can be overridden via the `PG_DUMP_CMD` environment
    variable (but take a look at the switches that are used, below). N.B.: the
    overriding command is split on whitespace before use.

    :param database:
    :param filename:
    :param schemas:
    :param empty: just backup the database proper, no schemas
    :param conn_info: dict of 'username', 'hostname', and 'port'
    :return: None
    """
    cmd = _make_cmd(os.environ.get('PG_DUMP_CMD', 'pg_dump').split(),
                    '--format=c',  # compressed format
                    _optional('-U', conn_info.get('username', None)),
                    _optional('-h', conn_info.get('hostname', None)),
                    _optional('-p', conn_info.get('port', None)),
                    '-d', database,
                    '-f', filename)

    if empty:
        if schemas:
            raise ValueError('non-None schemas incompatible with `empty`')
        for schema in get_schemas(database, conn_info):
            cmd.append('-N')
            cmd.append(schema)

    if schemas:
        for schema in schemas:
            cmd.append('-n')
            cmd.append(schema)

    run_pg_command(cmd, database, conn_info)

def pg_dumpall_globals(filename, conn_info):
    """Execute pg_dumpall command to dump globals.

    The `pg_dumpall` command can be overridden via the `PG_DUMPALL_CMD`
    environment variable (but take a look at the switches that are used, below).
    N.B.: the overriding command is split on whitespace before use.

    :param filename:
    :param conn_info: dict of 'hostname', 'port', and 'username'
    :return: None
    """
    cmd = _make_cmd(os.environ.get('PG_DUMPALL_CMD', 'pg_dumpall').split(),
                    _optional('-U', conn_info.get('username', None)),
                    _optional('-h', conn_info.get('hostname', None)),
                    _optional('-p', conn_info.get('port', None)),
                    '--globals-only',
                    '--database=template1',
                    '-f', filename)
    run_pg_command(cmd, None, conn_info)

def pg_restore(filename, database=None, conn_info={}):
    """Execute pg_restore command.

    This is really only to facilitate tests.

    The `pg_restore` command can be overridden via the `PG_RESTORE_CMD`
    environment variable (but take a look at the switches that are used, below).
    N.B.: the overriding command is split on whitespace before use.

    If `database` is None, `pg_restore` will connect to `template1` and
    create whatever database is specified in the dump file. Otherwise,
    `pg_restore` will connect to the specified database and restore into it.

    To clarify the previous paragraph, `database` should NOT be None if the
    backup file was created with one or more `-n/--namespace` switches to
    specify schemas. Backups created in this way do not reference a particular
    database, and the restore needs to be performed into a specified database.

    :param filename: input dump file path
    :param database: database name to create and restore into (or None)
    :param conn_info: dict of 'hostname', 'port', and 'username'
    :return:
    """
    if not database:
        database = 'template1'
    cmd = _make_cmd(os.environ.get('PG_RESTORE_CMD', 'pg_restore').split(),
                    _optional('-U', conn_info.get('username', None)),
                    _optional('-h', conn_info.get('hostname', None)),
                    _optional('-p', conn_info.get('port', None)),
                    '--create',
                    '-d', database,
                    filename)

    results = run_pg_command(cmd, database, conn_info)
    return results

def get_schemas(database, conn_info):
    """List all regular schemas in the specified database.

    Return schemas normally returned by `\dn` in psql, i.e. all schemas
    except 'pg_temp_1', 'pg_toast', 'pg_toast_temp_1', 'pg_catalog', and
    'information_schema'.

    :param database: name of database
    :param conn_info: dict of 'hostname', 'port', and 'username'
    :return: list of schemas
    """
    cmd = ("select schema_name from information_schema.schemata"
           " where schema_name !~ '^(pg_temp.*)|(pg_toast*)|(pg_catalog)"
           "|(information_schema)$'")
    psql_output = psql(cmd, database=database, conn_info=conn_info)
    return [x.strip() for x in psql_output.split('\n') if x.strip()]

def get_databases(conn_info):
    """Return all regular databases in the PostgreSQL database.

    The `template0`, `template1`, and `postgres` are excluded.

    Arguably, `template1` should be included, because theoretically
    the user could customize it. However, we don't do that (yet).

    Also, although it is conventional that the founding superuser
    is named `postgres` and owns a similarly named database, this
    is not carved in stone.

    :param conn_info: dict of 'hostname', 'port', and 'username'
    """
    sql = ("select datname from pg_database "
           "where datname not in ('template0', 'template1', 'postgres')")
    psql_output = psql(sql, conn_info=conn_info)
    return [x.strip() for x in psql_output.split('\n') if x]

def filter_collection(collection, include=None, exclude=None):
    """Filter collection based on include and exclude regexps.

    The regexp patterns are not implicitly anchored at the beginning of
    strings (i.e. `search` is used, rather than `match`). E.g.
    'abc' will match '_abc_' as well as 'abcdef'.

    :return: set of matching collection elements
    """
    matches = set()
    if include:
        include_pat = re.compile(include)
    else:
        include_pat = None
    if exclude:
        exclude_pat = re.compile(exclude)
    else:
        exclude_pat = None

    for element in collection:
        if include_pat and not re.search(include_pat, element):
            continue  # Do not include this database; failed to match include
        if exclude_pat and re.search(exclude_pat, element):
            continue  # Do not include this database; matched exclude
        matches.add(element)

    return matches

def matching_databases(conn_info, include=None, exclude=None):
    """Return databases matching `include` and not matching `exclude`."""
    return filter_collection(get_databases(conn_info), include, exclude)

class SchemaCriteria(object):
    """Encapsulate schema selection criteria"""
    def __init__(self, database, conn_info, include=None, exclude=None):
        self.database = database
        self.conn_info = conn_info
        self.include = include
        self.exclude = exclude

def matching_schemas(schema_criteria):
    """Return schemas in database matching `include`/not matching `exclude`

    :param SchemaCriteria schema_criteria: database, conn_info, and inclusion
    and exclusion patterns
    :return: set of matching schema names in the database
    """
    return filter_collection(get_schemas(schema_criteria.database,
                                         schema_criteria.conn_info),
                             schema_criteria.include,
                             schema_criteria.exclude)


text:
// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---------------------------------------------------------------------------
//
// The contents of this file must follow a specific format in order to
// support the CEF translator tool. See the translator.README.txt file in the
// tools directory for more information.
//

#ifndef CEF_INCLUDE_CEF_TASK_H_
#define CEF_INCLUDE_CEF_TASK_H_

#include "include/cef_base.h"

typedef cef_thread_id_t CefThreadId;

///
// Implement this interface for asynchronous task execution. If the task is
// posted successfully and if the associated message loop is still running then
// the Execute() method will be called on the target thread. If the task fails
// to post then the task object may be destroyed on the source thread instead of
// the target thread. For this reason be cautious when performing work in the
// task object destructor.
///
/*--cef(source=client,no_debugct_check)--*/
class CefTask : public virtual CefBaseRefCounted {
 public:
  ///
  // Method that will be executed on the target thread.
  ///
  /*--cef()--*/
  virtual void Execute() = 0;
};

///
// Class that asynchronously executes tasks on the associated thread. It is safe
// to call the methods of this class on any thread.
//
// CEF maintains multiple internal threads that are used for handling different
// types of tasks in different processes. The cef_thread_id_t definitions in
// cef_types.h list the common CEF threads. Task runners are also available for
// other CEF threads as appropriate (for example, V8 WebWorker threads).
///
/*--cef(source=library)--*/
class CefTaskRunner : public virtual CefBaseRefCounted {
 public:
  ///
  // Returns the task runner for the current thread. Only CEF threads will have
  // task runners. An empty reference will be returned if this method is called
  // on an invalid thread.
  ///
  /*--cef()--*/
  static CefRefPtr<CefTaskRunner> GetForCurrentThread();

  ///
  // Returns the task runner for the specified CEF thread.
  ///
  /*--cef()--*/
  static CefRefPtr<CefTaskRunner> GetForThread(CefThreadId threadId);

  ///
  // Returns true if this object is pointing to the same task runner as |that|
  // object.
  ///
  /*--cef()--*/
  virtual bool IsSame(CefRefPtr<CefTaskRunner> that) = 0;

  ///
  // Returns true if this task runner belongs to the current thread.
  ///
  /*--cef()--*/
  virtual bool BelongsToCurrentThread() = 0;

  ///
  // Returns true if this task runner is for the specified CEF thread.
  ///
  /*--cef()--*/
  virtual bool BelongsToThread(CefThreadId threadId) = 0;

  ///
  // Post a task for execution on the thread associated with this task runner.
  // Execution will occur asynchronously.
  ///
  /*--cef()--*/
  virtual bool PostTask(CefRefPtr<CefTask> task) = 0;

  ///
  // Post a task for delayed execution on the thread associated with this task
  // runner. Execution will occur asynchronously. Delayed tasks are not
  // supported on V8 WebWorker threads and will be executed without the
  // specified delay.
  ///
  /*--cef()--*/
  virtual bool PostDelayedTask(CefRefPtr<CefTask> task, int64 delay_ms) = 0;
};

///
// Returns true if called on the specified thread. Equivalent to using
// CefTaskRunner::GetForThread(threadId)->BelongsToCurrentThread().
///
/*--cef()--*/
bool CefCurrentlyOn(CefThreadId threadId);

///
// Post a task for execution on the specified thread. Equivalent to
// using CefTaskRunner::GetForThread(threadId)->PostTask(task).
///
/*--cef()--*/
bool CefPostTask(CefThreadId threadId, CefRefPtr<CefTask> task);

///
// Post a task for delayed execution on the specified thread. Equivalent to
// using CefTaskRunner::GetForThread(threadId)->PostDelayedTask(task, delay_ms).
///
/*--cef()--*/
bool CefPostDelayedTask(CefThreadId threadId,
                        CefRefPtr<CefTask> task,
                        int64 delay_ms);

#endif  // CEF_INCLUDE_CEF_TASK_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DataBaseLayer;

namespace TSUILayer.Views.Sales
{
    /// <summary>
    /// Interaction logic for JobCardAView.xaml
    /// </summary>
    public partial class JobCardAView : UserControl
    {
        DataLayer data = null;
        //public static JobCardAView _jobAInstance = null;
        JOB_CARD jobCard = new JOB_CARD();

        public JobCardAView()
        {
            InitializeComponent();
            data = DataLayer.Instance;
            //_jobAInstance = this;
        }

        private void btnAddComplaint_Click(object sender, RoutedEventArgs e)
        {
            JOB_COMPLAINT complaint = new JOB_COMPLAINT();
            complaint.ACTION_TAKEN = txtActionOnComplaint.Text;
            complaint.ACTUAL_COMPLAINT = txtComplaint.Text;
            complaint.LABOUR_CHARGES = Convert.ToDecimal(txtLabourEstimation.Text);
            jobCard.JOB_COMPLAINTs.Add(complaint);

            gridComplaint.ItemsSource = jobCard.JOB_COMPLAINTs.Select((s, i) => new { SlNo = ++i, Complaint = s.ACTUAL_COMPLAINT, Action = s.ACTION_TAKEN, Charge = s.LABOUR_CHARGES }).ToList();

            txtActionOnComplaint.Clear();
            txtComplaint.Clear();
            txtLabourEstimation.Clear();
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            MainWindow._mainInstance.frmContent.NavigationService.Navigate(new Uri("Views/Service/JobCardForSparesView.xaml", UriKind.Relative));
            //string tractorApp = string.Empty;
            //TractorAppGrid.Children.OfType<CheckBox>().Where(s => s.IsChecked ?? false).All(s => { tractorApp += s.Content.ToString() + ","; return true; });

            //jobCard.SERIAL_NUMBER = Convert.ToInt32(txtJobCardSerialNo.Text);
            //jobCard.ESTIMATED_COST = Convert.ToDecimal(txtEstimatedCost.Text);
            //jobCard.SERVICE_COUPON_NO = Convert.ToInt32(txtServiceCouponNo.Text);
            //jobCard.TRACTOR_APPLICATION = tractorApp.Remove(tractorApp.Length - 1);
            //jobCard.IS_ACCEDENTAL = chkAccidental.IsChecked;
            //jobCard.IS_MOBILESERVICE = chkMobileService.IsChecked;
            //jobCard.IS_PAID = chkPaid.IsChecked;
            //jobCard.IS_SERVICECLINIC = chkServiceClinic.IsChecked;
            //jobCard.ESTIMATED_DELIVERY = dateEsimatedDelivery.SelectedDate;
            //jobCard.DATETIME_IN = dateTimeIn.SelectedDate;
            //jobCard.SERVICE_STARTDATETIME = dateTimeServiceStart.SelectedDate;
            //jobCard.SERVICE_ENDDATETIME = dateTimeServiceFinish.SelectedDate;
            jobCard.REPEAT_FIR_DETAIL = txtRepeat_PreviousFIRDetail.Text;

            new JobCardBView(jobCard);
        }

    }
}