text:
/* Pebble Slider strictly-enforced styles */

/* https://css-tricks.com/specifics-on-css-specificity/ */

span.pebble-slider {
    display: inline-block !important;
    position: relative !important;
}

span.pebble-slider span.ps-subwrap {
    background: none !important;
    border: none !important;
    display: block !important;
    height: 100% !important;
    left: 0 !important;
    margin: 0 !important;
    padding: 0 !important;
    position: absolute !important;
    top: 0 !important;
    width: 100% !important;
}

span.pebble-slider span.ps-range-base {
    background: none !important;
    border: none !important;
    height: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
    width: 100% !important;
}

span.pebble-slider span.ps-range-aligner {
    background: none !important;
    border: none !important;
    height: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
    /* position relative allows 100% height */
    position: relative !important;
    vertical-align: middle !important;
    width: 100% !important;
}

span.pebble-slider span.ps-range-sizer {
    background: none !important;
    border: none !important;
    display: block !important;
    padding: 0 !important;
    position: relative !important;
}

span.pebble-slider span.ps-range-rail {
    bottom: 0 !important;
    display: block !important;
    left: 0 !important;
    height: auto !important;
    margin: 0 !important;
    overflow: hidden !important;
    padding: 0 !important;
    position: absolute !important;
    right: 0 !important;
    top: 0 !important;
    width: auto !important;
}

span.pebble-slider span.ps-range-limiter {
    background: none !important;
    border: none !important;
    display: block !important;
    margin: 0 !important;
    padding: 0 !important;
    position: absolute !important;
}

span.pebble-slider span.ps-range-negative-spectrum-bar,
span.pebble-slider span.ps-range-positive-spectrum-bar,
span.pebble-slider span.ps-range-bar {
    display: block !important;
    margin: 0 !important;
    padding: 0 !important;
    position: absolute !important;
}

span.pebble-slider span.ps-range-negative-spectrum-bar,
span.pebble-slider span.ps-range-positive-spectrum-bar {
    border: solid transparent 0 !important;
}

span.pebble-slider span.ps-toggle-overlay-and-limiter {
    background: none !important;
    border: none !important;
    display: block !important;
    margin: 0 !important;
    padding: 0 !important;
    position: absolute !important;
}

span.pebble-slider span.ps-toggle-base {
    background: none !important;
    border: none !important;
    width: 100% !important;
    height: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
}

span.pebble-slider span.ps-toggle-rail {
    background: none !important;
    border: none !important;
    height: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
    position: relative !important;
    vertical-align: middle !important;
    width: 100% !important;
}

span.pebble-slider span.ps-toggle-neck {
    display: block !important;
    position: absolute !important;
}

span.pebble-slider.ps-horizontal-type span.ps-range-sizer {
    width: 100% !important;
    margin: 0 !important;
}

span.pebble-slider.ps-horizontal-type span.ps-range-limiter {
    bottom: 0 !important;
    top: 0 !important;
}

span.pebble-slider.ps-horizontal-type span.ps-range-negative-spectrum-bar,
span.pebble-slider.ps-horizontal-type span.ps-range-positive-spectrum-bar {
    bottom: 0 !important;
    height: auto !important;
    top: 0 !important;
    width: 0;
}

span.pebble-slider.ps-horizontal-type span.ps-range-negative-spectrum-bar {
    right: 50%;
}

span.pebble-slider.ps-horizontal-type span.ps-range-positive-spectrum-bar {
    left: 50%;
}

span.pebble-slider.ps-horizontal-type span.ps-range-bar {
    bottom: 0 !important;
    height: auto !important;
    left: auto !important;
    top: 0 !important;
    width: 150% !important;
}

span.pebble-slider.ps-horizontal-type span.ps-toggle-overlay-and-limiter {
    bottom: 0 !important;
    top: 0 !important;
}

span.pebble-slider.ps-horizontal-type span.ps-range-base,
span.pebble-slider.ps-horizontal-type span.ps-toggle-base {
    display: table !important;
}

span.pebble-slider.ps-horizontal-type span.ps-range-aligner,
span.pebble-slider.ps-horizontal-type span.ps-toggle-rail {
    display: table-cell !important;
}

span.pebble-slider.ps-horizontal-type span.ps-toggle-neck {
    bottom: auto !important;
    right: auto !important;
    top: auto !important;
}

span.pebble-slider.ps-vertical-type span.ps-range-sizer {
    height: 100% !important;
    margin: 0 auto !important;
}

span.pebble-slider.ps-vertical-type span.ps-range-limiter {
    left: 0 !important;
    right: 0 !important;
}

span.pebble-slider.ps-vertical-type span.ps-range-negative-spectrum-bar,
span.pebble-slider.ps-vertical-type span.ps-range-positive-spectrum-bar {
    left: 0 !important;
    right: 0 !important;
    width: auto !important;
}

span.pebble-slider.ps-vertical-type span.ps-range-negative-spectrum-bar {
    top: 50%;
}

span.pebble-slider.ps-vertical-type span.ps-range-positive-spectrum-bar {
    bottom: 50%;
}

span.pebble-slider.ps-vertical-type span.ps-range-bar {
    bottom: auto !important;
    height: 150% !important;
    left: 0 !important;
    right: 0 !important;
    width: auto !important;
}

span.pebble-slider.ps-vertical-type span.ps-toggle-overlay-and-limiter {
    left: 0 !important;
    right: 0 !important;
}

span.pebble-slider.ps-vertical-type span.ps-range-base,
span.pebble-slider.ps-vertical-type span.ps-range-aligner,
span.pebble-slider.ps-vertical-type span.ps-toggle-base,
span.pebble-slider.ps-vertical-type span.ps-toggle-rail {
    display: block !important;
}

span.pebble-slider.ps-vertical-type span.ps-toggle-neck {
    top: auto !important;
    left: 50% !important;
    right: auto !important;
}

span.pebble-slider span.hidden {
    visibility: hidden !important;
}


text:
<META http-equiv="content-type" content="text/html;charset=iso-8859-9"/><meta name="viewport" content="width=device-width, initial-scale=1"><title>ac</title> <link rel="stylesheet"  href="css/jquery.mobile-1.2.0.css" />

MUSTAFA AKÝF EFENDÝ (Amasyalý)

Geri

On sekizinci yüzyýlda Anadolu'da yetiþen ilim ve gönül ehlinden. Ýsmi, Mustafa bin Ebu
Muhammed Bayram Efendi el-Merzifoni'dir. 1686 (H.1098) senesinde Amasya'da doðdu.
1760 (H.1173) senesinde Amasya'da vefat etti. Kabri, Amasya'da surlarýn dýþýndaki
kabristanýn kýble tarafýndadýr.

Ýlim ehli asil bir aileye mensub olan Mustafa Akif Efendi, küçük yaþta ilim tahsiline baþladý.
Zamanýnýn ileri gelen alimlerinden akli ve nakli ilimleri tahsil etti. Þeyh Muhammed
Amasi'nin babasý Abdullah Efendi ile Kazabadi ve Remzi el-Kayseri ilim tahsil ettiði
alimlerin baþýnda gelirler. Tahsil için zamanýn çeþitli ilim merkezlerini gezdi. Kahire'ye

giderek, Arabi ilimler ile hadis ilmini tahsil etti. Burada özellikle Sahih-i Buhari, Sahih-i
Müslim ve diðer sahih hadis-i þerif kitaplarýný okudu. Ebü'l-Ýzz el-Acemi ona hadis-i þerif
okutmakla ilgili icazet verdi.

Üç defa hacca giden Mustafa Akif Efendi, hac esnasýnda çeþitli Ýslam memleketlerinden
gelen alim ve velilerle görüþüp, onlarýn meclis ve sohbetlerinde bulundu. Akli ve nakli
ilimlerde derin alim olduktan sonra memleketi olan Amasya'ya döndü. Sultan Bayezid
Medresesine müderris tayin edilip ders okuttu ve talebe yetiþtirdi. Daha sonra uzun müddet
Amasya Müftisi olarak vazife yaptý. Gerek müderisliði, gerek müftiliði sýrasýnda insanlara
Ýslam dininin emir ve yasaklarýný anlatýp onlarýn iki cihan saadetine kavuþmalarýna vesile
oldu.

Yaþlanýnca müftilikten ayrýldý. Ýlme ve müslümanlara hizmeti sebebiyle, Þeyhülislam
Mustafa Efendi kendisine, Süleymaniye müderrisliði payesini gönderdi. Ömrünün sonunda
insanlardan uzak bir hayat yaþamayý tercih eden Mustafa Akif Efendi, ilim ve ibadetle
meþgul oldu. Tasavvuf yoluna girip bu yolda ilerledi. Onda manevi haller ve kerametler
görüldü. Ýnsanlar ona, gördükleri bu haller sebebiyle deli ve mecnun gözüyle bakmaya
baþladýlar. Gece ve gündüzünü ilme ve ibadete veren Mustafa Akif Efendi, ilmi mütalaalar ve
araþtýrmalarda bulundu. Gece sabaha kadar lambasý hiç sönmeyen bu alim zat, gözlerinin
bozulmamasý için çalýþtýðý odaya birçok lamba koyardý.

Týb, astronomi ve matematik ilimlerinde maharet sahibiydi. Týb ilminin gereklerine dikkat
ederdi. Talebelerinin ve sevdiklerinin hastalýklarýna çeþitli ilaçlar yaparak tatbik ederdi.
Bunun için evinin üstünde bir oda yaptýrmýþtý. Burada oturur, bedenen sýhhatli olmak için
oraya hýzlý iner çýkardý. Bahçede gidip gelerek hareketli olmaya çalýþýrdý. Bu bahçede
talebelere ders okuturdu. Yanýnda çok sayýda talebe bulunmasýný istemezdi. Eðer talebelere
ders vermesi gerekirse dört veya beþ talebeye ders verirdi. Bir kiþi fazla olsa, onu kabul
etmezdi. Eðer azýcýk müsade etse etrafýný talebe sarardý.

Mustafa Akif Efendi ulema sýnýfýndan olmasýna raðmen belli bir kýyafet giyinmezdi. Bazan
ulemaya ait elbise giydiði gibi bazan da mevlevi derviþlerine ait elbise giyerdi. Camiye
giderken vakar ve aðýr baþlýlýkla giderdi.

Kendisi cömert olup, ikram ve ihsan sahibi idi. Ziyafet hazýrlar, memleketin ileri
gelenlerinden vali, kadý ile ulemadan birçoklarýný ve halkýn ileri gelenlerini davet ederdi.
Þehrin valisi Cuma günleri onu ziyaret ederdi. Valiyi saygý ile karþýlar ona izzet ve ikramda
bulunurdu. Vali ile müsafeha ettikten sonra; "Siz sultanýn vekillerisiniz. Size itaat ve saygý
gerekir." derdi. Kendisi fakir olmasýna raðmen Allahü tealanýn ihsan ve bereketiyle fakirlere
bol tasaddukta bulunurdu. Camiye giderken boynuna beyaz bir kese asar, kesenin içine altýn
ve gümüþ paralar doldururdu. Onun cömert ve ihsan sahibi olduðunu bilen fakirler, yolu
üzerine sýra olurlardý.Kesede bulunan paralarý fakirlere ve ihtiyaç sahiplerine altýn veya
gümüþ fark ettirmeden daðýtýrdý. Bazan da kesedeki para bitinceye kadar avuç dolusu verirdi.
Bazan fakirler onun üzerine fazlaca yüklenmek isteyince, keseyi býrakarak hýzlýca evine
giderdi. Sonra fakirler kesesini evine getirirlerdi. Malý ve geliri olmamasýna raðmen bu
adetini hemen hemen her gün devam ettirirdi. Ýnsanlar onun bu haline þaþarlardý. Halbuki
Allahü teala pekçok velisine olduðu gibi, Mustafa Akif Efendiye de keramet olarak bu
mallarý ihsan etmiþti.

Mustafa Akif Efendi, pekçok ilmi araþtýrmalarý olan bir zattý. Amasya kütüphanelerindeki
kitaplarý araþtýrmýþtý. Okuduðu ve incelediði kitaplara rakamlar þerhler koyar, fihristlerini
çýkarýrdý. Çok kere kýrmýzý mürekkeple ve ta'lik hattýyla yazardý. Arapça, Farsça ve Türkçe
þiirler söyler, nesirler yazardý. Üç lisanda da þiir kabiliyeti vardý. Týp ilminde de geniþ bilgi
sahibiydi. Hey'et, astronomi ve hendese, geometri ilimlerinin teorik ve pratik kýsýmlarýnda
ihtisas sahibiydi. Akli ve nakli ilimlerin usul ve füru kýsýmlarýnda yüksek alimdi. Hatta onun;
"Üç yüz senedir usul-i fýkýhta benim gibi birisi gelmedi." dediði rivayet olunur. Edebiyatta

Anadolu'daki Arapça divanlar onun þiirinin kaynaðýydý. Arapça Kaside-i Mimiyyesi ve
Kaside-i Ayniyyesi vardý.

Ýlmiyle amil, fazilet sahibi bir veli idi. Tefsir, hadis, usul-i fýkýh ve fýkýh ilimlerinde
zamanýnýn müracaat kaynaðý olan Mustafa Akif Efendi, 1760 (H.1173) senesi Receb ayýnýn
yirmi birinci Pazar günü güneþ doðmadan önce Amasya'da vefat etti. Amasya surunun
dýþýnda, Musalla yolundaki kabristanýn kýble tarafýnda defnedildi.

1) Kitabü'l-Mecmu fil-Meþhud vel-Mesmu; s.40-43

redpajama_set_name: RedPajamaGithub


text:
/** Vector java bean entity **/
package dbbeans.desccargoscompra;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Vector;

public class dbDESCCARGOSCOMPRAs {
	private Connection conn;
	private ResultSet rSet;
	private PreparedStatement stmt;
	private Vector result;

	public dbDESCCARGOSCOMPRAs() {
		super();
		result = new Vector();
	}
	public void setConnection(java.sql.Connection conn) {
		this.conn = conn;
	}
	public boolean find(String where) throws Exception, java.sql.SQLException {
		StringBuffer query = new StringBuffer();
		dbDESCCARGOSCOMPRA DESCCARGOSCOMPRA;
		query.append("SELECT * ");
		query.append("FROM DESCCARGOSCOMPRA ");
		if (!where.equals("")){
			query.append("WHERE " + where );
		}
		stmt = conn.prepareStatement(query.toString().toLowerCase());
		rSet = stmt.executeQuery();

		while (rSet.next()) {
			DESCCARGOSCOMPRA= new dbDESCCARGOSCOMPRA();
			DESCCARGOSCOMPRA.setIidproveedor(rSet.getInt("iidproveedor"));
			DESCCARGOSCOMPRA.setIidcategoria(rSet.getInt("iidcategoria"));
			DESCCARGOSCOMPRA.setIidgrupo(rSet.getInt("iidgrupo"));
			DESCCARGOSCOMPRA.setIidlinea(rSet.getInt("iidlinea"));
			DESCCARGOSCOMPRA.setIidmarca(rSet.getInt("iidmarca"));
			DESCCARGOSCOMPRA.setVchleyenda(rSet.getString("vchleyenda"));
			DESCCARGOSCOMPRA.setDecfactor(rSet.getFloat("decfactor"));
			result.addElement(DESCCARGOSCOMPRA);
		}
		rSet.close();
		stmt.close();
		return false;
	}
	public void setResult (Vector result){
		this.result = result;
	}
	public Vector getResult(){
		return this.result;
	}

	public boolean findByPar(int iidproveedor, int iidcategoria, int iidgrupo, int iidlinea, int iidmarca) throws Exception, java.sql.SQLException {
		StringBuffer query = new StringBuffer();
		dbDESCCARGOSCOMPRA DESCCARGOSCOMPRA;
		query.append("SELECT * ");
		query.append("FROM DESCCARGOSCOMPRA ");
		query.append("WHERE iidproveedor=? and iidcategoria=? and iidgrupo=? and iidlinea=? and iidmarca=? ");

		stmt = conn.prepareStatement(query.toString().toLowerCase());

		stmt.setInt(1,iidproveedor);
		stmt.setInt(2,iidcategoria);
		stmt.setInt(3,iidgrupo);
		stmt.setInt(4,iidlinea);
		stmt.setInt(5,iidmarca);

		rSet = stmt.executeQuery();

		while (rSet.next()) {
			DESCCARGOSCOMPRA= new dbDESCCARGOSCOMPRA();
			DESCCARGOSCOMPRA.setIidproveedor(rSet.getInt("iidproveedor"));
			DESCCARGOSCOMPRA.setIidcategoria(rSet.getInt("iidcategoria"));
			DESCCARGOSCOMPRA.setIidgrupo(rSet.getInt("iidgrupo"));
			DESCCARGOSCOMPRA.setIidlinea(rSet.getInt("iidlinea"));
			DESCCARGOSCOMPRA.setIidmarca(rSet.getInt("iidmarca"));
			DESCCARGOSCOMPRA.setVchleyenda(rSet.getString("vchleyenda"));
			DESCCARGOSCOMPRA.setDecfactor(rSet.getFloat("decfactor"));
			result.addElement(DESCCARGOSCOMPRA);
		}
		rSet.close();
		stmt.close();
		return false;
	}
}


text:
Sample codes of Windows 10 UWP Apps by megayuchi Source code that was demonstrated at MS Techdays 2015 in SEOUL ( https://doc.co/jERsyS )

[Requirements] 1. Windows 10 build 10240 or later 2. Visual Studio 2015

---

•RefClass - ref class sample in UWP.

--

•FileOpenUWP - File Open Sample in UWP.

--

•FFMPEG_UWP - DirectX 11 and ffmepg interop sample in UWP.

[Build]

1. Download latest ffmpeg build. ( https://github.com/FFmpeg/FFmpeg )
2. Build ffmpeg for WinRT. ( https://trac.ffmpeg.org/wiki/CompilationGuide/WinRT )
3. Copy ffmpeg's binary files to Windows-UWP\FFMPEG_UWP\ffmpeg folder.
4. Run copy_dlls.bat in Windows-UWP\FFMPEG_UWP folder.
5. Build Windows-UWP\FFMPEG_UWP\Decoder\Decoder.vcxproj Project.
6. Build and run Windows-UWP\FFMPEG_UWP\D3DVideoPlayer\D3DVideoPlayer.vcxproj Project.

--


text:
class UITestSuite : public ChromeTestSuite {
 public:
  UITestSuite(int argc, char** argv);

 protected:
  virtual void Initialize() OVERRIDE;
  virtual void Shutdown() OVERRIDE;

 private:
#if defined(OS_WIN)
  void LoadCrashService();

  base::ProcessHandle crash_service_;

  // JobObject used to clean up orphaned child processes.
  base::win::ScopedHandle job_handle_;
#endif
};

#endif  // CHROME_TEST_UI_UI_TEST_SUITE_H_


text:
namespace ipc {

class slave
	: public slave_intf
	, protected common
{
public:
	slave(logger_ptr logger, client_connection& connection, message_callback_fn callback_fn);

	struct factory {
		virtual std::shared_ptr<slave_intf> create_slave(logger_ptr logger, client_connection& connection, message_callback_fn callback_fn) const;
	};

	//! \copydoc slave_intf::send
	bool send(std::vector<uint8_t>& message, std::vector<uint8_t>& response) override;
	//! \copydoc slave_intf::stop
	void stop() override;
};

} // end of namespace ipc


text:
int main (void)
{
  CFLocaleRef locale;
  CFStringRef str;

  locale = CFLocaleCreate (NULL, CFSTR("nb"));
  str = CFLocaleCopyDisplayNameForPropertyValue (locale, kCFLocaleLanguageCode,
                                                 CFSTR("pt"));
  PASS_CFEQ (str, CFSTR("portugisisk"), "Display language is correct");
  CFRelease (str);

  str = CFLocaleCopyDisplayNameForPropertyValue (locale, kCFLocaleCountryCode,
                                                 CFSTR("BR"));
  PASS_CFEQ (str, CFSTR("Brasil"), "Display country is correct");
  CFRelease (str);

  str = CFLocaleCopyDisplayNameForPropertyValue (locale,
                                                 kCFLocaleCalendarIdentifier,
                                                 CFSTR("gregorian"));
  PASS_CFEQ (str, CFSTR("gregoriansk kalender"),
             "Display calendar identifier is correct");
  CFRelease (str);

  str = CFLocaleCopyDisplayNameForPropertyValue (locale,
                                                 kCFLocaleCollationIdentifier,
                                                 CFSTR("traditional"));
  PASS_CFEQ (str, CFSTR("tradisjonell sortering"),
             "Display collation identifier is correct");
  CFRelease (str);

  str = CFLocaleCopyDisplayNameForPropertyValue (locale, kCFLocaleCurrencyCode,
                                                 CFSTR("BRL"));
  PASS_CFEQ(str, CFSTR("brasilianske realer"),
            "Display currency code is correct");
  CFRelease (str);

  return 0;
}


text:
var minimatch = require('minimatch');
var path =  require('path');

var joinPath = (function () {
    var _join = path.join;
    return function (base, request) {
        if (request) {
            return _join(base, request).replace(/\\/g, '/');
        }
        return base.replace(/\\/g, '/');
    };
})();

function Codegs(config) {

    this.config = {
        rootdir:      null,
        mainfile:     null,
        source:       null,
        output:       null,
        core:         null,
        node_core:    null,
        node_modules: null,
        kernel:       null
    };

    this.files = {
        core:         {},
        node_core:    {},
        node_modules: {},
        source:       {},
        main:         null,
        kernel:       null
    };
    this.ignoreFilepath = [];
    this.ignorePattern = [];
    this.content = '';

    if (config) {
        Codegs.prototype.addConfig.call(this, config);
    }
}

Codegs.create = function (config) {
    return new Codegs(config);
};

Codegs.prototype.addConfig = function (config) {

    if (config.rootdir) {
        this.config.rootdir = config.rootdir;
    }

    if (config.mainfile) {
        this.config.mainfile = config.mainfile;
    }

    if (config.source) {
        if (this.config.source === null) {
            this.config.source = [];
        }
        this.config.source = this.config.source.concat(config.source);
    }

    if (config.output) {
        this.config.output = config.output;
    }

    if (config.core) {
        this.config.core = config.core;
    }

    if (config.node_core) {
        this.config.node_core = config.node_core;
    }

    if (config.node_modules) {
        if (this.config.node_modules === null) {
            this.config.node_modules = [];
        }
        this.config.node_modules = this.config.node_modules.concat(config.node_modules);
    }

    if (config.kernel) {
        this.config.kernel = config.kernel;
    }

    return null;
};

Codegs.prototype.loadPackageJson = function (filepath, mockfs) {
    var fs = mockfs || require('fs');
    var error = null;

    if ( ! fs.existsSync(filepath)) {
        return 'Error: package.json is not found.';
    }

    var packageInfo = this._require(filepath);

    var config = {
        rootdir:      path.dirname(filepath),
        mainfile:     packageInfo.main || null,
        node_modules: []
    };

    if (packageInfo.files) {
        config.source = [];
        for (var i = 0; i < packageInfo.files.length; i++) {
            config.source.push(joinPath(config.rootdir, packageInfo.files[i]));
        }
    }
    if (packageInfo.dependencies) {
        for (var p in packageInfo.dependencies) {
            if (packageInfo.dependencies.hasOwnProperty(p)) {
                config.node_modules.push(p);
            }
        }
    }

    error = this.addConfig(config);
    if (error) {
        return error;
    }

    if (packageInfo.nmlConfig) {
        error = this.addConfig(packageInfo.nmlConfig);
        if (error) {
            return error;
        }
    }

    this.packageInfo = packageInfo;

    // load .npmignore file.
    var ignoreFilepath = joinPath(config.rootdir, '.npmignore');
    if ( ! fs.existsSync(ignoreFilepath)) {
        return error;
    }

    var patterns = fs.readFileSync(ignoreFilepath, 'utf8').split('\n');
    for (var j = 0; j < patterns.length; j++) {
        if (patterns[j] !== '') {
            this._addIgnorePattern('**/' + patterns[j]);
        }
    }

    return error;
};

// this sub function is hook point for jasmine-spy.
Codegs.prototype._require = function (filepath) {
    return require(filepath);
};

Codegs.prototype.run = function () {
    var steps = [
            this.setup,
            this.addCoreFiles,
            this.addNodeCoreFiles,
            this.addNodeModules,
            this.addSourceFiles,
            this.compile,
            this.out
        ],
        error = null;

    for (var i = 0; (i < steps.length) && (error === null); i++) {
        error = steps[i].apply(this);
    }
    return error;
};

Codegs.prototype.setup = function (mockfs) {
    var fs = mockfs || require('fs');

    // config.rootdir
    if ( ! this.config.rootdir) {
        this.config.rootdir = process.cwd();
    }

    // config.mainfile
    if ( ! this.config.mainfile) {
        this.config.mainfile = process.cwd();
    }

    // config.core
    if (this.config.core) {
        this.config.core = path.resolve(this.config.rootdir, this.config.core);
        if ( ! fs.existsSync(this.config.core)) {
            return 'Error: core module directory is not existent.';
        }
        if ( ! fs.statSync(this.config.core).isDirectory()) {
            return 'Error: core module directory is not directory.';
        }
    } else {
        // default value. not check if it exists.
        this.config.core = path.resolve(this.config.rootdir, './core');
    }

    // config.node_core
    if (this.config.node_core) {
        this.config.node_core = path.resolve(this.config.rootdir, this.config.node_core);
        if ( ! fs.existsSync(this.config.node_core)) {
            return 'Error: node_core module directory is not existent.';
        }
        if ( ! fs.statSync(this.config.node_core).isDirectory()) {
            return 'Error: node_core module directory is not directory.';
        }
    } else {
        // default value. not check if it exists.
        this.config.node_core = path.resolve(this.config.rootdir, './node_core');
    }

    // files.main
    this.files.main = path.resolve(this.config.rootdir, this.config.mainfile);
    if ( ! fs.existsSync(this.files.main)) {
        this.files.main = null;
        return 'Error: main file is not existent.';
    }
    if ( ! fs.statSync(this.files.main).isFile()) {
        this.files.main = null;
        return 'Error: main file is not valid filetype.';
    }
    this._addIgnoreFilepath(this.files.main);

    // files.kernel
    if (this.config.kernel) {

        this.files.kernel = path.resolve(this.config.rootdir, this.config.kernel);
        if ( ! fs.existsSync(this.files.kernel)) {
            this.files.kernel = null;
            return 'Error: kernel file is not existent.';
        }
        if ( ! fs.statSync(this.files.kernel).isFile()) {
            this.files.kernel = null;
            return 'Error: kernel file is not valid filetype.';
        }
        this._addIgnoreFilepath(this.files.kernel);
    }

    return null;
};

Codegs.prototype.addCoreFiles = function (mockfs) {

    if (typeof this.config.core !== 'string') {
        return 'Error: core file directory is not specified.';
    }

    var coredir = joinPath(this.config.core);
    var error = this._addFilesToList(this.files.core, coredir, 'core/', false, mockfs);
    if (error === null) {
        coredir = coredir.slice(-1) === '/' ? coredir.slice(0, -1) : coredir;
        this._addIgnoreFilepath(coredir);
    }
    return error;
};

Codegs.prototype.addNodeCoreFiles = function (mockfs) {

    if (typeof this.config.node_core !== 'string') {
        return 'Error: node_core file directory is not specified.';
    }

    var nodecoredir = joinPath(this.config.node_core);
    var error = this._addFilesToList(this.files.node_core, nodecoredir, 'node_core/', false, mockfs);
    if (error === null) {
        nodecoredir = nodecoredir.slice(-1) === '/' ? nodecoredir.slice(0, -1) : nodecoredir;
        this._addIgnoreFilepath(nodecoredir);
    }
    return error;
};

Codegs.prototype.addNodeModules = function (mockfs) {

    var error = null;
    var rootdir = joinPath(this.config.rootdir);
    var moduledir = joinPath(rootdir, './node_modules');

    if (this.config.node_modules === null) {
        error = this._addFilesToList(this.files.node_modules, moduledir, '/node_modules/', false, mockfs);
        if (error === null) {
            this._addIgnoreFilepath(moduledir);
        }
        return error;
    }

    var i, source, storepath;
    for (i = 0; i < this.config.node_modules.length; i++) {

        storepath = source = joinPath(moduledir, this.config.node_modules[i]);
        storepath = storepath === rootdir ? '/' : storepath.slice(rootdir.length);

        error = this._addFilesToList(this.files.node_modules, source, storepath, false, mockfs);
        if (error === null) {
            source = source.slice(-1) === '/' ? source.slice(0, -1) : source;
            this._addIgnoreFilepath(source);
        } else {
            break;
        }
    }
    return error;
};

Codegs.prototype.addSourceFiles = function (mockfs) {

    if (this.config.source === null) {
        this.config.source = [];
        this.config.source.push(this.config.rootdir);
    }

    var i, source, storepath, error = null;
    var rootdir = joinPath(this.config.rootdir);

    for (i = 0; i < this.config.source.length; i++) {

        storepath = source = joinPath(this.config.source[i]);

        if (storepath.slice(0, rootdir.length) !== rootdir) {
            return 'Error: Source directory is outside project root.';
        }
        storepath = storepath === rootdir ? '/' : storepath.slice(rootdir.length);

        error = this._addFilesToList(this.files.source, source, storepath, true, mockfs);
        if (error === null) {
            source = source.slice(-1) === '/' ? source.slice(0, -1) : source;
            this._addIgnoreFilepath(source);
        } else {
            break;
        }
    }
    return error;
};

Codegs.prototype.compile = function (mockfs) {
    var fs = mockfs || require('fs');

    this.content = '';
    var content = '';

    content = Codegs._compileFilesList(this.files.core, mockfs);
    this.content += content;

    content = Codegs._compileFilesList(this.files.node_core, mockfs);
    this.content += content;

    content = Codegs._compileFilesList(this.files.node_modules, mockfs);
    this.content += content;

    content = Codegs._compileFilesList(this.files.source, mockfs);
    this.content += content;

    var mainfileList = Codegs._createFilesList(this.config, this.files.main, 'main');
    content = Codegs._compileFilesList(mainfileList, mockfs);
    this.content += content;

    if (this.files.kernel) {
        var corefileList = {};
        corefileList[this.files.kernel] = { type: 'core', path: '' };
        content = Codegs._compileFilesList(corefileList, mockfs);
    } else {
        // kernel === null, then should not wrap. just read and append.
        content = fs.readFileSync(require.resolve('./module.js'));
    }
    this.content += content;

    return null;
};

Codegs.prototype.out = function (mockfs) {
    var fs = mockfs || require('fs');

    if (this.config.output) {
        try {
            fs.writeFileSync(this.config.output, this.content);
        } catch(e) {
            return 'Error: ' + e;
        }
        return null;
    }

    return this.content;
};

Codegs._createFilesList = function (config, file, type) {
    var rootdir = joinPath(config.rootdir);
    var rootlength = rootdir.length - (rootdir.slice(-1) === '/' ? 1 : 0);

    var mainpath = file.slice(rootlength);
    var fileList = {};

    fileList[file] = { type: type, path: mainpath};

    return fileList;
};

Codegs._compileFilesList = function (filesList, mockfs) {
    var fs = mockfs || require('fs');
    var codegsModule = require('./module');

    var file, content, mergedContent = '';

    for (file in filesList) {
        if (filesList.hasOwnProperty(file)) {
            content = fs.readFileSync(file, {encoding: 'utf8'});

            // remove shebang
            content = content.replace(/^\#\!.*/, '');

            content = codegsModule.wrap(content, filesList[file].path, filesList[file].type);
            if (content === null) {
                throw new Error("Error: Invalid filepath '" + filesList[file].path +
                                "'or type '" + filesList[file].type + "'");
            }
            mergedContent += content;
        }
    }
    return mergedContent;
};

Codegs.prototype._addIgnoreFilepath = function (filepath) {
    this.ignoreFilepath.push(filepath);
};

Codegs.prototype._addIgnorePattern = function (pattern) {
    this.ignorePattern.push(pattern);
};

Codegs.prototype._isIgnoreFile = function (file, checkPattern) {
    for (var i = 0; i < this.ignoreFilepath.length; i++) {
        if (file === this.ignoreFilepath[i]) {
            return true;
        }
    }
    if (checkPattern) {
        for (var j = 0; j < this.ignorePattern.length; j++) {
            if (minimatch(file, this.ignorePattern[j])) {
                return true;
            }
        }
    }
    return false;
};

Codegs.prototype._addFilesToList = function (list, source, storepath, checkPattern, mockfs) {
    var fs = mockfs || require('fs');

    if (this._isIgnoreFile(source, checkPattern)) {
        return null;
    }

    if ( ! fs.existsSync(source)) {
        //return ("Error: File or Directory not Exists. '" + source + "'");
        return null;
    }

    var stat = fs.statSync(source);

    if (stat.isFile()) {
        // If specific file passed, no file type checking to add.
        if (list[source] === undefined) {
            list[source] = {
                type : source.slice(-5) === '.json' ? 'json' : 'js',
                path : storepath
            };
        }
        return null;
    }
    if (stat.isDirectory()) {
        var files = fs.readdirSync(source);

        var error;
        for (var i = 0; i < files.length; i++) {
            if (this._isIgnoreFile(files[i], checkPattern)) {
                continue;
            }
            stat = fs.statSync(joinPath(source, files[i]));
            if (stat.isFile()) {
                // File types to add are only '.js' and '.json', by default.
                if (! ( ((files[i].length > 3) && (files[i].slice(-3) === '.js')) ||
                        ((files[i].length > 5) && (files[i].slice(-5) === '.json'))) ) {
                    continue;
                }
            }
            error = this._addFilesToList(list,
                                    joinPath(source, files[i]),
                                    joinPath(storepath, files[i]),
                                    checkPattern,
                                    mockfs);
            if (error !== null) {
                return error;
            }
        }
        return null;
    }
    return null;
};

module.exports = Codegs;


text:
import { TestBed, inject } from '@angular/core/testing';

import { Service574Service } from './service-574.service';

describe('Service574Service', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [Service574Service]
    });
  });

  it('should ...', inject([Service574Service], (service: Service574Service) => {
    expect(service).toBeTruthy();
  }));
});


text:
* * *

license: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

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

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

## under the License.

# Anleitung zur Windows Platform

Diese Anleitung zeigt wie der SDK-Entwicklungsumgebung zum Erstellen und Bereitstellen von Cordova apps für Windows 8, Windows 8.1 und Windows Phone 8.1 einzurichten. Es zeigt, wie mithilfe von entweder Shell-Werkzeugen generieren und bauen apps oder die plattformübergreifende Cordova CLI diskutiert in der Command-Line Interface. (Siehe die Übersicht für einen Vergleich dieser Entwicklung-Optionen.) In diesem Abschnitt veranschaulicht auch Cordova apps innerhalb von Visual Studio zu ändern. Unabhängig davon, welchen Ansatz Sie nehmen, müssen Sie das Visual Studio-SDK installieren, wie unten beschrieben.

Informationen zum Aktualisieren von bestehender Windows 8 Cordova-Projekten finden Sie unter Aktualisieren von Windows 8.

Einzelheiten siehe Fenster Telefon 8 (wp8) Aufenthalte als separate Plattform Windows Phone 8 Platform Guide.

Cordova WebViews unter Windows sind auf Internet Explorer 10 (Windows 8.0) und Internet Explorer 11 (Windows 8.1 und Windows Phone 8.1) als ihre Rendering-Engine, also als eine praktische Sache Sie IE leistungsstarken Debugger verwenden können, um alle Webinhalte testen, die Cordova-APIs aufrufen nicht. Die Windows Phone Developer Blog enthält [hilfreiche Hinweise][1] zum Support IE sowie vergleichbare WebKit-Browser.

 [1]: http://blogs.windows.com/windows_phone/b/wpdev/archive/2012/11/15/adapting-your-webkit-optimized-site-for-internet-explorer-10.aspx

## Anforderungen und Unterstützung

Entwickeln von Anwendungen für Windows-Plattform, die Sie brauchen:

*   Eine Windows-8.1, 32 oder 64-Bit-Maschine (*Home*, *Pro*oder *Enterprise* -Editionen) mit mindestens 4 GB RAM.

*   Für die Windows Phone-Emulatoren, Professional Edition Windows 8.1 (X 64) oder höher, und ein Prozessor unterstützt [Client Hyper-V und Second Level Address Translation (Stab)][2]. Eine Evaluierungsversion von Windows 8.1 Enterprise gibt es aus dem [Microsoft Developer Network][3].

*   [Visual Studio-2013 für Windows][4] (Express oder höher).

 [2]: https://msdn.microsoft.com/en-us/library/windows/apps/ff626524(v=vs.105).aspx#hyperv
 [3]: http://msdn.microsoft.com/en-US/evalcenter/jj554510
 [4]: http://www.visualstudio.com/downloads/download-visual-studio-vs#d-express-windows-8

Apps, die kompiliert unter Windows 8.1 tun *nicht* laufen unter Windows 8.0. Apps unter Windows 8.0 kompiliert sind aufwärtskompatibel mit 8.1.

Folgen Sie den Anweisungen auf [windowsstore.com][5] die app Windows Store einreichen.

 [5]: http://www.windowsstore.com/

Entwicklung von Cordova apps für Windows können einen PC mit Windows, aber Sie können auch auf einem Mac entwickeln, oder mit einer VM-Umgebung mithilfe von Boot Camp eine Windows-8.1 Dual-Boot-Partition. Finden Sie diese Ressourcen die erforderlichen Windows-Entwicklungsumgebung auf einem Mac einrichten:

*   [VMWare Fusion][6]

*   [Parallels Desktop][7],

*   [Boot Camp][8].

 [6]: http://msdn.microsoft.com/en-US/library/windows/apps/jj945426
 [7]: http://msdn.microsoft.com/en-US/library/windows/apps/jj945424
 [8]: http://msdn.microsoft.com/en-US/library/windows/apps/jj945423

## Das SDK installieren

Installieren Sie die *ultimative*, *Premium*oder *Professional* 2013 Editionen von [Visual Studio][4].

![][9]

 [9]: img/guide/platforms/win8/win8_installSDK.png

## Mithilfe von Cordova Shell Tools

Wenn Sie Cordova's Windows-zentrierte Shell-Werkzeugen in Verbindung mit dem SDK verwenden möchten, müssen Sie zwei grundlegende Optionen:

*   Greifen sie lokal von Projektcode generiert durch die CLI. Sie stehen in den `platforms/windows/` Verzeichnis, nachdem Sie die `Windows` -Plattform hinzufügen, wie unten beschrieben.

*   Aus eine separate Verteilung auf [cordova.apache.org][10]herunterladen. Die Cordova-Distribution enthält separate Archiv für jede Plattform. Achten Sie darauf, um das entsprechende Archiv, `Cordova-Windows` in diesem Fall in ein leeres Verzeichnis zu erweitern. Die entsprechenden Batch-Dienstprogramme sind im `Paket/bin` -Verzeichnis. (Konsultieren Sie die **README** -Datei, ggf. für eine genauere Wegbeschreibung.)

 [10]: https://www.apache.org/dist/cordova/platforms/

Diese Shell-Tools können Sie erstellen, erstellen und Ausführen von Windows-Anwendungen. Informationen über die zusätzliche Befehlszeilenschnittstelle, die Plugin-Features für alle Plattformen aktiviert, finden Sie unter Using Plugman zu Plugins verwalten.

## Erstellen eines neuen Projekts

Zu diesem Zeitpunkt zum Erstellen eines neuen Projekts können Sie zwischen das Cross-Plattform-CLI-Tool in The Command-Line Interface oder den Satz von Windows-spezifischen Shell Tools beschrieben. Der CLI-Ansatz unten wird eine app mit dem Namen *"HelloWorld"* eines neue `hello` -Projekt-Verzeichnis:

        > cordova create hello com.example.hello HelloWorld
        > cd hello
        > cordova platform add windows

Hier ist der entsprechende Low-Level-Shell-Tool-Ansatz:

        C:\path\to\cordova-windows\package\bin\create.bat C:\path\to\new\hello com.example.hello HelloWorld

## Erstellen Sie das Projekt

Bei Verwendung von CLI in der Entwicklung ist das Projektverzeichnis der obersten Ebene `www` Verzeichnis enthält die Quellcode-Dateien. Führen Sie einen dieser dem Projektverzeichnis, die app neu zu erstellen:

        > cordova build
        > cordova build windows              # do not rebuild other platforms
        > cordova build windows   --debug    # generates debugging information
        > cordova build windows   --release  # signs the apps for release

Hier ist der entsprechende Low-Level-Shell-Tool-Ansatz:

        C:\path\to\project\cordova\build.bat --debug
        C:\path\to\project\cordova\build.bat --release
        C:\path\to\project\cordova\clean.bat

## Ziel-Windows-Version zu konfigurieren

Von Standard `build` Befehl erzeugt zwei Pakete: Windows 8.0 und Windows Phone 8.1. Aktualisieren von Windows-Paket auf Version 8.1 folgende Konfigurationseinstellung in Konfigurationsdatei (`"config.xml"` hinzugefügt werden).

        <preference name='windows-target-version' value='8.1' />

Sobald Sie hinzufügen startet diese Einstellung-Befehl `Erstellen` , produzieren Windows 8.1 und Windows Phone 8.1 Pakete.

## Die app bereitstellen

Windows-Paket bereitstellen:

        > cordova run windows -- --win  # explicitly specify Windows as deployment target
        > cordova run windows # `run` uses Windows package by default

Windows Phone-Paket bereitstellen:

        > cordova run windows -- --phone  # deploy app to Windows Phone 8.1 emulator
        > cordova run windows --device -- --phone  # deploy app to connected device

Können Sie **cordova run windows --list** finden alle verfügbaren Ziele und **cordova run windows --target=target_name \-- -|-phone** Anwendung auf ein bestimmtes Gerät oder einen Emulator ausführen (z. B. `ordova run windows --target="Emulator 8.1 720P 4.7 inch" -- --phone`).

Sie können auch **cordova run --help** finden Sie unter zusätzliche Build und Ausführungsoptionen.

## Öffnen Sie das Projekt im SDK und Bereitstellen der Anwendung

Sobald Sie eine Cordova-Anwendung zu erstellen, wie oben beschrieben, können Sie es mit Visual Studio öffnen. Die verschiedenen `build` Befehle Generieren einer Visual Studio-Projektmappendatei (*.sln*). Öffnen Sie die Datei im Datei-Explorer ändern Sie das Projekt in Visual Studio:

![][11]

 [11]: img/guide/platforms/win8/win8_sdk_openSLN.png

Die `CordovaApp` -Komponente zeigt innerhalb der Lösung und ihrer `Www` -Verzeichnis enthält den Web-basierte Source-Code, einschließlich der `index.html` -Homepage:

![][12]

 [12]: img/guide/platforms/win8/win8_sdk.png

Mit den Steuerelementen unter Visual Studio im Hauptmenü können Sie testen oder Bereitstellen der app:

![][13]

 [13]: img/guide/platforms/win8/win8_sdk_deploy.png

**Lokalen Computer** ausgewählt drücken Sie den grünen Pfeil um die app auf dem gleichen Computer ausführen von Visual Studio installieren. Einmal tun Sie dies, die app erscheint in Windows 8 app angeboten:

![][14]

 [14]: img/guide/platforms/win8/win8_sdk_runApp.png

Jedes Mal, wenn Sie die Anwendung neu erstellen, wird die Version in der Schnittstelle aktualisiert.

Sobald Sie in der app-Angebote verfügbar, ermöglicht halten Sie die **STRG** -Taste beim Markieren der app um zum Hauptbildschirm zu fixieren:

![][15]

 [15]: img/guide/platforms/win8/win8_sdk_runHome.png

Beachten Sie, dass wenn Sie die app in einer virtuellen Umgebung öffnen, müssen Sie möglicherweise klicken Sie auf in den Ecken oder an den Seiten des Windows apps zu wechseln oder auf zusätzliche Funktionen zugreifen:

![][16]

 [16]: img/guide/platforms/win8/win8_sdk_run.png

Wählen Sie alternativ die **Simulator** -Bereitstellungsoption die app anzeigen, als ob es auf einem Tablettgerät ausgeführt wurden:

![][17]

 [17]: img/guide/platforms/win8/win8_sdk_sim.png

Im Gegensatz zu desktop-Bereitstellung mit dieser Option können Sie simulieren die Tablette Orientierung, Lage, und variieren ihre Netzwerkeinstellungen.

**Hinweis**: Rufen Sie die Übersicht für Ratschläge, wie mithilfe von Cordovas Kommandozeilen-Tools oder das SDK in Ihrem Workflow. Cordova CLI stützt sich auf Cross-Plattform-Quellcode, der routinemäßig die plattformspezifischen Dateien vom SDK verwendet überschreibt. Möchten Sie das SDK zu verwenden, ändern Sie das Projekt, verwenden Sie die Low-Level-Shell-Werkzeugen als Alternative zu den CLI.


text:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Do something!" />

    <TextView
        android:id="@+id/locationTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>


text:
package com.example.lang.thread;

/**
 * http://www.programering.com/a/MDO2MTNwATc.html
 *

 * Use the interrupt signal to interrupt non blocking threads
 *

 * Interrupt threads the best, the most recommended way is using shared variables (shared, variable) signal,
 * told the thread must stop running tasks. Thread must periodically check the variable,
 * then in order to stop the task. Example describes this way:
 */
class ThreadInterruptExample2 extends Thread {

    volatile boolean stop = false;

    public static void main(String args[]) throws Exception {
        ThreadInterruptExample2 thread = new ThreadInterruptExample2();
        System.out.println("Starting thread...");
        thread.start();
        Thread.sleep(3000);
        System.out.println("Asking thread to stop...");
        thread.stop = true;
        Thread.sleep(3000);
        System.out.println("Stopping application...");
    }

    @Override
    public void run() {
        // Every second check interrupt signal
        while (!stop) {
            System.out.println("Thread is running...");
            long time = System.currentTimeMillis();
            /*
             * Use a while loop simulation sleep method, here don't use sleep, otherwise they will be thrown on the obstruction
             * Abnormal InterruptedException and exit the loop, so that the while detection of stop conditions will not be executed,
             * Lost meaning.
             */
            while ((System.currentTimeMillis() - time < 1000) && (!stop)) {
            }
        }
        System.out.println("Thread exiting under request...");
    }
}


text:
<?php

namespace Listreat\MainBundle\Controller;

/**
 * This code has been auto-generated by the JMSDiExtraBundle.
 *
 * Manual changes to it will be lost.
 */
class ShopController__JMSInjector
{
    public static function inject($container) {
        $instance = new \Listreat\MainBundle\Controller\ShopController();
        return $instance;
    }
}


text:
class AddLogoToSeller < ActiveRecord::Migration
  def change
    add_column :sellers, :logo, :string
  end
end


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Functions for event management.
 *
 * @package PhpMyAdmin
 */
use PMA\libraries\Response;

if (! defined('PHPMYADMIN')) {
    exit;
}

/**
 * Sets required globals
 *
 * @return void
 */
function PMA_EVN_setGlobals()
{
    global $event_status, $event_type, $event_interval;

    $event_status        = array(
                               'query'   => array('ENABLE',
                                                  'DISABLE',
                                                  'DISABLE ON SLAVE'),
                               'display' => array('ENABLED',
                                                  'DISABLED',
                                                  'SLAVESIDE_DISABLED')
                           );
    $event_type          = array('RECURRING',
                                 'ONE TIME');
    $event_interval      = array('YEAR',
                                 'QUARTER',
                                 'MONTH',
                                 'DAY',
                                 'HOUR',
                                 'MINUTE',
                                 'WEEK',
                                 'SECOND',
                                 'YEAR_MONTH',
                                 'DAY_HOUR',
                                 'DAY_MINUTE',
                                 'DAY_SECOND',
                                 'HOUR_MINUTE',
                                 'HOUR_SECOND',
                                 'MINUTE_SECOND');
}

/**
 * Main function for the events functionality
 *
 * @return void
 */
function PMA_EVN_main()
{
    global $db;

    PMA_EVN_setGlobals();
    /**
     * Process all requests
     */
    PMA_EVN_handleEditor();
    PMA_EVN_handleExport();
    /**
     * Display a list of available events
     */
    $items = $GLOBALS['dbi']->getEvents($db);
    echo PMA_RTE_getList('event', $items);
    /**
     * Display a link for adding a new event, if
     * the user has the privileges and a link to
     * toggle the state of the event scheduler.
     */
    echo PMA_EVN_getFooterLinks();
} // end PMA_EVN_main()

/**
 * Handles editor requests for adding or editing an item
 *
 * @return void
 */
function PMA_EVN_handleEditor()
{
    global $_REQUEST, $_POST, $errors, $db;

    if (! empty($_REQUEST['editor_process_add'])
        || ! empty($_REQUEST['editor_process_edit'])
    ) {
        $sql_query = '';

        $item_query = PMA_EVN_getQueryFromRequest();

        if (! count($errors)) { // set by PMA_RTN_getQueryFromRequest()
            // Execute the created query
            if (! empty($_REQUEST['editor_process_edit'])) {
                // Backup the old trigger, in case something goes wrong
                $create_item = $GLOBALS['dbi']->getDefinition(
                    $db,
                    'EVENT',
                    $_REQUEST['item_original_name']
                );
                $drop_item = "DROP EVENT "
                    . PMA\libraries\Util::backquote($_REQUEST['item_original_name'])
                    . ";\n";
                $result = $GLOBALS['dbi']->tryQuery($drop_item);
                if (! $result) {
                    $errors[] = sprintf(
                        __('The following query has failed: "%s"'),
                        htmlspecialchars($drop_item)
                    )
                    . '
'
                    . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
                } else {
                    $result = $GLOBALS['dbi']->tryQuery($item_query);
                    if (! $result) {
                        $errors[] = sprintf(
                            __('The following query has failed: "%s"'),
                            htmlspecialchars($item_query)
                        )
                        . '
'
                        . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
                        // We dropped the old item, but were unable to create
                        // the new one. Try to restore the backup query
                        $result = $GLOBALS['dbi']->tryQuery($create_item);
                        $errors = checkResult(
                            $result,
                            __(
                                'Sorry, we failed to restore the dropped event.'
                            ),
                            $create_item,
                            $errors
                        );
                    } else {
                        $message = PMA\libraries\Message::success(
                            __('Event %1$s has been modified.')
                        );
                        $message->addParam(
                            PMA\libraries\Util::backquote($_REQUEST['item_name'])
                        );
                        $sql_query = $drop_item . $item_query;
                    }
                }
            } else {
                // 'Add a new item' mode
                $result = $GLOBALS['dbi']->tryQuery($item_query);
                if (! $result) {
                    $errors[] = sprintf(
                        __('The following query has failed: "%s"'),
                        htmlspecialchars($item_query)
                    )
                    . '

'
                    . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
                } else {
                    $message = PMA\libraries\Message::success(
                        __('Event %1$s has been created.')
                    );
                    $message->addParam(
                        PMA\libraries\Util::backquote($_REQUEST['item_name'])
                    );
                    $sql_query = $item_query;
                }
            }
        }

        if (count($errors)) {
            $message = PMA\libraries\Message::error(
                ''
                . __(
                    'One or more errors have occurred while processing your request:'
                )
                . ''
            );
            $message->addString('
');
            foreach ($errors as $string) {
                $message->addString('
' . $string . '
');
            }
            $message->addString('
');
        }

        $output = PMA\libraries\Util::getMessage($message, $sql_query);
        if ($GLOBALS['is_ajax_request']) {
            $response = PMA\libraries\Response::getInstance();
            if ($message->isSuccess()) {
                $events = $GLOBALS['dbi']->getEvents($db, $_REQUEST['item_name']);
                $event = $events[0];
                $response->addJSON(
                    'name',
                    htmlspecialchars(
                        mb_strtoupper($_REQUEST['item_name'])
                    )
                );
                $response->addJSON('new_row', PMA_EVN_getRowForList($event));
                $response->addJSON('insert', ! empty($event));
                $response->addJSON('message', $output);
            } else {
                $response->setRequestStatus(false);
                $response->addJSON('message', $message);
            }
            exit;
        }
    }
    /**
     * Display a form used to add/edit a trigger, if necessary
     */
    if (count($errors)
        || (empty($_REQUEST['editor_process_add'])
        && empty($_REQUEST['editor_process_edit'])
        && (! empty($_REQUEST['add_item'])
        || ! empty($_REQUEST['edit_item'])
        || ! empty($_REQUEST['item_changetype'])))
    ) { // FIXME: this must be simpler than that
        $operation = '';
        if (! empty($_REQUEST['item_changetype'])) {
            $operation = 'change';
        }
        // Get the data for the form (if any)
        if (! empty($_REQUEST['add_item'])) {
            $title = PMA_RTE_getWord('add');
            $item = PMA_EVN_getDataFromRequest();
            $mode = 'add';
        } else if (! empty($_REQUEST['edit_item'])) {
            $title = __("Edit event");
            if (! empty($_REQUEST['item_name'])
                && empty($_REQUEST['editor_process_edit'])
                && empty($_REQUEST['item_changetype'])
            ) {
                $item = PMA_EVN_getDataFromName($_REQUEST['item_name']);
                if ($item !== false) {
                    $item['item_original_name'] = $item['item_name'];
                }
            } else {
                $item = PMA_EVN_getDataFromRequest();
            }
            $mode = 'edit';
        }
        PMA_RTE_sendEditor('EVN', $mode, $item, $title, $db, $operation);
    }
} // end PMA_EVN_handleEditor()

/**
 * This function will generate the values that are required to for the editor
 *
 * @return array    Data necessary to create the editor.
 */
function PMA_EVN_getDataFromRequest()
{
    $retval = array();
    $indices = array('item_name',
                     'item_original_name',
                     'item_status',
                     'item_execute_at',
                     'item_interval_value',
                     'item_interval_field',
                     'item_starts',
                     'item_ends',
                     'item_definition',
                     'item_preserve',
                     'item_comment',
                     'item_definer');
    foreach ($indices as $index) {
        $retval[$index] = isset($_REQUEST[$index]) ? $_REQUEST[$index] : '';
    }
    $retval['item_type']        = 'ONE TIME';
    $retval['item_type_toggle'] = 'RECURRING';
    if (isset($_REQUEST['item_type']) && $_REQUEST['item_type'] == 'RECURRING') {
        $retval['item_type']        = 'RECURRING';
        $retval['item_type_toggle'] = 'ONE TIME';
    }
    return $retval;
} // end PMA_EVN_getDataFromRequest()

/**
 * This function will generate the values that are required to complete
 * the "Edit event" form given the name of a event.
 *
 * @param string $name The name of the event.
 *
 * @return array Data necessary to create the editor.
 */
function PMA_EVN_getDataFromName($name)
{
    global $db;

    $retval = array();
    $columns = "`EVENT_NAME`, `STATUS`, `EVENT_TYPE`, `EXECUTE_AT`, "
             . "`INTERVAL_VALUE`, `INTERVAL_FIELD`, `STARTS`, `ENDS`, "
             . "`EVENT_DEFINITION`, `ON_COMPLETION`, `DEFINER`, `EVENT_COMMENT`";
    $where   = "EVENT_SCHEMA " . PMA\libraries\Util::getCollateForIS() . "="
             . "'" . $GLOBALS['dbi']->escapeString($db) . "' "
             . "AND EVENT_NAME='" . $GLOBALS['dbi']->escapeString($name) . "'";
    $query   = "SELECT $columns FROM `INFORMATION_SCHEMA`.`EVENTS` WHERE $where;";
    $item    = $GLOBALS['dbi']->fetchSingleRow($query);
    if (! $item) {
        return false;
    }
    $retval['item_name']   = $item['EVENT_NAME'];
    $retval['item_status'] = $item['STATUS'];
    $retval['item_type']   = $item['EVENT_TYPE'];
    if ($retval['item_type'] == 'RECURRING') {
        $retval['item_type_toggle'] = 'ONE TIME';
    } else {
        $retval['item_type_toggle'] = 'RECURRING';
    }
    $retval['item_execute_at']     = $item['EXECUTE_AT'];
    $retval['item_interval_value'] = $item['INTERVAL_VALUE'];
    $retval['item_interval_field'] = $item['INTERVAL_FIELD'];
    $retval['item_starts']         = $item['STARTS'];
    $retval['item_ends']           = $item['ENDS'];
    $retval['item_preserve']       = '';
    if ($item['ON_COMPLETION'] == 'PRESERVE') {
        $retval['item_preserve']   = " checked='checked'";
    }
    $retval['item_definition'] = $item['EVENT_DEFINITION'];
    $retval['item_definer']    = $item['DEFINER'];
    $retval['item_comment']    = $item['EVENT_COMMENT'];

    return $retval;
} // end PMA_EVN_getDataFromName()

/**
 * Displays a form used to add/edit an event
 *
 * @param string $mode      If the editor will be used to edit an event
 *                              or add a new one: 'edit' or 'add'.
 * @param string $operation If the editor was previously invoked with
 *                              JS turned off, this will hold the name of
 *                              the current operation
 * @param array  $item      Data for the event returned by
 *                              PMA_EVN_getDataFromRequest() or
 *                              PMA_EVN_getDataFromName()
 *
 * @return string   HTML code for the editor.
 */
function PMA_EVN_getEditorForm($mode, $operation, $item)
{
    global $db, $table, $event_status, $event_type, $event_interval;

    $modeToUpper = mb_strtoupper($mode);

    // Escape special characters
    $need_escape = array(
                       'item_original_name',
                       'item_name',
                       'item_type',
                       'item_execute_at',
                       'item_interval_value',
                       'item_starts',
                       'item_ends',
                       'item_definition',
                       'item_definer',
                       'item_comment'
                   );
    foreach ($need_escape as $index) {
        $item[$index] = htmlentities($item[$index], ENT_QUOTES);
    }
    $original_data = '';
    if ($mode == 'edit') {
        $original_data = "<input name='item_original_name' "
                       . "type='hidden' value='{$item['item_original_name']}'/>\n";
    }
    // Handle some logic first
    if ($operation == 'change') {
        if ($item['item_type'] == 'RECURRING') {
            $item['item_type']         = 'ONE TIME';
            $item['item_type_toggle']  = 'RECURRING';
        } else {
            $item['item_type']         = 'RECURRING';
            $item['item_type_toggle']  = 'ONE TIME';
        }
    }
    if ($item['item_type'] == 'ONE TIME') {
        $isrecurring_class = ' hide';
        $isonetime_class   = '';
    } else {
        $isrecurring_class = '';
        $isonetime_class   = ' hide';
    }
    // Create the output
    $retval  = "";
    $retval .= "\n\n";
    $retval .= "<form class='rte_form' action='db_events.php' method='post'>\n";
    $retval .= "<input name='{$mode}_item' type='hidden' value='1' />\n";
    $retval .= $original_data;
    $retval .= PMA_URL_getHiddenInputs($db, $table) . "\n";
    $retval .= "<fieldset>\n";
    $retval .= "<legend>" . __('Details') . "</legend>\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "    " . __('Event name') . "	\n";
    $retval .= "    <input type='text' name='item_name' \n";
    $retval .= "               value='{$item['item_name']}'\n";
    $retval .= "               maxlength='64' />	\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "    " . __('Status') . "	\n";
    $retval .= "    \n";
    $retval .= "        <select name='item_status'>\n";
    foreach ($event_status['display'] as $key => $value) {
        $selected = "";
        if (! empty($item['item_status']) && $item['item_status'] == $value) {
            $selected = " selected='selected'";
        }
        $retval .= "<option$selected>$value</option>";
    }
    $retval .= "        </select>\n";
    $retval .= "    	\n";
    $retval .= "
\n";

    $retval .= "
\n";
    $retval .= "    " . __('Event type') . "	\n";
    $retval .= "    \n";
    if ($GLOBALS['is_ajax_request']) {
        $retval .= "        <select name='item_type'>";
        foreach ($event_type as $key => $value) {
            $selected = "";
            if (! empty($item['item_type']) && $item['item_type'] == $value) {
                $selected = " selected='selected'";
            }
            $retval .= "<option$selected>$value</option>";
        }
        $retval .= "        </select>\n";
    } else {
        $retval .= "        <input name='item_type' type='hidden' \n";
        $retval .= "               value='{$item['item_type']}' />\n";
        $retval .= "
\n";
        $retval .= "            {$item['item_type']}\n";
        $retval .= "
\n";
        $retval .= "        <input style='width: 49%;' type='submit'\n";
        $retval .= "               name='item_changetype'\n";
        $retval .= "               value='";
        $retval .= sprintf(__('Change to %s'), $item['item_type_toggle']);
        $retval .= "' />\n";
    }
    $retval .= "    	\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "    " . __('Execute at') . "	\n";
    $retval .= "    \n";
    $retval .= "        <input type='text' name='item_execute_at'\n";
    $retval .= "               value='{$item['item_execute_at']}'\n";
    $retval .= "               class='datetimefield' />\n";
    $retval .= "    	\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "    " . __('Execute every') . "	\n";
    $retval .= "    \n";
    $retval .= "        <input style='width: 49%;' type='text'\n";
    $retval .= "               name='item_interval_value'\n";
    $retval .= "               value='{$item['item_interval_value']}' />\n";
    $retval .= "        <select style='width: 49%;' name='item_interval_field'>";
    foreach ($event_interval as $key => $value) {
        $selected = "";
        if (! empty($item['item_interval_field'])
            && $item['item_interval_field'] == $value
        ) {
            $selected = " selected='selected'";
        }
        $retval .= "<option$selected>$value</option>";
    }
    $retval .= "        </select>\n";
    $retval .= "    	\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "    " . _pgettext('Start of recurring event', 'Start');
    $retval .= "    	\n";
    $retval .= "    \n";
    $retval .= "        <input type='text'\n name='item_starts'\n";
    $retval .= "               value='{$item['item_starts']}'\n";
    $retval .= "               class='datetimefield' />\n";
    $retval .= "    	\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "    " . _pgettext('End of recurring event', 'End') . "	\n";
    $retval .= "    \n";
    $retval .= "        <input type='text' name='item_ends'\n";
    $retval .= "               value='{$item['item_ends']}'\n";
    $retval .= "               class='datetimefield' />\n";
    $retval .= "    	\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "    " . __('Definition') . "	\n";
    $retval .= "    <textarea name='item_definition' rows='15' cols='40'>";
    $retval .= $item['item_definition'];
    $retval .= "</textarea>	\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "    " . __('On completion preserve') . "	\n";
    $retval .= "    <input type='checkbox'\n";
    $retval .= "             name='item_preserve'{$item['item_preserve']} />	\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "    " . __('Definer') . "	\n";
    $retval .= "    <input type='text' name='item_definer'\n";
    $retval .= "               value='{$item['item_definer']}' />	\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "    " . __('Comment') . "	\n";
    $retval .= "    <input type='text' name='item_comment' maxlength='64'\n";
    $retval .= "               value='{$item['item_comment']}' />	\n";
    $retval .= "
\n";
    $retval .= "
\n";
    $retval .= "</fieldset>\n";
    if ($GLOBALS['is_ajax_request']) {
        $retval .= "<input type='hidden' name='editor_process_{$mode}'\n";
        $retval .= "       value='true' />\n";
        $retval .= "<input type='hidden' name='ajax_request' value='true' />\n";
    } else {
        $retval .= "<fieldset class='tblFooters'>\n";
        $retval .= "    <input type='submit' name='editor_process_{$mode}'\n";
        $retval .= "           value='" . __('Go') . "' />\n";
        $retval .= "</fieldset>\n";
    }
    $retval .= "</form>\n\n";
    $retval .= "\n\n";

    return $retval;
} // end PMA_EVN_getEditorForm()

/**
 * Composes the query necessary to create an event from an HTTP request.
 *
 * @return string  The CREATE EVENT query.
 */
function PMA_EVN_getQueryFromRequest()
{
    global $_REQUEST, $errors, $event_status, $event_type, $event_interval;

    $query = 'CREATE ';
    if (! empty($_REQUEST['item_definer'])) {
        if (mb_strpos($_REQUEST['item_definer'], '@') !== false
        ) {
            $arr = explode('@', $_REQUEST['item_definer']);
            $query .= 'DEFINER=' . PMA\libraries\Util::backquote($arr[0]);
            $query .= '@' . PMA\libraries\Util::backquote($arr[1]) . ' ';
        } else {
            $errors[] = __('The definer must be in the "username@hostname" format!');
        }
    }
    $query .= 'EVENT ';
    if (! empty($_REQUEST['item_name'])) {
        $query .= PMA\libraries\Util::backquote($_REQUEST['item_name']) . ' ';
    } else {
        $errors[] = __('You must provide an event name!');
    }
    $query .= 'ON SCHEDULE ';
    if (! empty($_REQUEST['item_type'])
        && in_array($_REQUEST['item_type'], $event_type)
    ) {
        if ($_REQUEST['item_type'] == 'RECURRING') {
            if (! empty($_REQUEST['item_interval_value'])
                && !empty($_REQUEST['item_interval_field'])
                && in_array($_REQUEST['item_interval_field'], $event_interval)
            ) {
                $query .= 'EVERY ' . intval($_REQUEST['item_interval_value']) . ' ';
                $query .= $_REQUEST['item_interval_field'] . ' ';
            } else {
                $errors[]
                    = __('You must provide a valid interval value for the event.');
            }
            if (! empty($_REQUEST['item_starts'])) {
                $query .= "STARTS '"
                    . $GLOBALS['dbi']->escapeString($_REQUEST['item_starts'])
                    . "' ";
            }
            if (! empty($_REQUEST['item_ends'])) {
                $query .= "ENDS '"
                    . $GLOBALS['dbi']->escapeString($_REQUEST['item_ends'])
                    . "' ";
            }
        } else {
            if (! empty($_REQUEST['item_execute_at'])) {
                $query .= "AT '"
                    . $GLOBALS['dbi']->escapeString($_REQUEST['item_execute_at'])
                    . "' ";
            } else {
                $errors[]
                    = __('You must provide a valid execution time for the event.');
            }
        }
    } else {
        $errors[] = __('You must provide a valid type for the event.');
    }
    $query .= 'ON COMPLETION ';
    if (empty($_REQUEST['item_preserve'])) {
        $query .= 'NOT ';
    }
    $query .= 'PRESERVE ';
    if (! empty($_REQUEST['item_status'])) {
        foreach ($event_status['display'] as $key => $value) {
            if ($value == $_REQUEST['item_status']) {
                $query .= $event_status['query'][$key] . ' ';
                break;
            }
        }
    }
    if (! empty($_REQUEST['item_comment'])) {
        $query .= "COMMENT '" . $GLOBALS['dbi']->escapeString(
            $_REQUEST['item_comment']
        ) . "' ";
    }
    $query .= 'DO ';
    if (! empty($_REQUEST['item_definition'])) {
        $query .= $_REQUEST['item_definition'];
    } else {
        $errors[] = __('You must provide an event definition.');
    }

    return $query;
} // end PMA_EVN_getQueryFromRequest()


text:
package org.wso2.am.integration.tests.api.lifecycle;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
import org.wso2.am.integration.test.utils.bean.APICreationRequestBean;
import org.wso2.am.integration.test.utils.bean.APILifeCycleState;
import org.wso2.am.integration.test.utils.bean.APILifeCycleStateRequest;
import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient;
import org.wso2.am.integration.test.utils.clients.APIStoreRestClient;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;

import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

/**
 * "Block an API and check its accessibility in the API Store."
 */
public class AccessibilityOfBlockAPITestCase extends APIManagerLifecycleBaseTest {

    private static final String API_NAME = "BlockAPITest";
    private static final String API_CONTEXT = "BlockAPI";
    private static final String API_TAGS = "testTag1, testTag2, testTag3";
    private static final String API_DESCRIPTION = "This is test API create by API manager integration test";
    private static final String API_END_POINT_METHOD = "/customers/123";
    private static final String API_RESPONSE_DATA = "<id>123</id><name>John</name></Customer>";
    private static final String API_VERSION_1_0_0 = "1.0.0";
    private static final String APPLICATION_NAME = "AccessibilityOfBlockAPITestCase";
    private static final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/";
    private String apiEndPointUrl;
    private APIIdentifier apiIdentifier;
    private String providerName;
    private APICreationRequestBean apiCreationRequestBean;
    private Map<String, String> requestHeaders;
    private APIPublisherRestClient apiPublisherClientUser1;
    private APIStoreRestClient apiStoreClientUser1;

    @BeforeClass(alwaysRun = true)
    public void initialize() throws APIManagerIntegrationTestException, XPathExpressionException, MalformedURLException {
        super.init();
        apiEndPointUrl = gatewayUrls.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL;
        providerName = publisherContext.getContextTenant().getContextUser().getUserName();
        apiCreationRequestBean =
                new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl));
        apiCreationRequestBean.setTags(API_TAGS);
        apiCreationRequestBean.setDescription(API_DESCRIPTION);
        String publisherURLHttp = publisherUrls.getWebAppURLHttp();
        String storeURLHttp = storeUrls.getWebAppURLHttp();
        apiPublisherClientUser1 = new APIPublisherRestClient(publisherURLHttp);
        apiStoreClientUser1 = new APIStoreRestClient(storeURLHttp);
        //Login to API Publisher with  admin
        apiPublisherClientUser1.login(
                publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());
        //Login to API Store with  admin
        apiStoreClientUser1.login(
                storeContext.getContextTenant().getContextUser().getUserName(),
                storeContext.getContextTenant().getContextUser().getPassword());
        apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION_1_0_0);
        apiStoreClientUser1.addApplication(APPLICATION_NAME, "", "", "");
    }

    @Test(groups = {"wso2.am"}, description = "Test invocation of the APi before block")
    public void testInvokeAPIBeforeChangeAPILifecycleToBlock() throws APIManagerIntegrationTestException, IOException {
        //Create and publish  and subscribe API version 1.0.0
        createPublishAndSubscribeToAPI(
                apiIdentifier, apiCreationRequestBean, apiPublisherClientUser1, apiStoreClientUser1, APPLICATION_NAME);
        //get access token
        String accessToken = generateApplicationKeys(apiStoreClientUser1, APPLICATION_NAME).getAccessToken();
        // Create requestHeaders
        requestHeaders = new HashMap<String, String>();
        requestHeaders.put("accept", "text/xml");
        requestHeaders.put("Authorization", "Bearer " + accessToken);
        //Invoke  old version
        HttpResponse oldVersionInvokeResponse =
                HttpRequestUtil.doGet(gatewayWebAppUrl + API_CONTEXT + "/" +
                        API_VERSION_1_0_0 + API_END_POINT_METHOD, requestHeaders);
        assertEquals(oldVersionInvokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK,
                "Response code mismatched when invoke api before block");
        assertTrue(oldVersionInvokeResponse.getData().contains(API_RESPONSE_DATA),
                "Response data mismatched when invoke  API  before block" +
                        " Response Data:" + oldVersionInvokeResponse.getData());
    }

    @Test(groups = {"wso2.am"}, description = "Change API lifecycle to block",
            dependsOnMethods = "testInvokeAPIBeforeChangeAPILifecycleToBlock")
    public void testChangeAPILifecycleToBlock() throws APIManagerIntegrationTestException {
        //Block the API version 1.0.0
        APILifeCycleStateRequest blockUpdateRequest =
                new APILifeCycleStateRequest(API_NAME, providerName, APILifeCycleState.BLOCKED);
        blockUpdateRequest.setVersion(API_VERSION_1_0_0);
        //Change API lifecycle  to Block
        HttpResponse blockAPIActionResponse =
                apiPublisherClientUser1.changeAPILifeCycleStatus(blockUpdateRequest);
        assertEquals(blockAPIActionResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK, "Response code mismatched");
        assertTrue(verifyAPIStatusChange(blockAPIActionResponse, APILifeCycleState.PUBLISHED,
                APILifeCycleState.BLOCKED), "API status Change is invalid when block an API :" +
                getAPIIdentifierString(apiIdentifier) + " Response Code:" + blockAPIActionResponse.getData());
    }

    @Test(groups = {"wso2.am"}, description = "Invocation og the APi after block",
            dependsOnMethods = "testChangeAPILifecycleToBlock")
    public void testInvokeAPIAfterChangeAPILifecycleToBlock() throws APIManagerIntegrationTestException, IOException {
        //Invoke  old version
        HttpResponse oldVersionInvokeResponse =
                HttpRequestUtil.doGet(gatewayWebAppUrl + API_CONTEXT + "/" + API_VERSION_1_0_0 + API_END_POINT_METHOD,
                        requestHeaders);
        assertEquals(oldVersionInvokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_SERVICE_UNAVAILABLE,
                "Response code mismatched when invoke api after block");
        assertTrue(oldVersionInvokeResponse.getData().contains(HTTP_RESPONSE_DATA_API_BLOCK),
                "Response data mismatched when invoke  API  after block" +
                        " Response Data:" + oldVersionInvokeResponse.getData());
    }

    @AfterClass(alwaysRun = true)
    public void cleanUpArtifacts() throws APIManagerIntegrationTestException {
        apiStoreClientUser1.removeApplication(APPLICATION_NAME);
        deleteAPI(apiIdentifier, apiPublisherClientUser1);
    }

}


text:
import json
import time

import kombu.connection
import kombu.entity

from glance.notifier import strategy
from glance.openstack.common import cfg
import glance.openstack.common.log as logging

LOG = logging.getLogger(__name__)

rabbit_opts = [
    cfg.StrOpt('rabbit_host', default='localhost'),
    cfg.IntOpt('rabbit_port', default=5672),
    cfg.BoolOpt('rabbit_use_ssl', default=False),
    cfg.StrOpt('rabbit_userid', default='guest'),
    cfg.StrOpt('rabbit_password', default='guest'),
    cfg.StrOpt('rabbit_virtual_host', default='/'),
    cfg.StrOpt('rabbit_notification_exchange', default='glance'),
    cfg.StrOpt('rabbit_notification_topic',
               default='glance_notifications'),
    cfg.StrOpt('rabbit_max_retries', default=0),
    cfg.StrOpt('rabbit_retry_backoff', default=2),
    cfg.StrOpt('rabbit_retry_max_backoff', default=30),
    cfg.BoolOpt('rabbit_durable_queues', default=False),
]

CONF = cfg.CONF
CONF.register_opts(rabbit_opts)

class KombuMaxRetriesReached(Exception):
    pass

class RabbitStrategy(strategy.Strategy):
    """A notifier that puts a message on a queue when called."""

    def __init__(self):
        """Initialize the rabbit notification strategy."""
        self.topic = CONF.rabbit_notification_topic
        self.max_retries = CONF.rabbit_max_retries
        # NOTE(comstud): When reading the config file, these values end
        # up being strings, and we need them as ints.
        self.retry_backoff = int(CONF.rabbit_retry_backoff)
        self.retry_max_backoff = int(CONF.rabbit_retry_max_backoff)

        self.connection = None
        self.retry_attempts = 0
        try:
            self.reconnect()
        except KombuMaxRetriesReached:
            pass

    def _close(self):
        """Close connection to rabbit."""
        try:
            self.connection.close()
        except self.connection_errors:
            pass
        self.connection = None

    def _connect(self):
        """Connect to rabbit.  Exceptions should be handled by the
        caller.
        """
        log_info = {}
        log_info['hostname'] = CONF.rabbit_host
        log_info['port'] = CONF.rabbit_port
        if self.connection:
            LOG.info(_("Reconnecting to AMQP server on "
                       "%(hostname)s:%(port)d") % log_info)
            self._close()
        else:
            LOG.info(_("Connecting to AMQP server on "
                       "%(hostname)s:%(port)d") % log_info)
        self.connection = kombu.connection.BrokerConnection(
                hostname=CONF.rabbit_host,
                port=CONF.rabbit_port,
                userid=CONF.rabbit_userid,
                password=CONF.rabbit_password,
                virtual_host=CONF.rabbit_virtual_host,
                ssl=CONF.rabbit_use_ssl)
        self.connection_errors = self.connection.connection_errors
        self.connection.connect()
        self.channel = self.connection.channel()
        self.exchange = kombu.entity.Exchange(
                channel=self.channel,
                type="topic",
                durable=CONF.rabbit_durable_queues,
                name=CONF.rabbit_notification_exchange)

        # NOTE(jerdfelt): Normally the consumer would create the queues,
        # but we do this to ensure that messages don't get dropped if the
        # consumer is started after we do
        for priority in ["WARN", "INFO", "ERROR"]:
            routing_key = "%s.%s" % (self.topic, priority.lower())
            queue = kombu.entity.Queue(
                    channel=self.channel,
                    exchange=self.exchange,
                    durable=CONF.rabbit_durable_queues,
                    name=routing_key,
                    routing_key=routing_key)
            queue.declare()
        LOG.info(_("Connected to AMQP server on "
                   "%(hostname)s:%(port)d") % log_info)

    def reconnect(self):
        """Handles reconnecting and re-establishing queues."""
        while True:
            self.retry_attempts += 1
            try:
                self._connect()
                return
            except self.connection_errors, e:
                pass
            except Exception, e:
                # NOTE(comstud): Unfortunately it's possible for amqplib
                # to return an error not covered by its transport
                # connection_errors in the case of a timeout waiting for
                # a protocol response.  (See paste link in LP888621 for
                # nova.)  So, we check all exceptions for 'timeout' in them
                # and try to reconnect in this case.
                if 'timeout' not in str(e):
                    raise

            log_info = {}
            log_info['err_str'] = str(e)
            log_info['max_retries'] = self.max_retries
            log_info['hostname'] = CONF.rabbit_host
            log_info['port'] = CONF.rabbit_port

            if self.max_retries and self.retry_attempts >= self.max_retries:
                LOG.exception(_('Unable to connect to AMQP server on '
                                '%(hostname)s:%(port)d after %(max_retries)d '
                                'tries: %(err_str)s') % log_info)
                if self.connection:
                    self._close()
                raise KombuMaxRetriesReached

            sleep_time = self.retry_backoff * self.retry_attempts
            if self.retry_max_backoff:
                sleep_time = min(sleep_time, self.retry_max_backoff)

            log_info['sleep_time'] = sleep_time
            LOG.exception(_('AMQP server on %(hostname)s:%(port)d is'
                            ' unreachable: %(err_str)s. Trying again in '
                            '%(sleep_time)d seconds.') % log_info)
            time.sleep(sleep_time)

    def log_failure(self, msg, priority):
        """Fallback to logging when we can't send to rabbit."""
        message = _('Notification with priority %(priority)s failed: '
                    'msg=%(msg)s')
        LOG.error(message % {'msg': msg, 'priority': priority})

    def _send_message(self, msg, routing_key):
        """Send a message.  Caller needs to catch exceptions for retry."""
        msg = self.exchange.Message(json.dumps(msg),
                                    content_type='application/json')
        self.exchange.publish(msg, routing_key=routing_key)

    def _notify(self, msg, priority):
        """Send a notification and retry if needed."""
        self.retry_attempts = 0

        if not self.connection:
            try:
                self.reconnect()
            except KombuMaxRetriesReached:
                self.log_failure(msg, priority)
                return

        routing_key = "%s.%s" % (self.topic, priority.lower())

        while True:
            try:
                self._send_message(msg, routing_key)
                return
            except self.connection_errors, e:
                pass
            except Exception, e:
                # NOTE(comstud): Unfortunately it's possible for amqplib
                # to return an error not covered by its transport
                # connection_errors in the case of a timeout waiting for
                # a protocol response.  (See paste link in LP888621 for
                # nova.)  So, we check all exceptions for 'timeout' in them
                # and try to reconnect in this case.
                if 'timeout' not in str(e):
                    raise

            LOG.exception(_("Unable to send notification: %s") % str(e))

            try:
                self.reconnect()
            except KombuMaxRetriesReached:
                break
        self.log_failure(msg, priority)

    def warn(self, msg):
        self._notify(msg, "WARN")

    def info(self, msg):
        self._notify(msg, "INFO")

    def error(self, msg):
        self._notify(msg, "ERROR")


text:
package com.salesforce.pyplyn.duct.appconfig;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.salesforce.pyplyn.util.SerializationHelper;

/**
 * Provides an app config object
 *

 *
Deserializes the specified configuration file and stores the generated config object
 *
 * @author Mihai Bojin <mbojin@salesforce.com>
 * @since 3.0
 */
public class AppConfigProvider implements Provider<AppConfig> {
    private final AppConfig appConfig;

    @Inject
    public AppConfigProvider(@Named("config") String configFile, ObjectMapper mapper) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        // TODO: simplify this / move to modules
        appConfig = mapper.readValue(SerializationHelper.loadResourceInsecure(configFile), AppConfig.class);
    }

    @Override
    public AppConfig get() {
        return appConfig;
    }
}


text:
package org.apache.jena.query.text.changes;

import org.apache.jena.graph.Node ;

/** Count changes, or simply note if a change has been made.
 */
public class ChangesCounter implements TextDatasetChanges
{
    public long countStart    = 0 ;
    public long countFinish   = 0 ;

    public long countAdd      = 0 ;
    public long countDelete   = 0 ;
    public long countNoAdd    = 0 ;
    public long countNoDelete = 0 ;

    @Override
    public void start() {
        countStart++ ;
    }

    @Override
    public void change(TextQuadAction qaction, Node g, Node s, Node p, Node o) {
        if ( qaction == null )
            throw new NullPointerException() ;
        switch (qaction) {
            case ADD:       countAdd++ ; break ;
            case DELETE:    countDelete++ ; break ;
            case NO_ADD:    countNoAdd++ ; break ;
            case NO_DELETE: countNoDelete++ ; break ;
            //default : break ;
        }
    }

    @Override
    public void finish() {
        countFinish++ ;
    }

    public boolean hasChanged() {
        return countAdd > 0 || countDelete > 0 ;
    }

    @Override
    public void reset() {
        countStart    = 0 ;
        countFinish   = 0 ;

        countAdd      = 0 ;
        countDelete   = 0 ;
        countNoAdd    = 0 ;
        countNoDelete = 0 ;
    }
}


text:
package model

import (
	"sync"

	"istio.io/istio/pkg/cluster"
)

// Controller defines an event controller loop.  Proxy agent registers itself
// with the controller loop and receives notifications on changes to the
// service topology or changes to the configuration artifacts.
//
// The controller guarantees the following consistency requirement: registry
// view in the controller is as AT LEAST as fresh as the moment notification
// arrives, but MAY BE more fresh (e.g. "delete" cancels an "add" event).  For
// example, an event for a service creation will see a service registry without
// the service if the event is immediately followed by the service deletion
// event.
//
// Handlers execute on the single worker queue in the order they are appended.
// Handlers receive the notification event and the associated object.  Note
// that all handlers must be appended before starting the controller.
type Controller interface {
	// Note: AppendXXXHandler is used to register high level handlers.
	// For per cluster handlers, they should be registered by the `AppendXXXHandlerForCluster` interface.

	// AppendServiceHandler notifies about changes to the service catalog.
	AppendServiceHandler(f func(*Service, Event))

	// AppendWorkloadHandler notifies about changes to workloads. This differs from InstanceHandler,
	// which deals with service instances (the result of a merge of Service and Workload)
	AppendWorkloadHandler(f func(*WorkloadInstance, Event))

	// Run until a signal is received
	Run(stop <-chan struct{})

	// HasSynced returns true after initial cache synchronization is complete
	HasSynced() bool
}

// AggregateController is a wrapper of Controller, it supports registering handlers of a specific cluster。
type AggregateController interface {
	Controller
	// AppendServiceHandlerForCluster is similar to Controller.AppendServiceHandler,
	// but it is used to store the handler from a specific cluster.
	AppendServiceHandlerForCluster(clusterID cluster.ID, f func(*Service, Event))
	// AppendWorkloadHandlerForCluster is similar to Controller.AppendWorkloadHandler,
	// but it is used to store the handler from a specific cluster.
	AppendWorkloadHandlerForCluster(clusterID cluster.ID, f func(*WorkloadInstance, Event))
	UnRegisterHandlersForCluster(clusterID cluster.ID)
}

// ControllerHandlers is a utility to help Controller implementations manage their lists of handlers.
type ControllerHandlers struct {
	mutex            sync.RWMutex
	serviceHandlers  []func(*Service, Event)
	workloadHandlers []func(*WorkloadInstance, Event)
}

func (c *ControllerHandlers) AppendServiceHandler(f func(*Service, Event)) {
	// Copy on write.
	c.mutex.Lock()
	handlers := make([]func(*Service, Event), 0, len(c.serviceHandlers)+1)
	handlers = append(handlers, c.serviceHandlers...)
	handlers = append(handlers, f)
	c.serviceHandlers = handlers
	c.mutex.Unlock()
}

func (c *ControllerHandlers) AppendWorkloadHandler(f func(*WorkloadInstance, Event)) {
	// Copy on write.
	c.mutex.Lock()
	handlers := make([]func(*WorkloadInstance, Event), 0, len(c.workloadHandlers)+1)
	handlers = append(handlers, c.workloadHandlers...)
	handlers = append(handlers, f)
	c.workloadHandlers = handlers
	c.mutex.Unlock()
}

func (c *ControllerHandlers) GetServiceHandlers() []func(*Service, Event) {
	c.mutex.RLock()
	defer c.mutex.RUnlock()
	// Return a shallow copy of the array
	return c.serviceHandlers
}

func (c *ControllerHandlers) GetWorkloadHandlers() []func(*WorkloadInstance, Event) {
	c.mutex.RLock()
	defer c.mutex.RUnlock()
	// Return a shallow copy of the array
	return c.workloadHandlers
}

func (c *ControllerHandlers) NotifyServiceHandlers(svc *Service, event Event) {
	for _, f := range c.GetServiceHandlers() {
		f(svc, event)
	}
}

func (c *ControllerHandlers) NotifyWorkloadHandlers(w *WorkloadInstance, event Event) {
	for _, f := range c.GetWorkloadHandlers() {
		f(w, event)
	}
}

// Event represents a registry update event
type Event int

const (
	// EventAdd is sent when an object is added
	EventAdd Event = iota

	// EventUpdate is sent when an object is modified
	// Captures the modified object
	EventUpdate

	// EventDelete is sent when an object is deleted
	// Captures the object at the last known state
	EventDelete
)

func (event Event) String() string {
	out := "unknown"
	switch event {
	case EventAdd:
		out = "add"
	case EventUpdate:
		out = "update"
	case EventDelete:
		out = "delete"
	}
	return out
}


text:
When tracking the memory usage of a process using an application like `top`,
the usage statistics will be broken down into a number of subcategories.
These subcategories give insight regarding where the process' data has been
allocated and how the operating system is handling this allocation.  The
following list describes the meaning of each subcategory in detail:

- **Virtual Memory**: The space of memory that has been allocated by the process
  but not necessarily mapped to physical memory by the operating system.  This
  category generally applies to memory that has been allocated (e.g. using `malloc`
  or `mmap` in C) but not yet read/written.
- **Resident Memory**: The space of memory that has been mapped to physical
  memory by the operating system.  This set of memory can be thought of as the
  "live" memory for the process.
- **Shared Memory**: The space of memory that spans the subset of the virtual
  memory that can be shared with other processes.  Generally, the memory that
  falls into this category is memory used by loading shared libraries (primarily
  their binary symbols).

### Memory Workflow ###

Within an application, memory allocations will cause the process' **virtual memory**
space to expand.  When this memory is accessed or written to by the process,
this memory will become **resident memory** for the machine as well.  The amount
of **resident memory** for any given process will fluctuate based on the process
environment for the machine and may shrink if many rival applications begin to
consume memory concurrently.

While the unknown environment of the host machine makes it hard to optimize a
process' memory usage in all cases, there are a number of strategies that can
be followed to improve memory performance:

- Allocate most (if not all) of the application's memory on initialization.
  This ensure that the application's memory blocks are subsequent, which
  greatly helps with cache performance.
- Allocate memory for structures that are commonly used together in adjacent
  or near-adjacent memory blocks, which will also help with cache performance.

### Resources ###

The information for this listing was pulled from the following resources:

- [Server Fault: What Does Virtual Memory Size Mean?](https://serverfault.com/a/138625)
- [MG's Notes: VIRT, RES, and SHR Memory](http://mugurel.sumanariu.ro/linux/the-difference-among-virt-res-and-shr-in-top-output/)
- [Stack Overflow: What are RSS and VSZ in Linux Memory Management?](https://stackoverflow.com/a/21049737/837221)


text:
import * as React from "react";
import classNames from "classnames/dedupe";

import { omit } from "../../utils/Util";

export default (
  props: { inputRef?: string } & React.InputHTMLAttributes<HTMLInputElement>
) => {
  const { className, inputRef, type = "text" } = props;
  const classes = classNames("form-control", className);

  const toggleIndicator = ["radio", "checkbox"].includes(type) ? (

  ) : null;

  return (

      <input
        className={classes}
        ref={inputRef}
        {...omit(props, ["className", "inputRef"])}
      />
      {toggleIndicator}

  );
};


text:
#ifndef __nFRC_2015_1_0_A_Alarm_h__
#define __nFRC_2015_1_0_A_Alarm_h__

#include "tSystemInterface.h"

namespace nFPGA
{
namespace nFRC_2015_1_0_A
{

class tAlarm
{
public:
   tAlarm(){}
   virtual ~tAlarm(){}

   virtual tSystemInterface* getSystemInterface() = 0;
   static tAlarm* create(tRioStatusCode *status);

   typedef enum
   {
      kNumSystems = 1,
   } tIfaceConstants;

   typedef enum
   {
   } tEnable_IfaceConstants;

   virtual void writeEnable(bool value, tRioStatusCode *status) = 0;
   virtual bool readEnable(tRioStatusCode *status) = 0;

   typedef enum
   {
   } tTriggerTime_IfaceConstants;

   virtual void writeTriggerTime(unsigned int value, tRioStatusCode *status) = 0;
   virtual unsigned int readTriggerTime(tRioStatusCode *status) = 0;

private:
   tAlarm(const tAlarm&);
   void operator=(const tAlarm&);
};

}
}

#endif // __nFRC_2015_1_0_A_Alarm_h__


text:
<?php
namespace Apikr\SKPlanet\TMap\Exception;

use Exception;

class NotFoundGeocodingException extends TMapException
{
    /** @var string */
    protected $address;

    public function __construct($address, $message = '', $code = 0, Exception $previous = null)
    {
        $this->address = $address;
        parent::__construct($message, $code, $previous);
    }

    /**
     * @return string
     */
    public function getAddress()
    {
        return $this->address;
    }
}