text:
layout: post
title: "Oracle Recovery 02 - Controlfile"
category: Oracle
tags: Oracle BBED controlfile
---

* content
{:toc}

Oracle - Recovery 02 - Controlfile

All of controlfiles are removed. ----> How to recovery?

### Prepare Test Case

Archive log mode/db is read write/backup create controlfile sql.

	SYS@orcl11g> archive log list;
	Database log mode              Archive Mode
	Automatic archival             Enabled
	Archive destination            USE_DB_RECOVERY_FILE_DEST
	Oldest online log sequence     56
	Next log sequence to archive   58
	Current log sequence           58
	SYS@orcl11g>
	SYS@orcl11g> select open_mode from v$database;

	OPEN_MODE
	--------------------
	READ WRITE

	SYS@orcl11g> set line 150 pagesize 9999
	SYS@orcl11g> col name for a60
	SYS@orcl11g> select * from v$controlfile;

	STATUS  NAME                                                         IS_ BLOCK_SIZE FILE_SIZE_BLKS
	------- ------------------------------------------------------------ --- ---------- --------------
			/u01/app/oracle/oradata/orcl11g/control01.ctl                NO       16384            594
			/u01/app/oracle/fast_recovery_area/orcl11g/control02.ctl     NO       16384            594

	SYS@orcl11g>

Also backup the controlfile sql;

	SYS@orcl11g> alter database backup controlfile to trace as '/home/oracle/orcl11g.control.bak.sql';

	Database altered.

	SYS@orcl11g>

### Simulate to remove all controlfiles

Use OS command - rm to remove controlfiles

	[oracle@databasevm001 ~]$ rm /u01/app/oracle/oradata/orcl11g/control01.ctl
	[oracle@databasevm001 ~]$ rm /u01/app/oracle/fast_recovery_area/orcl11g/control02.ctl

Switch logfile in instance, also the checkpoint.

	SYS@orcl11g> alter system switch logfile;

	System altered.

	SYS@orcl11g> /

	System altered.

	SYS@orcl11g> /

	System altered.

	SYS@orcl11g> alter system checkpoint;

	System altered.

	SYS@orcl11g> /

	System altered.

	SYS@orcl11g> /

	System altered.

	SYS@orcl11g>

### Shutdown / Open Database

There was an error while shutdown the instance.

	SYS@orcl11g> shu immediate
	Database closed.
	ORA-00210: cannot open the specified control file
	ORA-00202: control file: '/u01/app/oracle/oradata/orcl11g/control01.ctl'
	ORA-27041: unable to open file
	Linux Error: 2: No such file or directory
	Additional information: 3

	SYS@orcl11g> !ps -ef | grep smon
	oracle    2074     1  0 15:25 ?        00:00:00 ora_smon_orcl11g
	oracle    2291  2044  0 15:53 pts/3    00:00:00 /bin/bash -c ps -ef | grep smon
	oracle    2293  2291  0 15:53 pts/3    00:00:00 grep smon

	SYS@orcl11g> shu abort
	ORACLE instance shut down.
	SYS@orcl11g>

There also was an error while startup instance.

	SYS@orcl11g> startup
	ORACLE instance started.

	Total System Global Area 1556787200 bytes
	Fixed Size                  1364844 bytes
	Variable Size             889195668 bytes
	Database Buffers          654311424 bytes
	Redo Buffers               11915264 bytes
	ORA-00205: error in identifying control file, check alert log for more info

	SYS@orcl11g>

The alert log: ORA-27037

	MMNL started with pid=16, OS id=2330
	starting up 1 dispatcher(s) for network address '(ADDRESS=(PARTIAL=YES)(PROTOCOL=TCP))'...
	starting up 1 shared server(s) ...
	ORACLE_BASE from environment = /u01/app/oracle
	Wed May 23 15:54:45 2018
	ALTER DATABASE   MOUNT
	ORA-00210: cannot open the specified control file
	ORA-00202: control file: '/u01/app/oracle/fast_recovery_area/orcl11g/control02.ctl'
	ORA-27037: unable to obtain file status
	Linux Error: 2: No such file or directory
	Additional information: 3
	ORA-00210: cannot open the specified control file
	ORA-00202: control file: '/u01/app/oracle/oradata/orcl11g/control01.ctl'
	ORA-27037: unable to obtain file status
	Linux Error: 2: No such file or directory
	Additional information: 3
	ORA-205 signalled during: ALTER DATABASE   MOUNT...
	Wed May 23 15:54:45 2018
	Checker run found 2 new persistent data failures

+++++++++++++++++++++++++++++++++++++++++

FD in os:

	[oracle@databasevm001 ~]$ ps -ef | grep ckpt | grep -v grep
	oracle    2072     1  0 15:25 ?        00:00:00 ora_ckpt_orcl11g
	[oracle@databasevm001 ~]$ cd /proc/2072/fd
	[oracle@databasevm001 fd]$ ls -ltr
	total 0
	lrwx------. 1 oracle oinstall 64 May 23 15:50 9 -> /u01/app/oracle/product/11.2.0.4/dbhome_1/dbs/hc_orcl11g.dat
	lr-x------. 1 oracle oinstall 64 May 23 15:50 8 -> /dev/zero
	lr-x------. 1 oracle oinstall 64 May 23 15:50 7 -> /proc/2072/fd
	lr-x------. 1 oracle oinstall 64 May 23 15:50 6 -> /u01/app/oracle/product/11.2.0.4/dbhome_1/rdbms/mesg/oraus.msb
	lr-x------. 1 oracle oinstall 64 May 23 15:50 5 -> /dev/null
	lr-x------. 1 oracle oinstall 64 May 23 15:50 4 -> /dev/null
	lr-x------. 1 oracle oinstall 64 May 23 15:50 3 -> /dev/null
	lrwx------. 1 oracle oinstall 64 May 23 15:50 262 -> /u01/app/oracle/oradata/orcl11g/data01.dbf
	lrwx------. 1 oracle oinstall 64 May 23 15:50 261 -> /u01/app/oracle/oradata/orcl11g/users01.dbf
	lrwx------. 1 oracle oinstall 64 May 23 15:50 260 -> /u01/app/oracle/oradata/orcl11g/undotbs01.dbf
	lrwx------. 1 oracle oinstall 64 May 23 15:50 259 -> /u01/app/oracle/oradata/orcl11g/sysaux01.dbf
	lrwx------. 1 oracle oinstall 64 May 23 15:50 258 -> /u01/app/oracle/oradata/orcl11g/system01.dbf
	lrwx------. 1 oracle oinstall 64 May 23 15:50 257 -> /u01/app/oracle/fast_recovery_area/orcl11g/control02.ctl (deleted)
	lrwx------. 1 oracle oinstall 64 May 23 15:50 256 -> /u01/app/oracle/oradata/orcl11g/control01.ctl (deleted)
	l-wx------. 1 oracle oinstall 64 May 23 15:50 2 -> /dev/null
	lr-x------. 1 oracle oinstall 64 May 23 15:50 11 -> /u01/app/oracle/product/11.2.0.4/dbhome_1/rdbms/mesg/oraus.msb
	lrwx------. 1 oracle oinstall 64 May 23 15:50 10 -> /u01/app/oracle/product/11.2.0.4/dbhome_1/dbs/lkORCL11G
	l-wx------. 1 oracle oinstall 64 May 23 15:50 1 -> /dev/null
	lr-x------. 1 oracle oinstall 64 May 23 15:50 0 -> /dev/null
	[oracle@databasevm001 fd]$

+++++++++++++++++++++++++++++++++++++

### Get the Database informations.

Database Name,Character set etc.

	SYS@orcl11g> select status from v$instance;

	STATUS
	------------
	STARTED

	SYS@orcl11g> show parameter db_name

	NAME                                 TYPE        VALUE
	------------------------------------ ----------- ------------------------------
	db_name                              string      orcl11g
	SYS@orcl11g>
	SYS@orcl11g> select * from v$version;

	BANNER
	--------------------------------------------------------------------------------
	Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - Production
	PL/SQL Release 11.2.0.4.0 - Production
	CORE    11.2.0.4.0      Production
	TNS for Linux: Version 11.2.0.4.0 - Production
	NLSRTL Version 11.2.0.4.0 - Production

	SYS@orcl11g>

Use the same version DB to check the following sql and confirm with the block position.

	+++++++++++++++++++++++++++++
	select distinct dbms_rowid.rowid_relative_fno(rowid) file#,
		dbms_rowid.rowid_block_number(rowid) block#
	from props$;

		FILE#     BLOCK#
	---------- ----------
			1        801
	+++++++++++++++++++++++++++++

Check the Character set ---> AL32UTF8

	[oracle@databasevm001 ~]$ ls -l /u01/app/oracle/oradata/orcl11g/system01.dbf
	-rw-r-----. 1 oracle oinstall 796925952 May 23 15:52 /u01/app/oracle/oradata/orcl11g/system01.dbf
	[oracle@databasevm001 ~]$
	[oracle@databasevm001 ~]$ dd if=/u01/app/oracle/oradata/orcl11g/system01.dbf of=/home/oracle/system01_01.tmp bs=8192 skip=801 count=1
	1+0 records in
	1+0 records out
	8192 bytes (8.2 kB) copied, 0.000332498 s, 24.6 MB/s
	[oracle@databasevm001 ~]$
	[oracle@databasevm001 ~]$ strings /home/oracle/system01_01.tmp
	~
	NLS_CALENDAR    GREGORIAN
	Calendar system,
	NLS_CHARACTERSET
	AL32UTF8
	Character set,
	NLS_NUMERIC_CHARACTERS
	~
	[oracle@databasevm001 ~]$

Confirm with the archive mode

	Check whether there is archivelog files in archivelog directory.

### Recovery controlfile

According to the redo log's status, there are two recovery modes.

	NORESETLOGS: redo log doesn't drop/miss..
	REDO LOG日志没有丢失时使用NORESETLOGS脚本创建控制文件

	RESETLOGS:redo log was missed
	REDO LOG日志丢失

#### noresetlogs mode

Use the following sql to re-create controlfile.

	STARTUP NOMOUNT
	CREATE CONTROLFILE REUSE DATABASE "orcl11g" NORESETLOGS  ARCHIVELOG
		MAXLOGFILES 16
		MAXLOGMEMBERS 3
		MAXDATAFILES 100
		MAXINSTANCES 8
		MAXLOGHISTORY 292
	LOGFILE
	GROUP 1 '/u01/app/oracle/oradata/orcl11g/redo01.log'  SIZE 50M BLOCKSIZE 512,
	GROUP 2 '/u01/app/oracle/oradata/orcl11g/redo02.log'  SIZE 50M BLOCKSIZE 512,
	GROUP 3 '/u01/app/oracle/oradata/orcl11g/redo03.log'  SIZE 50M BLOCKSIZE 512
	-- STANDBY LOGFILE
	DATAFILE
	'/u01/app/oracle/oradata/orcl11g/system01.dbf',
	'/u01/app/oracle/oradata/orcl11g/sysaux01.dbf',
	'/u01/app/oracle/oradata/orcl11g/undotbs01.dbf',
	'/u01/app/oracle/oradata/orcl11g/users01.dbf',
	'/u01/app/oracle/oradata/orcl11g/data01.dbf'
	CHARACTER SET AL32UTF8
	;

After the sql execution, check the controlfiles.

	SYS@orcl11g> select open_mode from v$database;

	OPEN_MODE
	--------------------
	MOUNTED

	SYS@orcl11g> !ls /u01/app/oracle/oradata/orcl11g/control01.ctl
	/u01/app/oracle/oradata/orcl11g/control01.ctl

	SYS@orcl11g> !ls /u01/app/oracle/fast_recovery_area/orcl11g/control02.ctl
	/u01/app/oracle/fast_recovery_area/orcl11g/control02.ctl

	SYS@orcl11g>

Register the archivelog files.(After remove the controlfiles, we have switched logfile and do the checkporint by some times.)

	SYS@orcl11g> select SEQUENCE#,RESETLOGS_ID from v$archived_log;

	no rows selected

	SYS@orcl11g>

	[oracle@databasevm001 2018_05_23]$ pwd
	/u01/app/oracle/fast_recovery_area/ORCL11G/archivelog/2018_05_23
	[oracle@databasevm001 2018_05_23]$ ls -ltr
	total 16144
	-rw-r-----. 1 oracle oinstall 16515584 May 23 15:37 o1_mf_1_58_fjc2ojps_.arc
	-rw-r-----. 1 oracle oinstall     1024 May 23 15:37 o1_mf_1_59_fjc2olrx_.arc
	-rw-r-----. 1 oracle oinstall     7168 May 23 15:37 o1_mf_1_60_fjc2ops4_.arc
	[oracle@databasevm001 2018_05_23]$

	alter database register physical logfile '/u01/app/oracle/fast_recovery_area/ORCL11G/archivelog/2018_05_23/o1_mf_1_58_fjc2ojps_.arc';
	alter database register physical logfile '/u01/app/oracle/fast_recovery_area/ORCL11G/archivelog/2018_05_23/o1_mf_1_59_fjc2olrx_.arc';
	alter database register physical logfile '/u01/app/oracle/fast_recovery_area/ORCL11G/archivelog/2018_05_23/o1_mf_1_60_fjc2ops4_.arc';

If there are a lot of archive log file, we can use rman to register the  archive log files.

	# Example:
	rman target /
	catalog start with '/u01/app/oracle/fast_recovery_area/ORCL11G/archivelog/2018_05_23/*.arc';

	SYS@orcl11g> select SEQUENCE#,RESETLOGS_ID from v$archived_log;

	SEQUENCE# RESETLOGS_ID
	---------- ------------
			58    961600948
			59    961600948
			60    961600948

	SYS@orcl11g>

Recover database and create temp tablespace.

	SYS@orcl11g> recover database;
	ORA-00283: recovery session canceled due to errors
	ORA-00264: no recovery required

	SYS@orcl11g> alter system archive log all;

	System altered.

	SYS@orcl11g> alter database open;

	Database altered.

	SYS@orcl11g> ALTER TABLESPACE TEMP ADD TEMPFILE '/u01/app/oracle/oradata/orcl11g/temp01.dbf' SIZE 500m  REUSE AUTOEXTEND ON NEXT 50m  MAXSIZE 32767M;

	Tablespace altered.

	SYS@orcl11g>

#### resetlogs mode

Prepare the test env again.
Remove the all redolog files and controlfiles.

Check the files.

	SYS@orcl11g> col  name for a60
	SYS@orcl11g> select status,name from v$controlfile;

	STATUS  NAME
	------- ------------------------------------------------------------
			/u01/app/oracle/oradata/orcl11g/control01.ctl
			/u01/app/oracle/fast_recovery_area/orcl11g/control02.ctl

	SYS@orcl11g> select file#,name from v$datafile;

		FILE# NAME
	---------- ------------------------------------------------------------
			1 /u01/app/oracle/oradata/orcl11g/system01.dbf
			2 /u01/app/oracle/oradata/orcl11g/sysaux01.dbf
			3 /u01/app/oracle/oradata/orcl11g/undotbs01.dbf
			4 /u01/app/oracle/oradata/orcl11g/users01.dbf
			5 /u01/app/oracle/oradata/orcl11g/data01.dbf

	SYS@orcl11g> col member for a50
	SYS@orcl11g> select group#,status,member from v$logfile;

		GROUP# STATUS  MEMBER
	---------- ------- --------------------------------------------------
			1 STALE   /u01/app/oracle/oradata/orcl11g/redo01.log
			3         /u01/app/oracle/oradata/orcl11g/redo03.log
			2         /u01/app/oracle/oradata/orcl11g/redo02.log

	SYS@orcl11g>

Shutdown database normally and remove all of the controlfiles and redologfiles.

	SYS@orcl11g> shu immediate
	Database closed.
	Database dismounted.
	ORACLE instance shut down.
	SYS@orcl11g> host rm /u01/app/oracle/oradata/orcl11g/redo*.log

	SYS@orcl11g> host rm /u01/app/oracle/oradata/orcl11g/control01.ctl

	SYS@orcl11g> host rm /u01/app/oracle/fast_recovery_area/orcl11g/control02.ctl

	SYS@orcl11g>

We need to resetlog while re-creating controlfile if the REDO log file have been missed.

	STARTUP NOMOUNT
	CREATE CONTROLFILE REUSE DATABASE "orcl11g" RESETLOGS  ARCHIVELOG
		MAXLOGFILES 16
		MAXLOGMEMBERS 3
		MAXDATAFILES 100
		MAXINSTANCES 8
		MAXLOGHISTORY 292
	LOGFILE
	GROUP 1 '/u01/app/oracle/oradata/orcl11g/redo01.log'  SIZE 50M BLOCKSIZE 512,
	GROUP 2 '/u01/app/oracle/oradata/orcl11g/redo02.log'  SIZE 50M BLOCKSIZE 512,
	GROUP 3 '/u01/app/oracle/oradata/orcl11g/redo03.log'  SIZE 50M BLOCKSIZE 512
	-- STANDBY LOGFILE
	DATAFILE
	'/u01/app/oracle/oradata/orcl11g/system01.dbf',
	'/u01/app/oracle/oradata/orcl11g/sysaux01.dbf',
	'/u01/app/oracle/oradata/orcl11g/undotbs01.dbf',
	'/u01/app/oracle/oradata/orcl11g/users01.dbf',
	'/u01/app/oracle/oradata/orcl11g/data01.dbf'
	CHARACTER SET AL32UTF8
	;

The database have changed to MOUNTED after re-creating the controlfile.

	SYS@orcl11g> select open_mode from v$database;

	OPEN_MODE
	--------------------
	MOUNTED

	SYS@orcl11g>

We will meet the ORA-00283&ORA-01610 while recovering database.

	SYS@orcl11g> recover database;
	ORA-00283: recovery session canceled due to errors
	ORA-01610: recovery using the BACKUP CONTROLFILE option must be done
	SYS@orcl11g>

Accourding to the tips from the error message, recover database again.

	SYS@orcl11g> recover database using backup controlfile until cancel;
	ORA-00279: change 1406291 generated at 05/31/2018 04:26:49 needed for thread 1
	ORA-00289: suggestion : /u01/app/oracle/fast_recovery_area/ORCL11G/archivelog/2018_05_31/o1_mf_1_63_%u_.arc
	ORA-00280: change 1406291 for thread 1 is in sequence #63

	Specify log: {<RET>=suggested | filename | AUTO | CANCEL}
	cancel	-----------------------------------> Input the word: "cancel"
	Media recovery cancelled.
	SYS@orcl11g>

After that, open database via resetlogs.

	SYS@orcl11g> alter database open resetlogs;

	Database altered.

	SYS@orcl11g>

In the ending of recovering, we need to re-create temp tablespace.

	SYS@orcl11g> ALTER TABLESPACE TEMP ADD TEMPFILE '/u01/app/oracle/oradata/orcl11g/temp01.dbf' SIZE 500m  REUSE AUTOEXTEND ON NEXT 50m  MAXSIZE 32767M;

	Tablespace altered.

	SYS@orcl11g>

Attendation:
When to use "alter database open resetlogs" to open database?

    1.在不完全恢复(介质恢复)时 / Incompleted recover mode.
    2.使用备份的控制文件进行数据库恢复时 / Use the backup controlfile to recover database.
    3.丢失redo log,并使用RESETLOGS方式手工创建控制文件进行数据库恢复时 / Missed redo logs and use resetlogs to re-create controlfile.

	If you lose all redo log files for the database. It can be deleted by mistake or disk corruption.
	If you database recovery needed by redo log group corruption
	If you don't have archive log backups to finish the incomplete recovery of the database.
	If your 'open resetlogs command' fails with error ORA-01194: file 1 needs more recovery to be consistent

### Backup controlfile and restore controlfile via RMAN

	[oracle@databasevm001 ~]$ rman target /

	Recovery Manager: Release 11.2.0.4.0 - Production on Thu May 31 04:40:30 2018

	Copyright (c) 1982, 2011, Oracle and/or its affiliates.  All rights reserved.

	connected to target database: ORCL11G (DBID=1068485233)

	RMAN> show all;

	using target database control file instead of recovery catalog
	RMAN configuration parameters for database with db_unique_name ORCL11G are:
	CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
	CONFIGURE BACKUP OPTIMIZATION OFF; # default
	CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
	CONFIGURE CONTROLFILE AUTOBACKUP OFF; # default
	CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
	CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
	CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
	CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
	CONFIGURE MAXSETSIZE TO UNLIMITED; # default
	CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
	CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
	CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE ; # default
	CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
	CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u01/app/oracle/product/11.2.0.4/dbhome_1/dbs/snapcf_orcl11g.f'; # default

	RMAN>
	RMAN> CONFIGURE CONTROLFILE AUTOBACKUP ON;

	new RMAN configuration parameters:
	CONFIGURE CONTROLFILE AUTOBACKUP ON;
	new RMAN configuration parameters are successfully stored

	RMAN>
	RMAN> CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/home/oracle/backup/control_file_bak_%F';

	new RMAN configuration parameters:
	CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/home/oracle/backup/control_file_bak_%F';
	new RMAN configuration parameters are successfully stored

	RMAN>
	RMAN> backup database format '/home/oracle/backup/full_bak_%d_%T_%s_%U.bak';

	After backup database, it will backup controlfile automatically.

	[oracle@databasevm001 backup]$ ls -ltr
	total 9751456
	-rw-r-----. 1 oracle oinstall 9975332864 May 31 04:50 full_bak_ORCL11G_20180531_1_01t48bav_1_1.bak
	-rw-r-----. 1 oracle oinstall   10158080 May 31 04:50 control_file_bak_c-1068485233-20180531-00
	[oracle@databasevm001 backup]$

	RMAN> list incarnation;

	List of Database Incarnations
	DB Key  Inc Key DB Name  DB ID            STATUS  Reset SCN  Reset Time
	------- ------- -------- ---------------- --- ---------- ----------
	1       1       ORCL11G  1068485233       PARENT  635002     01-DEC-17
	2       2       ORCL11G  1068485233       CURRENT 1406292    31-MAY-18

	RMAN>

	Or

	SYS@orcl11g> select * from v$database_incarnation;

Restore controlfile via RMAN.

	RMAN> restore controlfile to '/u01/app/oracle/oradata/orcl11g/control01.ctl' from '/home/oracle/backup/control_file_bak_c-1068485233-20180531-00';

	Starting restore at 31-MAY-18
	using target database control file instead of recovery catalog
	allocated channel: ORA_DISK_1
	channel ORA_DISK_1: SID=129 device type=DISK

	channel ORA_DISK_1: restoring control file
	RMAN-00571: ===========================================================
	RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
	RMAN-00571: ===========================================================
	RMAN-03002: failure of restore command at 05/31/2018 05:03:20
	ORA-19607: /u01/app/oracle/oradata/orcl11g/control01.ctl is an active control file

	RMAN>

	*** after that, it should keep all the controlfiles are the same.

	SYS@orcl11g> alter database mount;
	alter database mount
	*
	ERROR at line 1:
	ORA-00214: control file '/u01/app/oracle/fast_recovery_area/orcl11g/control02.ctl' version 2826 inconsistent with file '/u01/app/oracle/oradata/orcl11g/control01.ctl' version 2796

	SYS@orcl11g> host cp /u01/app/oracle/oradata/orcl11g/control01.ctl /u01/app/oracle/fast_recovery_area/orcl11g/control02.ctl

	SYS@orcl11g> alter database mount;

	Database altered.

	SYS@orcl11g>

The database should be in the nomount mode.

	RMAN> restore controlfile to '/u01/app/oracle/oradata/orcl11g/control01.ctl' from '/home/oracle/backup/control_file_bak_c-1068485233-20180531-00';

	Starting restore at 31-MAY-18
	using target database control file instead of recovery catalog
	allocated channel: ORA_DISK_1
	channel ORA_DISK_1: SID=129 device type=DISK

	channel ORA_DISK_1: restoring control file
	channel ORA_DISK_1: restore complete, elapsed time: 00:00:01
	Finished restore at 31-MAY-18

	RMAN>

Using the second controlfile is the best/fastest way to recover controlfile.

	cp /u01/app/oracle/oradata/orcl/control01.ctl /u01/app/oracle/fast_recovery_area/orcl/control02.ctl

	SQL> alter database mount;

	Database altered.

	SQL> alter database open;

	Database altered.

### Oracle Hidden/Undocumented Parameters

The Hidden parameters mentioned for Database restoration are.

	Parameter Name                            Description
	----------------------------------------- --------------------------------------------------------
	_allow_error_simulation                   Allow error simulation for testing
	_allow_read_only_corruption               allow read-only open even if database is corrupt
	_allow_resetlogs_corruption               allow resetlogs even if it will cause corruption
	_allow_terminal_recovery_corruption       Finish terminal recovery even if it may cause corruption
	_corrupted_rollback_segments              corrupted undo segment list

	_ALLOW_RESETLOGS_CORRUPTION=TRUE
	This parameter helps to open the database even the datafile headers are not sync with the SCN details. It will allow you to open the database with resetlogs option even the datafiles needed recovery. As soon as the database opens with resetlogs the next check point SCN will get updated to the datafile headers. This leaves the database to an unknown state as it avoids the rolling forward process.

	_CORRUPTED_ROLLBACK_SEGMENTS=(_SYSSMU10_1912826470$,..)
	This parameter is used to corrupt the active rollback segments and which will not be used in the open database. Using this parameter you can drop the rollback segments as well as the undo tablespaces.

	_allow_error_simulation=TRUE
	This parameter allows the error simulation for testing purpose. Normally it used for Oracle internal purpose.

	_minimum_giga_scn=<number>
	This parameter is similar to the ADJUST_SCN event to advance the database SCN to higher value (ahead value). The database should be rebuilt after using this parameter and you should get support from Oracle to decide the value. This parameter is useful in some recovery situations where the current SCN needs to be incremented by a large value to ensure it is ahead of the highest SCN in the database. Typically it needed for ORA-600 [2662] errors to be recoverd.

	DB_Parameter _ALLOW_RESETLOGS_CORRUPTION
	========================================

	This documentation has been prepared avoiding the mention of the complex
	structures from the code and to simply give an insight to the 'damage it could
	cause'.  The usage of this parameter leads to an in-consistent Database with no
	other alternative but to rebuild the complete Database.  This parameter could
	be used when we realize that there are no stardard options available and are
	convinced that the customer understands the implications of using the Oracle's
	secret parameter.  The factors to be considered are ;--

	1. Customer does not have a good backup.
	2. A lot of time and money has been invested after the last good backup and
	there is no possibility for reproduction of the lost data.
	3. The customer has to be ready to export the full database and import it
	back after creating a new one.
	4. There is no 100% guarantee that by using this parameter the database would
	come up.
	5. Oracle does not support the database after using this parameter for
	recovery.
	6. ALL OPTIONS including the ones mentioned in the action part of the error
	message have been tried.

	By setting _ALLOW_RESETLOGS_CORRUPTION=TRUE, certain consistency checks are
	SKIPPED during database open stage.  This basically means it does not check
	the datafile headers as to what the status was before the shutdown and how it
	was shutdown.  The following cases mention few of the checks that were skipped.

	Case-I
	------
	Verification that the datafile present has not been restored from a BACKUP
	taken before the database was opened successfully by using RESETLOGS.

	ORA-01190: control file or data file %s is from before the last RESETLOGS
		Cause: Attempting to use a data file when the log reset information in
			the file does not match the control file.  Either the data file or
			the control file is a backup that was made before the most recent
			ALTER DATABASE OPEN RESETLOGS.
	Action: Restore file from a more recent backup.

	Case-II
	-------
	Verification that the status bit of the datafile is not in a FUZZY state.
	The datafile could be in this state due to the database going down when the
	- Datafile was on-line and open
	- Datafile was not closed cleanly (maybe due to OS).

	ORA-01194: file %s needs more recovery to be consistent
		Cause: An incomplete recover session was started, but an insufficient
			number of logs were applied to make the file consistent.  The
			reported file was not closed cleanly when it was last opened by
			the database.  It must be recovered to a time when it was not
			being updated.  The most likely cause of this error is forgetting
			to restore the file from a backup before doing incomplete
			recovery.
	Action: Either apply more logs until the file is consistent or restore the
			file from an older backup and repeat recovery.

	Case-III
	--------
	Verification that the COMPLETE recover strategies have been applied for
	recovering the datafile and not any of the INCOMPLETE recovery options.
	Basically because the complete recovery is one in which we even apply the
	ON-LINE redo log files and open the DB without reseting the logs.

	ORA-01113: file '%s' needs media recovery starting at log sequence # %s
		Cause: An attempt was made to open a database file that is in need of
			media recovery.
	Action: First apply media recovery to the file.

	Case-IV
	-------
	Verification that the datafile has been recovered through an END BACKUP if the
	control file indicates that it was in backup mode.
	This is useful when the DB has crashed while in hot backup mode and we lost
	all log files in DB version's less than V7.2.

	ORA-01195: on-line backup of file %s needs more recovery to be consistent"
		Cause: An incomplete recovery session was started, but an insufficient
			number of logs were applied to make the file consistent.  The
			reported file is an on-line backup which must be recovered to the
			time the backup ended.
	Action: Either apply more logs until the file is consistent or resotre
			the database files from an older backup and repeat recovery.

	In version 7.2, we could simply issue the ALTER DATABASE DATAFILE xxxx END
	BACKUP statement and proceed with the recovery.  But again to issue this
	statement, we need to have the ON-LINE redo logs or else we still are forced to
	use this parameter.

	Case-V
	------
	Verification that the data file status is not still in (0x10) MEDIA recovery
	FUZZY.
	When recovery is started, a flag is set in the datafile header status flag to
	indicate that the file is presently in media recovery.  This is reset when
	recovery is completed and at times when it has not been reset we are forced to
	use this paramter.

	ORA-01196: file %s is inconsistent due to a failed media recovery session
		Cause: The file was being recovered but the recovery did not terminate
			normally.  This left the file in an inconsistent state.  No more
			recovery was successfully completed on this file.
	Action: Either apply more logs until the file is consistent or restore the
			backup again and repeat recovery.

	Case-VI
	-------
	Verification that the datafile has been restored form a proper backup to
	correspond with the log files.  This situation could happen when we have
	decided that the data file is invalid since its SCN is ahead of the last
	applied logs SCN but it has not failed on one of the ABOVE CHECKS.

	ORA-01152: file '%s' was not restored from a sufficientluy old backup"
		Cause: A manual recovery session was started, but an insufficient number
			of logs were applied to make the database consistent.  This file is
			still in the future of the last log applied.  Note that this
			mistake can not always be caught.
	Action: Either apply more logs until the database is consistent or
			restore the database file from an older backup and repeat
			recovery.

使用_ALLOW_RESETLOGS_CORRUPTION 参数需谨慎,因为该参数可能导致数据库逻辑不一致,甚至可能把本来很简单的一个恢复弄的非常复杂甚至不可恢复的后果,建议在oracle support支持下使用.另外使用该参数resetlogs库之后,强烈建议通过逻辑方式重建库

Have a good day! 2018/05 via LinHong


text:
namespace Urho3D
{

}
namespace Prime
{
	namespace GamePlay
	{
		struct Controls
		{
			Controls()
			{
				forward = 0;
				backwards = 0;
				left = 0;
				right = 0;
				power1 = 0;
			}
			bool forward;
			bool backwards;
			bool left;
			bool right;
			bool power1;
		};

		class Player : public Urho3D::LogicComponent
		{
			OBJECT(Player);
		public:
			Player(Urho3D::Context* context);
			~Player();

			static void RegisterObject(Urho3D::Context* context);

			/// Handle enabled/disabled state change. Changes update event subscription.
			void OnSetEnabled() override;
			/// Called when the component is added to a scene node. Other components may not yet exist.
			void Start() override;
			/// Called before the first update. At this point all other components of the node should exist. Will also be called if update events are not wanted; in that case the event is immediately unsubscribed afterward.
			void DelayedStart() override;
			/// Called when the component is detached from a scene node, usually on destruction.
			void Stop() override;
			/// Called on scene update, variable timestep.
			void Update(float timeStep) override;
			/// Called on scene post-update, variable timestep.
			void PostUpdate(float timeStep) override;
			/// Called on physics update, fixed timestep.
			void FixedUpdate(float timeStep) override;
			/// Called on physics post-update, fixed timestep.
			void FixedPostUpdate(float timeStep) override;

		protected: // Internal functions

		protected: // Event handlers

			void HandleSetCamera(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData);

			void HandleMouseWheel(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData);

			void HandleKeyDown(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData);
			void HandleKeyUp(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData);

		private:
			float _cameraDistance;
			Urho3D::WeakPtr<Urho3D::Node> _cameraNode;
			Urho3D::IntVector2 _cameraRotation;

			Controls _controls;
		};
	}
}
#endif

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.builder.xml;

import javax.xml.transform.ErrorListener;
import javax.xml.transform.TransformerException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * {@link ErrorListener} which logs the errors.
 */
public class XsltErrorListener implements ErrorListener {

    private static final Logger LOG = LoggerFactory.getLogger(XsltErrorListener.class);

    @Override
    public void warning(TransformerException e) throws TransformerException {
        LOG.warn(e.getMessageAndLocation());
    }

    @Override
    public void error(TransformerException e) throws TransformerException {
        LOG.error(e.getMessageAndLocation(), e);
    }

    @Override
    public void fatalError(TransformerException e) throws TransformerException {
        LOG.error(e.getMessageAndLocation(), e);
    }
}


text:
using UnityEngine;
using System.Collections;

public class VietnamStarScript : MonoBehaviour
{
    public float xBoost;
    public float yBoost;
}


text:
var express = require("express");
var router = express.Router();

var User = require("../models/user");

var authMiddleware = require("../middlewares/auth");

router.get("/login/", function(request, response) {
  return response.render("auth/login");
});

router.post("/login/", function(request, response, next) {
  var username = request.body.username;
  var password = request.body.password;

  User.authenticate(username, password, function(error, user) {
    if (error) return next(error);

    request.session.user = user;
    request.flash("success", "성공적으로 로그인 되었습니다.");

    return response.redirect("/");
  });
});

router.get("/signup/", function(request, response) {
  return response.render("auth/signup");
});

router.post("/signup/", function(request, response, next) {
  // FIXME: should validate user

  var user = new User({
    username: request.body.username,
    password: request.body.password,
    email: request.body.email,
    phonenumber: request.body.phonenumber
  });

  user.save(function(error, user) {
    if (error) return next(error);
    return response.redirect("/");
  });
});

router.get("/logout/", function(request, response) {
  return response.redirect("/");
});

router.get("/profile/", authMiddleware.loginRequired, function(request, response) {
  return response.render("auth/profile");
});

module.exports = router;


text:
const pages = [
  {
    pathname: '/joy-ui/getting-started',
    scopePathnames: ['/joy-ui/core-features'],
    icon: 'DescriptionIcon',
    children: [
      { pathname: '/joy-ui/getting-started/overview' },
      { pathname: '/joy-ui/getting-started/usage' },
      { pathname: '/joy-ui/getting-started/tutorial' },
      { pathname: '/joy-ui/getting-started/templates' },
      {
        pathname: '/joy-ui/core-features',
        subheader: 'core-features',
        children: [
          { pathname: '/joy-ui/core-features/global-variant' },
          { pathname: '/joy-ui/core-features/automatic-adjustment' },
          { pathname: '/joy-ui/core-features/perfect-dark-mode' },
        ],
      },
    ],
  },
  {
    pathname: '/joy-ui/react-',
    title: 'Components',
    icon: 'ToggleOnIcon',
    children: [
      {
        pathname: '/joy-ui/components/inputs',
        subheader: 'inputs',
        children: [{ pathname: '/joy-ui/react-button' }, { pathname: '/joy-ui/react-slider' }],
      },
      {
        pathname: '/joy-ui/components/data-display',
        subheader: 'data-display',
        children: [
          { pathname: '/joy-ui/react-aspect-ratio' },
          { pathname: '/joy-ui/react-avatar' },
          { pathname: '/joy-ui/react-badge' },
          { pathname: '/joy-ui/react-chip' },
          { pathname: '/joy-ui/react-typography' },
        ],
      },
      {
        pathname: '/joy-ui/components/surfaces',
        subheader: 'surfaces',
        children: [{ pathname: '/joy-ui/react-card' }],
      },
      {
        pathname: '/joy-ui/components/navigation',
        subheader: 'navigation',
        children: [{ pathname: '/joy-ui/react-link' }],
      },
    ],
  },
  {
    pathname: '/joy-ui/customization',
    icon: 'CreateIcon',
    children: [
      { pathname: '/joy-ui/customization/approaches' },
      { pathname: '/joy-ui/customization/default-theme' },
      { pathname: '/joy-ui/customization/theme-tokens' },
      { pathname: '/joy-ui/customization/themed-components' },
      { pathname: '/joy-ui/customization/using-css-variables', title: 'Using CSS variables' },
    ],
  },
  {
    pathname: '/joy-ui/guides',
    title: 'How To Guides',
    icon: 'VisibilityIcon',
    children: [{ pathname: '/joy-ui/guides/apply-dark-mode', title: 'Apply dark mode' }],
  },
];

export default pages;


text:
import {
  SAVE_SEARCH_RESULTS,
  SET_FETCHING_FLAG,
  SET_FETCHING_ERROR,
  setError,
  setFetchingFlag,
  saveRates,
  initialState,
  default as reducer
} from 'routes/ExchangeRates/modules/exchangeRates'

describe('(Redux Module) Exchange Rates', () => {
  it('Should export a constant SAVE_SEARCH_RESULTS.', () => {
    expect(SAVE_SEARCH_RESULTS).to.equal('SAVE_SEARCH_RESULTS')
  })

  it('Should export a constant SET_FETCHING_FLAG.', () => {
    expect(SET_FETCHING_FLAG).to.equal('SET_FETCHING_FLAG')
  })

  it('Should export a constant SET_FETCHING_ERROR.', () => {
    expect(SET_FETCHING_ERROR).to.equal('SET_FETCHING_ERROR')

    describe('(Reducer)', () => {
      it('Should be a function.', () => {
        expect(reducer).to.be.a('function')
      })

      it('Should initialize with a **initialState**.', () => {
        expect(reducer(undefined, {})).to.equal(initialState)
      })

      it('Should return the previous state if an action was not matched.', () => {
        let state = reducer(undefined, {})
        expect(state).to.eql(initialState)
        state = reducer(state, { type: 'xxx' })
        expect(state).to.eql(initialState)
        state = reducer(state, setError('error'))
        expect(state).to.eql({ ...initialState, error: 'error' })
        state = reducer(state, { type: 'xxx' })
        expect(state).to.eql({ ...initialState, error: 'error' })
      })
    })

    describe('(Action Creator) setFetchingFlag', () => {
      it('Should be exported as a function.', () => {
        expect(setFetchingFlag).to.be.a('function')
      })

      it('Should return an action with type "COUNTER_INCREMENT".', () => {
        expect(setFetchingFlag(true)).to.have.property('type', SET_FETCHING_FLAG)
      })

      it('Should assign the first argument to the "payload" property.', () => {
        expect(setFetchingFlag(true)).to.have.property('payload', true)
      })

      it('Should always return "payload" property as a boolean', () => {
        expect(setFetchingFlag()).to.have.property('payload', false)
      })
    })

    describe('(Action Creator) setError', () => {
      it('Should be exported as a function.', () => {
        expect(setError).to.be.a('function')
      })

      it('Should return an action with type "COUNTER_INCREMENT".', () => {
        expect(setError('error')).to.have.property('type', SET_FETCHING_ERROR)
      })

      it('Should assign the first argument to the "payload" property.', () => {
        expect(setError('error')).to.have.property('payload', 'error')
      })
    })

    describe('(Action Creator) saveRates', () => {
      const ratesResult = {
        base: 'GBP',
        date: '2017-03-26',
        rates: { EUR: 1.2, USD: 1.5 }
      }

      it('Should be exported as a function.', () => {
        expect(saveRates).to.be.a('function')
      })

      it('Should return an action with type "SAVE_SEARCH_RESULTS".', () => {
        expect(saveRates(ratesResult)).to.have.property('type', SAVE_SEARCH_RESULTS)
      })

      it('Should assign the first argument to the "payload" property.', () => {
        expect(saveRates(ratesResult)).to.have.property('payload', ratesResult)
      })
    })
  })
})


text:
#ifndef PF_NET_SOCKET_API_H_
#define PF_NET_SOCKET_API_H_

#include "pf/net/socket/config.h"

#if __LINUX__
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#elif __WINDOWS__
#include <winsock.h>
#endif
#include <errno.h>

#define SOCKET_ERROR_WOULD_BLOCK -100

//解决系统函数名和命名空间冲突
int32_t sys_socket(int32_t domain, int32_t type, int32_t protocol);

namespace pf_net {

namespace socket {

namespace api {

PF_API int32_t socketex(int32_t domain, int32_t type, int32_t protocol);

PF_API bool bindex(int32_t socketid,
                   const struct sockaddr *name,
                   uint32_t namelength);

PF_API bool connectex(int32_t socketid,
                      const struct sockaddr *name,
                      uint32_t namelength);

PF_API bool listenex(int32_t socketid, uint32_t backlog);

PF_API int32_t acceptex(int32_t socketid,
                        struct sockaddr *addr,
                        uint32_t *addrlength);

PF_API bool getsockopt_exb(int32_t socketid,
                           int32_t level,
                           int32_t optname,
                           void *optval,
                           uint32_t *optlength);

PF_API uint32_t getsockopt_exu(int32_t socketid,
                               int32_t level,
                               int32_t optname,
                               void *optval,
                               uint32_t* optlength);

PF_API bool setsockopt_ex(int32_t socketid,
                          int32_t level,
                          int32_t optname,
                          const void *optval,
                          uint32_t optlength);

PF_API int32_t sendex(int32_t socketid,
                      const void *buffer,
                      uint32_t length,
                      uint32_t flag);

PF_API int32_t sendto_ex(int32_t socketid,
                         const void *buffer,
                         int32_t length,
                         uint32_t flag,
                         const struct sockaddr *to,
                         int32_t tolength);

PF_API int32_t recvex(int32_t socketid,
                      void *buffer,
                      uint32_t length,
                      uint32_t flag);

PF_API int32_t recvfrom_ex(int32_t socketid,
                           void *buffer,
                           int32_t length,
                           uint32_t flag,
                           struct sockaddr* from,
                           uint32_t *fromlength);

PF_API bool closeex(int32_t socketid);

PF_API bool ioctlex(int32_t socketid, int64_t cmd, uint64_t *argp);

PF_API bool get_nonblocking_ex(int32_t socketid);

PF_API bool set_nonblocking_ex(int32_t socketid, bool on);

PF_API uint32_t availableex(int32_t socketid);

PF_API bool shutdown_ex(int32_t socketid, int32_t how);

PF_API int32_t selectex(int32_t maxfdp,
                        fd_set *readset,
                        fd_set *writeset,
                        fd_set *exceptset,
                        struct timeval *timeout);

PF_API int32_t getsockname_ex(int32_t socketid,
                              struct sockaddr *name,
                              int32_t *namelength);

PF_API int32_t getlast_errorcode();
PF_API void getlast_errormessage(char *buffer, uint16_t length);

}; //namespace api

}; //namespace socket

}; //namespace pf_net

#endif //PF_NET_SOCKET_API_H_


text:
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "sql/database_memory_dump_provider.h"

#include <inttypes.h>

#include <ostream>  // Needed to compile NOTREACHED() with operator <<.
#include <string>

#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/trace_event/memory_dump_request_args.h"
#include "base/trace_event/process_memory_dump.h"
#include "sql/sqlite_result_code.h"
#include "sql/sqlite_result_code_values.h"
#include "third_party/sqlite/sqlite3.h"

namespace sql {

DatabaseMemoryDumpProvider::DatabaseMemoryDumpProvider(sqlite3* db,
                                                       const std::string& name)
    : db_(db), connection_name_(name) {}

DatabaseMemoryDumpProvider::~DatabaseMemoryDumpProvider() = default;

void DatabaseMemoryDumpProvider::ResetDatabase() {
  base::AutoLock lock(lock_);
  db_ = nullptr;
}

bool DatabaseMemoryDumpProvider::OnMemoryDump(
    const base::trace_event::MemoryDumpArgs& args,
    base::trace_event::ProcessMemoryDump* pmd) {
  if (args.level_of_detail == base::trace_event::MemoryDumpLevelOfDetail::LIGHT)
    return true;

  MemoryUsageResult memory_usage = GetDbMemoryUsage();
  if (!memory_usage.is_valid)
    return false;

  base::trace_event::MemoryAllocatorDump* dump =
      pmd->CreateAllocatorDump(FormatDumpName());
  dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
                  base::trace_event::MemoryAllocatorDump::kUnitsBytes,
                  memory_usage.cache_size + memory_usage.schema_size +
                      memory_usage.statement_size);
  dump->AddScalar("cache_size",
                  base::trace_event::MemoryAllocatorDump::kUnitsBytes,
                  memory_usage.cache_size);
  dump->AddScalar("schema_size",
                  base::trace_event::MemoryAllocatorDump::kUnitsBytes,
                  memory_usage.schema_size);
  dump->AddScalar("statement_size",
                  base::trace_event::MemoryAllocatorDump::kUnitsBytes,
                  memory_usage.statement_size);
  return true;
}

bool DatabaseMemoryDumpProvider::ReportMemoryUsage(
    base::trace_event::ProcessMemoryDump* pmd,
    const std::string& dump_name) {
  MemoryUsageResult memory_usage = GetDbMemoryUsage();
  if (!memory_usage.is_valid)
    return false;

  auto* mad = pmd->CreateAllocatorDump(dump_name);
  mad->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
                 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
                 memory_usage.cache_size + memory_usage.schema_size +
                     memory_usage.statement_size);
  pmd->AddSuballocation(mad->guid(), FormatDumpName());

  return true;
}

DatabaseMemoryDumpProvider::MemoryUsageResult
DatabaseMemoryDumpProvider::GetDbMemoryUsage() {
  MemoryUsageResult result;

  // Lock is acquired here so that db_ is not reset in ResetDatabase when
  // collecting stats.
  base::AutoLock lock(lock_);
  if (!db_) {
    DCHECK_EQ(result.is_valid, false);
    return result;
  }

  // The following calls all set the high watermark to zero.
  // See /https://www.sqlite.org/c3ref/c_dbstatus_options.html
  int high_watermark = 0;

  auto sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
      db_, SQLITE_DBSTATUS_CACHE_USED, &result.cache_size, &high_watermark,
      /*resetFlg=*/0));
  DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
      << "sqlite3_db_status(SQLITE_DBSTATUS_CACHE_USED) failed";

#if DCHECK_IS_ON()
  int shared_cache_size = 0;
  sqlite_result_code = ToSqliteResultCode(
      sqlite3_db_status(db_, SQLITE_DBSTATUS_CACHE_USED_SHARED,
                        &shared_cache_size, &high_watermark, /*resetFlg=*/0));
  DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
      << "sqlite3_db_status(SQLITE_DBSTATUS_CACHE_USED_SHARED) failed";
  DCHECK_EQ(shared_cache_size, result.cache_size)
      << "Memory counting assumes that each database uses a private page cache";
#endif  // DCHECK_IS_ON()

  sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
      db_, SQLITE_DBSTATUS_SCHEMA_USED, &result.schema_size, &high_watermark,
      /*resetFlg=*/0));
  DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
      << "sqlite3_db_status(SQLITE_DBSTATUS_SCHEMA_USED) failed";

  sqlite_result_code = ToSqliteResultCode(sqlite3_db_status(
      db_, SQLITE_DBSTATUS_STMT_USED, &result.statement_size, &high_watermark,
      /*resetFlg=*/0));
  DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
      << "sqlite3_db_status(SQLITE_DBSTATUS_STMT_USED) failed";

  result.is_valid = true;
  return result;
}

std::string DatabaseMemoryDumpProvider::FormatDumpName() const {
  return base::StringPrintf(
      "sqlite/%s_connection/0x%" PRIXPTR,
      connection_name_.empty() ? "Unknown" : connection_name_.c_str(),
      reinterpret_cast<uintptr_t>(this));
}

}  // namespace sql


text:
<resources>
    <string name="app_name">Class Look Up</string>

    <string name="textHome">Home</string>
    <string name="textSettings">Settings</string>
    <string name="textSchedules">Schedules</string>

    <string name="textDownload">Download</string>
    <string name="textDownloaded">Downloaded</string>
    <string name="textCancel">Cancel</string>
    <string name="textSearch">Search</string>

    <string name="textFindClass">Find a Class</string>
    <string name="textTerm">Term</string>
    <string name="textBuildingName">Building Name</string>
    <string name="textRoomName">Room Name</string>
    <string name="textSearchInvalid">Please put in valid information</string>
    <string name="textSearchNoResults">No results found</string>

    <string name="textLoadingSchedule">Loading Schedule</string>

    <string name="textScheduleInstruction">Select a semester to download</string>
    <string name="textFetching">Fetching</string>

    <string name="coursesApiRoot">https://courses.illinois.edu/cisapp/explorer/schedule.xml</string>

    <string name="textCannotDeleteFile">Cannot delete file</string>
</resources>


text:
from flask.ext.cache import Cache

cache = Cache()


text:
/*
 * Problem 10. Extract text from XML
 * Write a program that extracts from given XML file all the text without the tags.
 */

using System;
using System.IO;
using System.Text.RegularExpressions;

class P10_ExtractTextFromXML
{
    static void Main()
    {
        // variable initialization
        string tagPattern = @"<.*?>";
        string whitespacePattern = @"\s+";
        string sourcePath = @"../../xml.txt";
        string resultPath = @"../../result.txt";
        Regex tagRemover = new Regex(tagPattern);
        Regex whiteSpaceRemover = new Regex(whitespacePattern);
        StreamReader reader = new StreamReader(sourcePath);
        StreamWriter writer = new StreamWriter(resultPath);

        using (reader)
        {
            using (writer)
            {
                string line = reader.ReadLine();

                while (line != null)
                {
                    line = tagRemover.Replace(line, string.Empty);
                    line = whiteSpaceRemover.Replace(line, " ");

                    if (!string.IsNullOrWhiteSpace(line))
                    {
                        writer.WriteLine(line);
                    }

                    line = reader.ReadLine();
                }
            }
        }

        Console.WriteLine("Job Done. Check file {0} for results.", resultPath);
    }
}


text:
package eve.corp.manager.common.model;

import java.io.Serializable;

public class AuditedCharacter implements Serializable {

    private static final long serialVersionUID = 8439087603523118358L;

    private String characterName;

    private long characterID;

    private String corporationName;

    private long corporationID;

    private Long allianceID;

    private String allianceName;

    private double securityStatus;

    public AuditedCharacter() {
    }

    public String getCharacterName() {
        return this.characterName;
    }

    public void setCharacterName(String characterName) {
        this.characterName = characterName;
    }

    public long getCharacterID() {
        return this.characterID;
    }

    public void setCharacterID(long characterID) {
        this.characterID = characterID;
    }

    public String getCorporationName() {
        return this.corporationName;
    }

    public void setCorporationName(String corporationName) {
        this.corporationName = corporationName;
    }

    public long getCorporationID() {
        return this.corporationID;
    }

    public void setCorporationID(long corporationID) {
        this.corporationID = corporationID;
    }

    public Long getAllianceID() {
        return this.allianceID;
    }

    public void setAllianceID(Long allianceID) {
        this.allianceID = allianceID;
    }

    public String getAllianceName() {
        return this.allianceName;
    }

    public void setAllianceName(String allianceName) {
        this.allianceName = allianceName;
    }

    public double getSecurityStatus() {
        return this.securityStatus;
    }

    public void setSecurityStatus(double securityStatus) {
        this.securityStatus = securityStatus;
    }
}


text:
#ifndef FORMFIELD_H
#define FORMFIELD_H

#include <QSet>
#include <QString>

#include "formfieldtypes.h"
#include "runtime/input/events/domelementdescriptor.h"

namespace artemis
{

class FormField
{

public:
    FormField(FormFieldTypes fieldType, const DOMElementDescriptor* domElement, QSet<QString> inputOptions);
    FormField(FormFieldTypes fieldType, const DOMElementDescriptor* domElement);

    const DOMElementDescriptor* getDomElement() const;
    FormFieldTypes getType() const;
    QSet<QString> getInputOptions() const;

    QDebug friend operator<<(QDebug dbg, const FormField& f);

private:
    const DOMElementDescriptor* mElementDescriptor;
    const FormFieldTypes mFieldType;
    QSet<QString> mDefaultInputs;

};

}

#endif // FORMFIELD_H


text:
THISDIR=$(cd $(dirname "$0"); pwd) #this script's directory
clear;

die () {
	printf >&2 "$@"
	exit 1
}

npm run lint || die '\nlint failed!\n\n'

$THISDIR/node_modules/.bin/nodemon -e js,html,svelte,sh,css --ignore dist/ --exec './build.sh && echo "\n\nNow run ./serve.sh from another shell window to serve the site locally.\n\n"'


text:
package org.xtreemfs.osd.operations;

import org.xtreemfs.common.Capability;
import org.xtreemfs.common.uuids.ServiceUUID;
import org.xtreemfs.common.xloc.InvalidXLocationsException;
import org.xtreemfs.common.xloc.XLocations;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader.ErrorResponse;
import org.xtreemfs.foundation.pbrpc.utils.ErrorUtils;
import org.xtreemfs.osd.InternalObjectData;
import org.xtreemfs.osd.OSDRequest;
import org.xtreemfs.osd.OSDRequestDispatcher;
import org.xtreemfs.osd.stages.StorageStage.ReadObjectCallback;
import org.xtreemfs.osd.storage.ObjectInformation;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.xtreemfs_rwr_fetchRequest;
import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceConstants;

public final class InternalRWRFetchOperation extends OSDOperation {

    final String sharedSecret;
    final ServiceUUID localUUID;

    public InternalRWRFetchOperation(OSDRequestDispatcher master) {
        super(master);
        sharedSecret = master.getConfig().getCapabilitySecret();
        localUUID = master.getConfig().getUUID();
    }

    @Override
    public int getProcedureId() {
        return OSDServiceConstants.PROC_ID_XTREEMFS_RWR_FETCH;
    }

    @Override
    public void startRequest(final OSDRequest rq) {
        final xtreemfs_rwr_fetchRequest args = (xtreemfs_rwr_fetchRequest)rq.getRequestArgs();

        if (Logging.isDebug()) {
            Logging.logMessage(Logging.LEVEL_DEBUG, this,"RWR fetch request for file %s-%d",args.getFileId(),args.getObjectNumber());
        }

        fetchObject(rq,args);

    }

    public void fetchObject(final OSDRequest rq, final xtreemfs_rwr_fetchRequest args) {
        master.getStorageStage().readObject(rq.getFileId(), args.getObjectNumber(),
                rq.getLocationList().getLocalReplica().getStripingPolicy(), 0, -1, 0, rq, new ReadObjectCallback() {

            @Override
            public void readComplete(ObjectInformation result, ErrorResponse error) {
                if (error != null)
                    sendResult(rq, null, error);
                else {
                    InternalObjectData odata = new InternalObjectData(0, false, 0, result.getData());
                    sendResult(rq, odata, null);
                }
            }
        });
    }

    public void sendResult(final OSDRequest rq, InternalObjectData response, ErrorResponse error) {

        if (error != null) {
            rq.sendError(error);
        } else {
            //only locally
           rq.sendSuccess(response.getMetadata(),response.getData());
        }
    }

    @Override
    public ErrorResponse parseRPCMessage(OSDRequest rq) {
        try {
            xtreemfs_rwr_fetchRequest rpcrq = (xtreemfs_rwr_fetchRequest)rq.getRequestArgs();
            rq.setFileId(rpcrq.getFileId());
            rq.setCapability(new Capability(rpcrq.getFileCredentials().getXcap(), sharedSecret));
            rq.setLocationList(new XLocations(rpcrq.getFileCredentials().getXlocs(), localUUID));

            return null;
        } catch (InvalidXLocationsException ex) {
            return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL, ex.toString());
        } catch (Throwable ex) {
            return ErrorUtils.getInternalServerError(ex);
        }
    }

    @Override
    public boolean requiresCapability() {
        return true;
    }

    @Override
    public void startInternalEvent(Object[] args) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}


text:
package org.apache.nuvem.xmpp.client;

import org.apache.nuvem.cloud.xmpp.api.XMPPConnector;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.oasisopen.sca.annotation.Service;

/**
 * Helps establish a connection to the XMPP Server and returns the same
 * connection instance once connected. This specific implementation of
 * {@link XMPPConnector} will try to connect to the XMPPServer in an unsecured
 * way called. For more secure way of connecting to the XMPP server, please use
 * {@link SSLConnector}
 *
 */
@Service(XMPPConnector.class)
public class SimpleConnector extends AbstractConnector {

	/**
	 * {@inheritDoc}
	 */
	public String getDescription() {
		return "Single Connection Default connector";
	}

	@Override
	protected void checkConfigurations() {
		if (host == null || port == 0 || clientJID == null
				|| clientPassword == null) {
			throw new IllegalStateException(
					"the configuration parameters are not initlaized properly!");
		}
	}

	/**
	 * Establishes a simple connection with the XMPP Server.
	 */
	protected void establishConnection() throws XMPPException {
		ConnectionConfiguration connectionConfiguration = new ConnectionConfiguration(
				host, port, serviceName);
		SASLAuthentication.supportSASLMechanism(authenticationMechanism, 0);
		this.connection = new XMPPConnection(connectionConfiguration);
		connection.connect();
	}

	/**
	 * Authenticates with the XMPPServer using client JID and password.
	 */
	protected void authenticateWithServer() throws XMPPException {
		this.connection.login(this.clientJID, this.clientPassword);

	}

}


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

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Pastime'
        db.create_table(u'pastimes_pastime', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=150)),
            ('desc', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
        ))
        db.send_create_signal(u'pastimes', ['Pastime'])

    def backwards(self, orm):
        # Deleting model 'Pastime'
        db.delete_table(u'pastimes_pastime')

    models = {
        u'pastimes.pastime': {
            'Meta': {'object_name': 'Pastime'},
            'desc': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '150'})
        }
    }

    complete_apps = ['pastimes']


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Geol-Palaeontol Mitt Innsbr Sonderbd 3: 138.

#### Original name
null

### Remarks
null


text:
@interface BeeTaskQueue : NSObject
{
	dispatch_queue_t _foreQueue;
	dispatch_queue_t _backQueue;
}

AS_SINGLETON( BeeTaskQueue );

- (dispatch_queue_t)foreQueue;
- (dispatch_queue_t)backQueue;

- (void)enqueueForeground:(dispatch_block_t)block;
- (void)enqueueBackground:(dispatch_block_t)block;
- (void)enqueueForegroundWithDelay:(dispatch_time_t)ms block:(dispatch_block_t)block;
- (void)enqueueBackgroundWithDelay:(dispatch_time_t)ms block:(dispatch_block_t)block;

@end


text:
cd /usr/games/bsdgames

path=$(ls)

system=$(eval zenity --list --column Games $path --width=480 --height=272)

case $? in
         0)
                ./"$system";;
         1)
                echo "No game selected.";;
        -1)
                echo "An unexpected error has occurred.";;
esac


text:
package org.spongepowered.common.data.value.mutable;

import org.spongepowered.api.data.key.Key;
import org.spongepowered.api.data.value.BaseValue;
import org.spongepowered.api.data.value.immutable.ImmutableValue;
import org.spongepowered.api.data.value.mutable.Value;
import org.spongepowered.common.data.value.AbstractBaseValue;
import org.spongepowered.common.data.value.immutable.ImmutableSpongeValue;

import java.util.function.Function;

public class SpongeValue<E> extends AbstractBaseValue<E> implements Value<E> {

    public SpongeValue(Key<? extends BaseValue<E>> key, E defaultValue) {
        this(key, defaultValue, defaultValue);
    }

    public SpongeValue(Key<? extends BaseValue<E>> key, E defaultValue, E actualValue) {
        super(key, defaultValue, actualValue);
    }

    @Override
    public Value<E> set(E value) {
        this.actualValue = value;
        return this;
    }

    @Override
    public Value<E> transform(Function<E, E> function) {
        this.actualValue = function.apply(this.actualValue);
        return this;
    }

    @Override
    public ImmutableValue<E> asImmutable() {
        return ImmutableSpongeValue.cachedOf(this.getKey(), this.getDefault(), this.actualValue);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Bungartz, Nash & Ryan, Can. J. Bot. 82(4): 552 (2004)

#### Original name
Buellia tergua Bungartz

### Remarks
null


text:
from __future__ import unicode_literals, absolute_import, print_function
import os
import sys
import codecs
import unittest
try:
    import mock
    from mock import patch
except ImportError:
    from unittest.mock import MagicMock as mock
    from unittest.mock import patch

try:
    import ardublocklyserver.actions as actions
    from ardublocklyserver.compilersettings import ServerCompilerSettings
except ImportError:
    import sys
    file_dir = os.path.dirname(os.path.realpath(__file__))
    package_dir = os.path.dirname(os.path.dirname(file_dir))
    sys.path.insert(0, package_dir)
    import ardublocklyserver.actions as actions
    from ardublocklyserver.compilersettings import ServerCompilerSettings

class ActionsTestCase(unittest.TestCase):
    """
    Tests for actions module
    """

    #
    # Helper functions
    #
    def delete_default_settings_file(self):
        """
        Checks if there is a settings file in the default location and deletes
        it if it finds it.
        This will DELETE a file from the directory this script is called !!!
        """
        default_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
        # Accessing the class static variable does not initialise the singleton
        settings_file = os.path.normpath(os.path.join(
            default_dir,
            ServerCompilerSettings._ServerCompilerSettings__settings_filename))
        if os.path.exists(settings_file):
            print('Removing settings file from %s' % settings_file)
            os.remove(settings_file)

    #
    # Command line tests
    #
    @patch('ardublocklyserver.actions.subprocess.Popen', autospec=True)
    #@patch.object(
    #    actions.ServerCompilerSettings, 'get_compiler_dir', autospec=True)
    def test_load_arduino_cli_valid(self, mock_popen):
        """
        Tests that a compiler path and arduino sketch path can be set
        and that a command line can be launched to open the sketch in the
        Arduino IDE.
        """
        sketch_path = actions.create_sketch_default()

        ServerCompilerSettings().load_ide_option = 'open'
        with patch(
                'ardublocklyserver.actions.ServerCompilerSettings.compiler_dir',
                new_callable=mock.PropertyMock) as mock_compiler_dir:
            mock_compiler_dir.return_value = 'true'  # do nothing command
            expected_command = ['true', sketch_path]
            success, conclusion, out, error, exit_code = \
                actions.load_arduino_cli(sketch_path)
            mock_popen.assert_called_with(expected_command, shell=False)
            self.assertTrue(success)

        ServerCompilerSettings().load_ide_option = 'verify'
        with patch(
                'ardublocklyserver.actions.ServerCompilerSettings.compiler_dir',
                new_callable=mock.PropertyMock) as mock_compiler_dir:
            mock_compiler_dir.return_value = 'true'  # do nothing command
            mock_popen.return_value.communicate.return_value = ('test', 'test')
            mock_popen.return_value.returncode = 0
            expected_command = ['true', '--verify', sketch_path]
            success, conclusion, out, error, exit_code = \
                actions.load_arduino_cli(sketch_path)
            mock_popen.assert_called_with(expected_command, shell=False,
                                          stderr=-1, stdout=-1)
            self.assertTrue(success)

        ServerCompilerSettings().load_ide_option = 'upload'
        with patch(
                'ardublocklyserver.actions.ServerCompilerSettings.compiler_dir',
                new_callable=mock.PropertyMock) as mock_compiler_dir:
            mock_compiler_dir.return_value = 'true'  # do nothing command
            mock_popen.return_value.communicate.return_value = ('test', 'test')
            mock_popen.return_value.returncode = 0
            expected_command = [
                'true', '--upload', '--port',
                ServerCompilerSettings().get_serial_port_flag(), '--board',
                ServerCompilerSettings().get_arduino_board_flag(), sketch_path]
            success, conclusion, out, error, exit_code = \
                actions.load_arduino_cli(sketch_path)
            mock_popen.assert_called_with(expected_command, shell=False,
                                          stderr=-1, stdout=-1)
            self.assertTrue(success)

        # Test for unicode strings as Py2 can be susceptible to fail there
        ServerCompilerSettings().load_ide_option = 'upload'
        with patch(
                'ardublocklyserver.actions.ServerCompilerSettings.compiler_dir',
                new_callable=mock.PropertyMock) as mock_compiler_dir:
            mock_compiler_dir.return_value = 'いろはにほへとちり'  # unicode
            mock_popen.return_value.communicate.return_value = (
                'Γαζέες καὶ μυρτιὲς', 'Âne ex aéquo au whist')
            mock_popen.return_value.returncode = 0
            expected_command = [
                mock_compiler_dir.return_value, '--upload', '--port',
                ServerCompilerSettings().get_serial_port_flag(), '--board',
                ServerCompilerSettings().get_arduino_board_flag(), sketch_path]
            success, conclusion, out, error, exit_code = \
                actions.load_arduino_cli(sketch_path)
            mock_popen.assert_called_with(expected_command, shell=False,
                                          stderr=-1, stdout=-1)
            self.assertTrue(success)

    def test_load_arduino_cli_invalid(self):
        # Test that an path that is not a file returns error
        success, conclusion, out, error, exit_code =\
            actions.load_arduino_cli(os.getcwd())
        self.assertFalse(success)
        self.assertTrue('Provided sketch path is not a valid' in conclusion)

        # Test for error if compiler dir is not set, default is None
        self.delete_default_settings_file()
        success, conclusion, out, error, exit_code = actions.load_arduino_cli()
        self.assertFalse(success)
        self.assertEqual(conclusion, 'Unable to find Arduino IDE')

        # Test for error if compiler dir is not set
        with patch(
                'ardublocklyserver.actions.ServerCompilerSettings.compiler_dir',
                new_callable=mock.PropertyMock) as mock_compiler_dir:
            with patch(
                    'ardublocklyserver.actions.ServerCompilerSettings.'
                    'load_ide_option', new_callable=mock.PropertyMock) as \
                    mock_load_ide_option:
                mock_compiler_dir.return_value = 'true'  # do nothing command
                mock_load_ide_option.return_value = None
                success, conclusion, out, error, exit_code = \
                    actions.load_arduino_cli()
                self.assertFalse(success)
                self.assertEqual(conclusion,
                                 'What should we do with the Sketch?')

        # Test for error if serial port unset, only required when set to upload
        ServerCompilerSettings().load_ide_option = 'upload'
        with patch(
                'ardublocklyserver.actions.ServerCompilerSettings.compiler_dir',
                new_callable=mock.PropertyMock) as mock_compiler_dir:
            with patch(
                    'ardublocklyserver.actions.ServerCompilerSettings.'
                    'get_serial_port_flag') as mock_get_serial_port_flag:
                mock_compiler_dir.return_value = 'true'  # do nothing command
                mock_get_serial_port_flag.return_value = None
                success, conclusion, out, error, exit_code = \
                    actions.load_arduino_cli()
                self.assertFalse(success)
                self.assertEqual(conclusion, 'Serial Port unavailable')

        # Test for error if board type unset, only required when set to upload
        ServerCompilerSettings().load_ide_option = 'upload'
        with patch(
                'ardublocklyserver.actions.ServerCompilerSettings.compiler_dir',
                new_callable=mock.PropertyMock) as mock_compiler_dir:
            with patch(
                    'ardublocklyserver.actions.ServerCompilerSettings.'
                    'get_arduino_board_flag') as mock_get_arduino_board_flag:
                mock_compiler_dir.return_value = 'true'  # do nothing command
                mock_get_arduino_board_flag.return_value = None
                success, conclusion, out, error, exit_code = \
                    actions.load_arduino_cli()
                self.assertFalse(success)
                self.assertEqual(conclusion, 'Unknown Arduino Board')

    #
    # Tests sketch creation
    #
    def test_create_sketch_default(self):
        sketch_dir = actions.create_sketch_default()
        self.assertTrue(os.path.isfile(sketch_dir))

    def test_create_sketch_from_string(self):
        sketch_content = 'test string sketch'
        sketch_dir = actions.create_sketch_from_string(sketch_content)
        self.assertTrue(os.path.isfile(sketch_dir))
        f = codecs.open(sketch_dir, "r", "utf-8")
        self.assertEqual(f.read(), sketch_content)

        # Test for unicode file
        sketch_content = 'いろはにほへとちり Γαζέες καὶ μυρτς Âne aéquo au whist'
        sketch_dir = actions.create_sketch_from_string(sketch_content)
        self.assertTrue(os.path.isfile(sketch_dir))
        f = codecs.open(sketch_dir, "r", "utf-8")
        self.assertEqual(f.read(), sketch_content)

    #
    # Tests sketch creation
    #
    @patch('ardublocklyserver.gui.browse_file_dialog')
    @patch('ardublocklyserver.compilersettings.os.path.isfile')
    def test_load_arduino_cli_valid(self, mock_isfile, mock_file_dialog):
        """
        Tests that the set_compiler_path method edits the settings based on the
        output from the gui.browse_file_dialog() function only if it has not
        been cancelled.
        The return value is not tested as it is a direct call to the
        actions.get_compiler_path() function and will be tested individually.
        """
        self.delete_default_settings_file()
        settings = ServerCompilerSettings()
        new_compiler_dir = os.path.join(os.getcwd(), 'arduino_debug.exe')
        mock_file_dialog.return_value = new_compiler_dir
        # The settings.compiler_dir checks for file validity
        mock_isfile.return_value = True
        old_compiler_dir = settings.compiler_dir
        actions.set_compiler_path()
        self.assertNotEqual(old_compiler_dir, settings.compiler_dir)
        # Using in as each OSs will dealt with compiler path differently
        self.assertTrue(new_compiler_dir in settings.compiler_dir)

        # If the dialog is cancelled, the ServerCompilerSettings class should
        # not be invoked at all
        with patch(
                'ardublocklyserver.actions.ServerCompilerSettings.__new__') \
                as mock_settings:
            # Avoid call to ServerCompilerSettings() in get_compiler_path
            with patch('ardublocklyserver.actions.get_compiler_path') \
                    as mock_get_compiler_path:
                mock_file_dialog.return_value = ''  # Dialog cancel return value
                mock_get_compiler_path.return_vale = None  # Don't care
                old_compiler_dir = settings.compiler_dir
                actions.set_compiler_path()
                self.assertEqual(old_compiler_dir, settings.compiler_dir)
                self.assertFalse(mock_settings.called)

    def test_get_compiler_path(self):
        #TODO: This test method
        pass

    #
    # Test sketch setting functions
    #
    def test_set_sketch_path(self):
        #TODO: This test method
        pass

    def test_get_sketch_path(self):
        #TODO: This test method
        pass

    #
    # Test arduino Board setting functions
    #
    def test_set_arduino_board(self):
        #TODO: This test method
        pass

    def test_get_arduino_boards(self):
        #TODO: This test method
        pass

    #
    # Test serial Port setting functions
    #
    def test_set_serial_port(self):
        #TODO: This test method
        pass

    def test_get_serial_ports(self):
        #TODO: This test method
        pass

    #
    # Test load IDE setting functions
    #
    def test_set_load_ide_only(self):
        #TODO: This test method
        pass

    def test_get_load_ide_only(self):
        #TODO: This test method
        pass

if __name__ == '__main__':
    unittest.main()


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../">
  <title data-ice="title">tests/PluginManager.test.js | Plugged In API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

  Home

  Reference
  Source
  Test
  Repository

    <input class="search-input">

CEvent

CNpm

CPluginManager

errors
CValidationError

tests/PluginManager.test.js

import Moment from 'moment';
import chai, { expect } from 'chai';
import PluginManager from './../src/PluginManager';

chai.use(require('dirty-chai'));

describe('PluginManager', () => {
  let manager;
  let npm;

  const options = {
    context: 'test-context',
    debug: true,
  };

  beforeEach(() => {
    function onError() { }
    function setInitialisedAt() { }
    function setDefaultMaxHandlers() { }
    function cleanUp(event) { event.context._events = {}; }

    manager = new PluginManager(options);
    npm = {
      generateConfig: (mgr) => {
        mgr._events = {
          error: [onError],
          postInit: [setDefaultMaxHandlers, setInitialisedAt],
          exit: [cleanUp],
        };

        return mgr;
      },
    };
  });

  it('gets created successfully', () => {
    expect(manager instanceof PluginManager).to.equal(true);
    expect(manager.context).to.equal(options.context);
    expect(manager.debug).to.equal(options.debug);
  });

  it('has logger', () => {
    expect(typeof manager.log._debug === 'boolean').to.equal(true);
  });

  describe('init', () => {
    it('gets initialised successfully', async () => {
      const result = await manager.init({}, npm);

      expect(result).to.deep.equal(manager);
      expect(typeof result._events.error[0]).to.equal('function');
      expect(typeof result._events.postInit[0]).to.equal('function');
      expect(typeof result._events.postInit[1]).to.equal('function');
    }).timeout(10000);

    it('with local event handlers', async () => {
      const onGenerateConfig = (event) => {
        event.context.createdAt = new Moment();
      };

      const plugin = {
        provides: {
          generateConfig: onGenerateConfig,
        },
      };

      const result = await manager.init(plugin, npm);

      expect(result).to.deep.equal(manager);
      expect(typeof result._events.generateConfig[0]).to.equal('function');
      expect(typeof result._events.error[0]).to.equal('function');
      expect(typeof result._events.postInit[0]).to.equal('function');
      expect(typeof result._events.postInit[1]).to.equal('function');
      expect(typeof result._events.exit[0]).to.equal('function');
    });

    it('removes handler on exit', async () => {
      const result = await manager.init({}, npm);

      await manager.dispatch('exit', manager);

      expect(result).to.deep.equal(manager);
      expect(Object.keys(result._events).length).to.equal(0);
    });

    it('local event handler overrides external', async () => {
      const setDefaultMaxHandlers = (event) => {
        const mgr = event.context;

        if (mgr) {
          mgr.setMaxHandlers(10);
        }
      };

      const plugin = {
        provides: {
          postInit: setDefaultMaxHandlers,
        },
      };

      await manager.init(plugin, npm);

      const handlers = manager.handlers('postInit')
        .filter((handler) =>
          handler.name === 'setDefaultMaxHandlers');

      expect(handlers.length).to.equal(1);
      expect(manager._defaultMaxHandlers).to.equal(10);
    });

    it('local event handler adds to external', async () => {
      const setDefaultMaxHandlers = (event) => {
        const mgr = event.context;

        if (mgr) {
          mgr.setMaxHandlers(20);
        }
      };

      manager._override = false;

      const plugin = {
        provides: {
          postInit: setDefaultMaxHandlers,
        },
      };

      await manager.init(plugin, npm);

      const handlers = manager.handlers('postInit')
        .filter((handler) =>
          handler.name === 'setDefaultMaxHandlers');

      expect(handlers.length).to.equal(2);
      expect(manager._defaultMaxHandlers).to.equal(20);
    });
  });

  describe('hasHandlers', () => {
    it('returns true if it has at least one handler for an event', async () => {
      await manager.init({}, npm);

      expect(manager.hasHandlers('postInit')).to.equal(true);
    });

    it('returns false if it does not have any handlers for an event', async () => {
      await manager.init({}, npm);

      expect(manager.hasHandlers('preInit')).to.equal(false);
    });

    it('throw error if hasHandlers() not passed an event name', async () => {
      await manager.init({}, npm);

      try {
        manager.hasHandlers();
      } catch (error) {
        expect(error.message).to.equal('Undefined event name');
      }
    });
  });

  describe('dispatch', () => {
    it('throws error if event name is not provided', async () => {
      try {
        await manager.init({}, npm);

        await manager.dispatch();
      } catch (error) {
        expect(error.message).to.equal('Event name not provided');
      }
    });

    it('dispatch event without context object should work', async () => {
      const config = { debug: true, start: 0 };

      const getConfig = (event) => {
        event.context.config = config;
      };

      const plugin = {
        provides: {
          preExec: getConfig,
        },
      };

      await manager.init(plugin, npm);

      const result = await manager.dispatch('preExec');

      expect(result.config).to.deep.equal(config);
    });
  });

  describe('addHandler', () => {
    it('accepts a new function handler for event', () => {
      const handler = (event) => {
        const context = event.context;

        context.data = 'data';
      };

      let handlers = manager.handlers('getData');

      expect(handlers.length).to.equal(0);

      const man = manager.addHandler('getData', handler);

      handlers = man.handlers('getData');

      expect(handlers.length).to.equal(1);
    });

    it('throws error when too many handlers are added for event', () => {
      try {
        const handler = (event) => {
          const context = event.context;

          context.data = 'data';
        };

        manager._defaultMaxHandlers = 1;

        manager.addHandler('getData', handler);
        manager.addHandler('getData', handler);
      } catch (error) {
        expect(error.message).to.equal('Exceeded maximum number of handlers for \'getData\' event');
      }
    });
  });

  describe('removeAllHandlers', () => {
    it('removes all handlers for an event', async () => {
      await manager.init({}, npm);

      expect(manager.handlers('postInit').length).to.equal(2);

      manager.removeAllHandlers('postInit');

      expect(manager.handlers('postInit').length).to.equal(0);
    });
  });

  describe('_getCallback', () => {
    it('loads plugin functions', async () => {
      const plugin = 'plugged-in-extras-plugin';
      const handlerName = 'cleanUp';

      const handler = await manager._getCallback(plugin, handlerName);

      expect(typeof handler).to.equal('function');
      expect(handler.name).to.equal(handlerName);
    });
  });
});

  Generated by ESDoc(0.4.8)


text:
package com.simoncat.framework.lucene;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import com.simoncat.framework.lucene.annotation.DeclareAsLuceneIndex;
import com.simoncat.framework.lucene.annotation.LuceneField;
import com.simoncat.framework.lucene.annotation.LuceneField.FieldType;

@Data
@AllArgsConstructor
@NoArgsConstructor
@DeclareAsLuceneIndex
public class LuceneTestData {

	@LuceneField(isKey=true, name="name")
	private String name;

	@LuceneField(name="description", type=FieldType.TEXT_FIELD, isStored=true)
	private String description;

	@LuceneField(name="count", type=FieldType.LONG_FIELD)
	private Long count;
}


text:
function getFormState() {
    var fields = document.getElementsByTagName('form')[0].elements;
    if (fields.length == 0){return};
    for (var i = 0; i <= fields.length-1; i++) {
        var name = fields[i].getAttribute('name');
        if (name in localStorage && localStorage[name] !== null) {
            fields[i].value = localStorage[name];
        }
    }
}

function saveFormState() {
    var fields = document.getElementsByTagName('form')[0].elements;
    if (fields.length == 0){return};
    var populated = false;
    for (var i = 0; i <= fields.length-1; i++) {
        var name = fields[i].getAttribute('name');
        if (fields[i].value != '' && fields[i].getAttribute('type') != 'submit') {
           localStorage[name] = fields[i].value;
           populated = true;
        }
    }
    // display the time form data was saved (optional)
    if (populated) {
        var date = new Date();
        var hours = date.getHours();
        var mins = date.getMinutes();
        var secs = date.getSeconds();
        hours = (hours < 10) ? '0' + hours : hours;
        mins = (mins < 10) ? '0' + mins : mins;
        secs = (secs < 10) ? '0' + secs : secs;
        var msg = 'Form data was saved at ' + hours + ':' + mins + ':' + secs;
        var timecont = document.getElementById('time_container');
        if (timecont !== null) {
            timecont.innerHTML = msg;
        }
        else {
            timecont = document.createElement('span');
            timecont.setAttribute('id', 'time_container');
            timecont.appendChild(document.createTextNode(msg));
            document.getElementsByTagName('form')[0].appendChild(timecont);
        }
    }
}

// run the above functions when the web page is loaded
window.onload = function () {
    // check if HTML5 localStorage is supported by the browser
    if ('localStorage' in window && window['localStorage'] !== null) {
        // get the form state
        getFormState();
        // save the state of the form each 15 seconds (customizable)
        setInterval('saveFormState()', 15 * 1000);
    }
}

function checkWordLen(obj,wl,section){
      var len = obj.value.split(/[\s]+/);
       if(len.length > wl){
           alert("You cannot put more than "+wl+" words in the "+section+" section. You have "+len.length+" words.");
           obj.oldValue = obj.value!=obj.oldValue?obj.value:obj.oldValue;
           obj.value = obj.oldValue?obj.oldValue:"";
           return false;
       }
     return true;
}


text:
package org.apache.flink.table.api.stream.table.validation

import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.api.java.typeutils.RowTypeInfo
import org.apache.flink.table.api.internal.TableEnvironmentInternal
import org.apache.flink.table.api.scala._
import org.apache.flink.table.api.{TableException, TableSchema, Types}
import org.apache.flink.table.utils.{TableTestBase, TestFilterableTableSourceWithoutExplainSourceOverride, TestProjectableTableSourceWithoutExplainSourceOverride}
import org.hamcrest.Matchers
import org.junit.Test

class TableSourceValidationTest extends TableTestBase {

  @Test
  def testPushProjectTableSourceWithoutExplainSource(): Unit = {
    expectedException.expectCause(Matchers.isA(classOf[TableException]))

    val tableSchema = new TableSchema(
      Array("id", "rtime", "val", "ptime", "name"),
      Array(Types.INT, Types.SQL_TIMESTAMP, Types.LONG, Types.SQL_TIMESTAMP, Types.STRING))
    val returnType = new RowTypeInfo(
      Array(Types.INT, Types.STRING, Types.LONG, Types.LONG)
        .asInstanceOf[Array[TypeInformation[_]]],
      Array("id", "name", "val", "rtime"))

    val util = streamTestUtil()
    util.tableEnv.asInstanceOf[TableEnvironmentInternal].registerTableSourceInternal(
      "T",
      new TestProjectableTableSourceWithoutExplainSourceOverride(
        tableSchema, returnType, Seq(), "rtime", "ptime"))

    val t = util.tableEnv.scan("T").select('name, 'val, 'id)

    // must fail since pushed projection is not explained in source
    util.explain(t)
  }

  @Test
  def testPushFilterableTableSourceWithoutExplainSource(): Unit = {
    expectedException.expectCause(Matchers.isA(classOf[TableException]))

    val tableSource = TestFilterableTableSourceWithoutExplainSourceOverride()
    val util = batchTestUtil()

    util.tableEnv.asInstanceOf[TableEnvironmentInternal]
      .registerTableSourceInternal("T", tableSource)

    val t = util.tableEnv
      .scan("T")
      .select('price, 'id, 'amount)
      .where($"price" * 2 < 32)

    // must fail since pushed filter is not explained in source
    util.explain(t)
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Zveen.MultiMenu.Models;

namespace System.Web.Mvc
{
    public static class UrlHelperExtensioms
    {
        public static string MultiMenuAdminList(this UrlHelper helper, int idMultiMenu)
        {
            return helper.Action("List", "MultiMenuAdmin", new { area = "Zveen.MultiMenu", idMultiMenu = idMultiMenu });
        }
    }
}


text:
default['ceph']['config'] = {}
default['ceph']['config-sections'] = {}
default['ceph']['config']['keystone']['rgw keystone accepted roles'] = 'admin, _member_'
default['ceph']['config']['keystone']['rgw keystone token cache size'] = 500
default['ceph']['config']['keystone']['rgw keystone revocation interval'] = 600
default['ceph']['config']['keystone']['nss db path'] = '/var/ceph/nss'
default['ceph']['config']['keystone']['rgw keystone admin token'] = 'openstack_identity_bootstrap_token'


text:
package io.github.m0pt0pmatt.survivalgames.game;

/** The different states a Survival Game can be in once it is running. */
public enum SurvivalGameRunningState {
    STOPPED,
    IN_PROGRESS,
    DEATH_MATCH
}


text:
module BeachApiCore
  class ProjectPolicy < ApplicationPolicy
    def update?
      record.user == user
    end
    alias destroy? update?
  end
end


text:
from urdf_parser_py.xml_reflection.basics import *
import urdf_parser_py.xml_reflection as xmlr

xmlr.start_namespace('srdf')

verbose = True

# Common stuff
name_attribute = xmlr.Attribute('name', str)

class Link(xmlr.Object):
  def __init__(self, name = None):
    self.name = name

xmlr.reflect(Link, params = [
   name_attribute
  ])

class Joint(xmlr.Object):
  def __init__(self, name = None):
    self.name = name

xmlr.reflect(Joint, params = [
   name_attribute
  ])

class JointVal(xmlr.Object):
  def __init__(self, name = None, value = []):
    self.name = name
    self.value = value

xmlr.reflect(JointVal, params = [
   name_attribute,
   xmlr.Attribute('value', "vector")
  ])

class Sphere(xmlr.Object):
  def __init__(self, center = None, radius = 0.0):
    self.center = center
    self.radius = radius

xmlr.reflect(Sphere, params = [
   xmlr.Attribute('center', str),
   xmlr.Attribute('radius', float)
  ])

# Common stuff again
link_element = xmlr.Element('link', Link, False)

class VirtualJoint(xmlr.Object):
  TYPES = ['unknown', 'fixed', 'floating', 'planar']

  def __init__(self, name = None, child_link = None, parent_frame = None, joint_type = None):
    self.name = name
    self.child_link = child_link
    self.parent_frame = parent_frame
    self.type = joint_type

  def check_valid(self):
    assert self.type in self.TYPES, "Invalid joint type: {}".format(self.type)

  # Aliases
  @property
  def joint_type(self): return self.type
  @joint_type.setter
  def joint_type(self, value): self.type = value

xmlr.reflect(VirtualJoint, params = [
  name_attribute,
  xmlr.Attribute('child_link', str),
  xmlr.Attribute('parent_frame', str),
  xmlr.Attribute('type', str)
  ])

class Chain(xmlr.Object):
  def __init__(self, base_link = None, tip_link = None):
    self.base_link = base_link
    self.tip_link = tip_link

xmlr.reflect(Chain, params = [
  xmlr.Attribute('base_link', str),
  xmlr.Attribute('tip_link', str)
  ])

class EndEffector(xmlr.Object):
  def __init__(self, name = None, group = None, parent_link = None, parent_group = None):
    self.name = name
    self.group = group
    self.parent_link = parent_link
    self.parent_group = parent_group

xmlr.reflect(EndEffector, params = [
  name_attribute,
  xmlr.Attribute('group', str),
  xmlr.Attribute('parent_link', str),
  xmlr.Attribute('parent_group', str, False)
  ])

class PassiveJoint(xmlr.Object):
  def __init__(self, name = None):
    self.name = name

xmlr.reflect(PassiveJoint, params = [
  name_attribute
  ])

class DisableCollisions(xmlr.Object):
  def __init__(self, link1 = None, link2 = None, reason = None):
    self.link1 = link1
    self.link2 = link2
    self.reason = reason

xmlr.reflect(DisableCollisions, params = [
  xmlr.Attribute('link1', str),
  xmlr.Attribute('link2', str),
  xmlr.Attribute('reason', str, False)
  ])

class Group(xmlr.Object):
  def __init__(self, name = None):
    self.aggregate_init()
    self.name = name
    self.links = []
    self.joints = []
    self.chains = []
    self.groups = []
    self.subgroups = self.groups

xmlr.reflect(Group, params = [
  name_attribute,
  xmlr.AggregateElement('link', Link),
  xmlr.AggregateElement('joint', Joint),
  xmlr.AggregateElement('chain', Chain),
  xmlr.AggregateElement('group', Group)
  ])

class GroupState(xmlr.Object):
  def __init__(self, name = None, group = None):
    self.aggregate_init()
    self.name = name
    self.joints = []
    self.group = group

xmlr.reflect(GroupState, params = [
  name_attribute,
  xmlr.AggregateElement('joint', JointVal),
  xmlr.Attribute('group', str)
  ])

class LinkSphereApproximation(xmlr.Object):
  def __init__(self, link = None):
    self.aggregate_init()
    self.link = link
    self.spheres = []

xmlr.reflect(LinkSphereApproximation, params = [
  xmlr.Attribute('link', str),
  xmlr.AggregateElement('sphere', Sphere)
  ])

class Robot(xmlr.Object):
  def __init__(self, name = None):
    self.aggregate_init()

    self.name = name
    self.groups = []
    self.group_states = []
    self.end_effectors = []
    self.virtual_joints = []
    self.disable_collisionss = []
    self.passive_joints = []
    self.link_sphere_approximations = []
    self.group_map = {}
    self.group_state_map = {}

  def add_aggregate(self, typeName, elem):
    xmlr.Object.add_aggregate(self, typeName, elem)

    if typeName == 'group':
      group = elem
      self.group_map[group.name] = group
    elif typeName == 'group_state':
      group_state = elem
      self.group_state_map[group_state.name] = group_state

  def add_link(self, link):
    self.add_aggregate('link', link)

  def add_joint(self, joint):
    self.add_aggregate('joint', joint)

  def add_chain(self, chain):
    self.add_aggregate('chain', chain)

  def add_group(self, group):
    self.add_aggregate('group', group)

  def add_passive_joint(self, joint):
    self.add_aggregate('passive_joint', joint)

  def add_disable_collisions(self, col):
    self.add_aggregate('disable_collisions', col)

  def add_link_sphere_approximation(self, link):
    self.add_aggregate('link_sphere_approximation', link)

  @classmethod
  def from_parameter_server(cls, key = 'robot_description_semantic'):
    """
    Retrieve the robot semantic model on the parameter server
    and parse it to create a SRDF robot structure.

    Warning: this requires roscore to be running.
    """
    # Could move this into xml_reflection
    import rospy
    return cls.from_xml_string(rospy.get_param(key))

xmlr.reflect(Robot, tag = 'robot', params = [
#   name_attribute,
  xmlr.Attribute('name', str, False), # Is 'name' a required attribute?
  xmlr.AggregateElement('group', Group),
  xmlr.AggregateElement('group_state', GroupState),
  xmlr.AggregateElement('end_effector', EndEffector),
  xmlr.AggregateElement('virtual_joint', VirtualJoint),
  xmlr.AggregateElement('passive_joint', PassiveJoint),
  xmlr.AggregateElement('disable_collisions', DisableCollisions),
  xmlr.AggregateElement('link_sphere_approximation', LinkSphereApproximation)
  ])

# Make an alias
SRDF = Robot

xmlr.end_namespace()


text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = require("react");
var react_router_1 = require("react-router");
require("./PageNotFound.less");
var PageNotFound = (function (_super) {
    __extends(PageNotFound, _super);
    function PageNotFound(props) {
        return _super.call(this, props) || this;
    }
    PageNotFound.prototype.render = function () {
        return (React.createElement("div", { className: "container" },
            React.createElement("div", { className: "text-center" },
                React.createElement("div", { className: "col-md-12 characters" }),
                React.createElement("div", { className: "col-md-12" },
                    React.createElement("h1", null, "Page not found"),
                    React.createElement("p", null, "Sorry, an error has occured, the page you are trying to visit is not available."),
                    React.createElement("p", null, "It could be a broken or dead link!"),
                    React.createElement("p", null,
                        React.createElement(react_router_1.Link, { to: "/", className: "btn btn-primary" },
                            React.createElement("i", { className: "fa fa-lg fa-home" }),
                            " Go back to Home Page")),
                    React.createElement("hr", null),
                    React.createElement("a", { href: "//github.com/hegdeashwin/alphonso", target: "_blank", className: "btn btn-link btn-sm" }, "Github Home Page"),
                    React.createElement("a", { href: "//github.com/hegdeashwin/alphonso/releases", target: "_blank", className: "btn btn-link btn-sm" }, "Release Page"),
                    React.createElement("a", { href: "//github.com/hegdeashwin/alphonso/milestones", target: "_blank", className: "btn btn-link btn-sm" }, "Milestones"),
                    React.createElement("a", { href: "//github.com/hegdeashwin/alphonso/issues", target: "_blank", className: "btn btn-link btn-sm" }, "Report Issues"),
                    React.createElement("a", { href: "//github.com/hegdeashwin/alphonso/pulls", target: "_blank", className: "btn btn-link btn-sm" }, "Open Pull Requests"),
                    React.createElement("a", { href: "//github.com/hegdeashwin/alphonso", target: "_blank", className: "btn btn-link btn-sm" }, "About Alphonso")))));
    };
    return PageNotFound;
}(React.Component));
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = PageNotFound;
//# sourceMappingURL=PageNotFound.js.map