text:
#ifndef UA_SUBSCRIPTION_H_
#define UA_SUBSCRIPTION_H_

#include "ua_util.h"
#include "ua_types.h"
#include "ua_types_generated.h"
#include "ua_nodes.h"
#include "ua_session.h"

/*****************/
/* MonitoredItem */
/*****************/

typedef enum {
    MONITOREDITEM_TYPE_CHANGENOTIFY = 1,
    MONITOREDITEM_TYPE_STATUSNOTIFY = 2,
    MONITOREDITEM_TYPE_EVENTNOTIFY = 4
} UA_MONITOREDITEM_TYPE;

typedef struct MonitoredItem_queuedValue {
    UA_DataValue value;
    TAILQ_ENTRY(MonitoredItem_queuedValue) listEntry;
} MonitoredItem_queuedValue;

typedef struct UA_MonitoredItem {
    LIST_ENTRY(UA_MonitoredItem) listEntry;
    UA_UInt32 itemId;
    UA_MONITOREDITEM_TYPE monitoredItemType;
    UA_UInt32 timestampsToReturn;
    UA_UInt32 monitoringMode;
    UA_NodeId monitoredNodeId;
    UA_UInt32 attributeID;
    UA_UInt32 clientHandle;
    UA_UInt32 samplingInterval; // [ms]
    UA_BoundedUInt32 queueSize;
    UA_Boolean discardOldest;
    UA_DateTime lastSampled;
    UA_ByteString lastSampledValue;
    // FIXME: indexRange is ignored; array values default to element 0
    // FIXME: dataEncoding is hardcoded to UA binary
    TAILQ_HEAD(QueueOfQueueDataValues, MonitoredItem_queuedValue) queue;
} UA_MonitoredItem;

UA_MonitoredItem *UA_MonitoredItem_new(void);
void MonitoredItem_delete(UA_MonitoredItem *monitoredItem);
void MonitoredItem_QueuePushDataValue(UA_Server *server, UA_MonitoredItem *monitoredItem);
void MonitoredItem_ClearQueue(UA_MonitoredItem *monitoredItem);
UA_Boolean MonitoredItem_CopyMonitoredValueToVariant(UA_UInt32 attributeID, const UA_Node *src,
                                                     UA_DataValue *dst);
UA_UInt32 MonitoredItem_QueueToDataChangeNotifications(UA_MonitoredItemNotification *dst,
                                                       UA_MonitoredItem *monitoredItem);

/****************/
/* Subscription */
/****************/

typedef struct UA_unpublishedNotification {
    UA_Boolean publishedOnce;
    LIST_ENTRY(UA_unpublishedNotification) listEntry;
    UA_NotificationMessage notification;
} UA_unpublishedNotification;

struct UA_Subscription {
    LIST_ENTRY(UA_Subscription) listEntry;
    UA_BoundedUInt32 lifeTime;
    UA_BoundedUInt32 keepAliveCount;
    UA_Double publishingInterval;     // [ms]
    UA_DateTime lastPublished;
    UA_UInt32 subscriptionID;
    UA_UInt32 notificationsPerPublish;
    UA_Boolean publishingMode;
    UA_UInt32 priority;
    UA_UInt32 sequenceNumber;
    UA_Guid timedUpdateJobGuid;
    UA_Boolean timedUpdateIsRegistered;
    LIST_HEAD(UA_ListOfUnpublishedNotifications, UA_unpublishedNotification) unpublishedNotifications;
    size_t unpublishedNotificationsSize;
    LIST_HEAD(UA_ListOfUAMonitoredItems, UA_MonitoredItem) MonitoredItems;
};

UA_Subscription *UA_Subscription_new(UA_UInt32 subscriptionID);
void UA_Subscription_deleteMembers(UA_Subscription *subscription, UA_Server *server);
void Subscription_updateNotifications(UA_Subscription *subscription);
UA_UInt32 *Subscription_getAvailableSequenceNumbers(UA_Subscription *sub);
void Subscription_generateKeepAlive(UA_Subscription *subscription);
void Subscription_copyTopNotificationMessage(UA_NotificationMessage *dst, UA_Subscription *sub);
UA_UInt32 Subscription_deleteUnpublishedNotification(UA_UInt32 seqNo, UA_Boolean bDeleteAll, UA_Subscription *sub);
void Subscription_copyNotificationMessage(UA_NotificationMessage *dst, UA_unpublishedNotification *src);
UA_StatusCode Subscription_createdUpdateJob(UA_Server *server, UA_Guid jobId, UA_Subscription *sub);
UA_StatusCode Subscription_registerUpdateJob(UA_Server *server, UA_Subscription *sub);
UA_StatusCode Subscription_unregisterUpdateJob(UA_Server *server, UA_Subscription *sub);

#endif /* UA_SUBSCRIPTION_H_ */


text:
package com.annotations.openface.omnibean.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;

import com.annotations.openface.omnibean.OmniBean;
import com.annotations.openface.omnibean.protobuf.InvalidProtocolBufferException;
import com.annotations.openface.omnibean.util.IoBuffer;
import static com.annotations.openface.omnibean.util.FieldType.*;

public class FieldSet {
	private int serial;
	private FieldType type;
	private boolean required;
	private boolean packed;
	private Field field;
	private FieldType genericType;

	public FieldSet(Field field,int serial,FieldType type,FieldType genericType){
		this.field = field;
		this.serial = serial;
		this.type = type;
		this.genericType = genericType;
		this.required = false;
		this.packed = true;
	}
	public FieldSet(Field field) throws InvalidProtocolBufferException{
		this.field = field;
		Define define = BeanUtil.getDefineAnnotation(field);
		if (define != null) {
			this.serial = define.serial();
			this.required = define.required();
			this.type = define.type();
			this.genericType = define.genericType();
			this.packed = define.packed();
		}else{
			throw new InvalidProtocolBufferException("Filed:"+field.getName()+" has no Define annotation.");
		}
	}
	private FieldSet(){}
	public FieldSet getGenericFieldSet(){
		FieldSet fs = new FieldSet();
		fs.serial = this.serial;
		fs.type = this.genericType;
		return fs;
	}

	public int getSerial() {
		return serial;
	}

	public FieldType getType() {
		return type;
	}

	public boolean isPacked() {
		return packed;
	}

	public boolean isRequired() {
		return required;
	}

	public Field getField() {
		return field;
	}

	public FieldType getGenericType() {
		return genericType;
	}

	private void setPublicValue(Object obj, Object value) {
		try {
			switch (type) {
			case DOUBLE:
				field.setDouble(obj, (Double) value);
				return;
			case FLOAT:
				field.setFloat(obj, (Float) value);
				return;
			case INT64:
				field.setLong(obj, (Long) value);
				return;
			case UINT64:
				field.setLong(obj, (Long) value);
				return;
			case INT32:
				field.setInt(obj, (Integer) value);
				return;
			case FIXED64:
				field.setLong(obj, (Long) value);
				return;
			case FIXED32:
				field.setInt(obj, (Integer) value);
				return;
			case BOOL:
				field.setBoolean(obj, (Boolean) value);
				return;
			case STRING:
				field.set(obj, (String) value);
				return;
			case MESSAGE:
				field.set(obj, (OmniBean) value);
				return;
			case BYTES:
				field.set(obj, ((IoBuffer) value).toArray());
				return;
			case UINT32:
				field.setInt(obj, (Integer) value);
				return;
			case SFIXED32:
				field.setInt(obj, (Integer) value);
				return;
			case SFIXED64:
				field.setLong(obj, (Long) value);
				return;
			case SINT32:
				field.setInt(obj, (Integer) value);
				return;
			case SINT64:
				field.setLong(obj, (Long) value);
				return;
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return;
	}

	public void setFieldValue(Object obj, Object value) {
		try {
			if (Modifier.isPublic(field.getModifiers())) {
				setPublicValue(obj, value);
			}
			String setName = BeanUtil.getSetName(field.getName());
			Method method = obj.getClass().getMethod(setName,
					new Class[] { field.getType() });
			if(this.type.equals(BOOL)){
				if(value.getClass().getSimpleName().toLowerCase().startsWith("int")){
					value = new Boolean(((Integer)value).intValue()!=0);
				}else if(value.getClass().getSimpleName().toLowerCase().startsWith("long")){
					value = new Boolean(((Long)value).longValue()!=0);
				}else if(value.getClass().getSimpleName().toLowerCase().startsWith("string")){
					value = new Boolean(((String)value).toLowerCase().equals("true"));
				}
			}else if(this.type.equals(INT64)||this.type.equals(UINT64)||this.type.equals(SINT64)||this.type.equals(FIXED64)||this.type.equals(SFIXED64)){
				if(value.getClass().getSimpleName().toLowerCase().startsWith("int")){
					value = new Long(((Integer)value).intValue());
				}
			}
			method.invoke(obj, new Object[] { value });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// ListԪ���ù�add�������
	public void addListFiledValue(Object obj, Object value) {
		try {
			String addName = BeanUtil.getAddName(field.getName());
			Method method = obj.getClass().getMethod(
					addName,
					new Class[] { (Class<?>) ((ParameterizedType) field
							.getGenericType()).getActualTypeArguments()[0] });
			method.invoke(obj, new Object[] { value });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// EnumԪ��ͨ��˷������
	public void setEnumVlaue(Object object, int value) {
		Class<?> c = field.getType();
		if (c.getSuperclass().getSimpleName().equals("ProtocolBufferEnum")) {
			try {
				Constructor<?> constructor = c.getConstructor(int.class);
				Object obj = constructor.newInstance(value);
				setFieldValue(object, obj);
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
A SQS job queue plugin for Seneca

It support send/receive messages to/from a given Amazon SQS queue.

In order to receive a message you should add a Seneca patter that will match the message you are sending i.e:

  ```js
  seneca.add({type: 'task'}, function (args, next) {
    console.log(args);
    next();  // This is needed to receive the next message
  })
  ```
and then start the receiver with:

  ```js
  seneca.act({role: 'queue', cmd: 'start'});
  ```

this will receive all the messages containing a `type` key with the `task` value, to send a message like this use:

  ```js
  seneca.act({role: 'queue', cmd: 'enqueue', msg: {type: 'task', number '42'}});
  ```

you can stop the queue with:

  ```js
  seneca.act({role: 'queue', cmd: 'stop'});
  ```

## Events

As you may suspect, when we stop the receiver it doesn't stop right away.
If we want to execute and action when the receiver is stopped we can subscribe to the 'stopped' event

  ```js
  seneca.add({
      role: 'queue',
      evnt: 'stopped'
    }, function () {
      console.log("RECEIVER STOPPED");
  });
  ```

You can do the same for the `empty` event, it is emitted every time the receiver time out waiting for a message.

# Test

To run the tests you need to create a `config/test_env` file using `config/example_env` as example and provide all the required information
The you can run:

  ```js
  npm test
  ```

# Acknowledgements

Sponsored by [nearForm](http://www.nearform.com/)

##
## License

MIT


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>wCMF 4.0: NodeIterator Class Reference</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="A MDSD framework for building reliable, maintainable and extendable web applications with PHP">
  <meta name="keywords" content="PHP, web application framework, model driven development">
  <meta name="author" content="wemove digital solutions">
  <link rel="shortcut icon" href="theme/images/favicon.ico">

  <link href="theme/css/doxstyles.css" rel="stylesheet">

  <link href="theme/bootstrap3/css/bootstrap.min.css" rel="stylesheet">
  <link href="theme/bootstrap3/css/font-awesome.min.css" rel="stylesheet">

  <link href="theme/js/tocify/jquery.tocify.css" rel="stylesheet">

  <link href="theme/css/syntax.css" rel="stylesheet">
  <link href="theme/css/style.css" rel="stylesheet">

          <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".menu-navbar-collapse">
            Toggle navigation
          </button>
          wCMF 4.0

 Guides

Getting started

Architecture

Model

Persistence

Presentation

Configuration

Security

I18n & l10n

Tests

 API

 Code

 Support

                <input id="MSearchField" type="text" class="form-control" placeholder="Search API" name="query" onkeyup="searchBox.OnSearchFieldChange(event)">

wcmf

lib

model

NodeIterator

Public Member Functions |
Protected Member Functions |
Protected Attributes |
List of all members

NodeIterator Class Reference

Detailed Description

NodeIterator is used to iterate over a tree/list built of Nodes using a Depth-First-Algorithm.

Classes used with the NodeIterator must implement the getChildren() and getOID() methods.

The following example shows the usage:

// load the node with depth 10

$node = ObjectFactory::getInstance('persistenceFacade')->load(new ObjectId('Page', 300), 10);

// iterate over all children

$it = new NodeIterator($node);

foreach($it as $oid => $obj) {

  echo("current object id: ".$oid);

  echo("current object: ".$obj);

}

Author

ingo herwig ingo@.nosp@m.wemo.nosp@m.ve.co.nosp@m.m

Definition at line 36 of file NodeIterator.php.

   Inheritance diagram for NodeIterator:

This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.

Public Member Functions

 	__construct ($node, $aggregationKinds=array())

 	current ()

 	key ()

 	next ()

 	rewind ()

 	valid ()

Protected Member Functions

 	addToQueue ($nodeList)

Protected Attributes

 	$_end

 	$_nodeList

 	$_processedOidList

 	$_currentNode

 	$_startNode

 	$_aggregationKinds

Constructor & Destructor Documentation

          __construct
          (

          $node,

          $aggregationKinds = array()

          )

Constructor.

Parameters

$node	The node to start from.

$aggregationKinds	Array of aggregation kind values of relations to follow possible values: 'none', 'shared', 'composite'. Empty array means all (default: empty)

Definition at line 51 of file NodeIterator.php.

Member Function Documentation

          current
          (
          	)

Return the current element.

Returns

Node instance

Definition at line 64 of file NodeIterator.php.

          key
          (
          	)

Return the key of the current element.

Returns

String, the serialized object id

Definition at line 72 of file NodeIterator.php.

          next
          (
          	)

Move forward to next element.

Definition at line 79 of file NodeIterator.php.

          rewind
          (
          	)

Rewind the Iterator to the first element.

Definition at line 126 of file NodeIterator.php.

          valid
          (
          	)

Checks if current position is valid.

Definition at line 136 of file NodeIterator.php.

          addToQueue
          (

          $nodeList	)

protected

Add nodes to the processing queue.

Parameters

$nodeList	An array of nodes.

Definition at line 144 of file NodeIterator.php.

Member Data Documentation

          $_end

protected

Definition at line 38 of file NodeIterator.php.

          $_nodeList

protected

Definition at line 39 of file NodeIterator.php.

          $_processedOidList

protected

Definition at line 40 of file NodeIterator.php.

          $_currentNode

protected

Definition at line 41 of file NodeIterator.php.

          $_startNode

protected

Definition at line 42 of file NodeIterator.php.

          $_aggregationKinds

protected

Definition at line 43 of file NodeIterator.php.

        © 2016 wemove digital solutions

          Generated on Fri Jul 15 2016 22:20:44 for wCMF by  doxygen 1.8.10


text:
<!DOCTYPE html>

<title>Yuzhouwan Shopping | Contacts</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="shortcut" href="images/favicon.ico" />
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/contact.css" />

				<form action="http://sc.chinaz.com/" id="searchForm">
					<fieldset>
						Search <input id="term" type="text" />
						<input type="submit" value="Submit" />
					</fieldset>
				</form>

Contacts

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
							sed do eiusmod tempor incididunt ut labore et dolore magna
							aliqua. Ut enim ad minim veniam, quis nostrud exercitation
							ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem
							ipsum dolor sit amet, consectetur adipisicing elit, sed do
							eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
							enim ad minim veniam, quis commodo consequat.

								Address Info 1:
 123 Main
									Street Los Angeles, CA, 94101
 Phone:
									+1 800 123 4567
 FAX:  +1
									800 891 2345
 Email: testmail@sitename.com

								Address Info 1:
 123 Main
									Street Los Angeles, CA, 94101
 Phone:
									+1 800 123 4567
 FAX:  +1
									800 891 2345
 Email: testmail@sitename.com

Leave a Reply

							<form method="post"
								action="http://sc.chinaz.com/games/contact.php" id="contactform">
								<fieldset>

											*Your
												Name: <input type="text" name="name" id="name" />

											*E-mail:
											<input type="text" name="email" id="email" />

											Phone: <input type="text"
												name="phone" id="phone" />

											Subject <select name="subject"
												id="subject">
												<option value="Support">Support</option>
												<option value="a Sale">Sales</option>
												<option value="a Bug fix">Report a bug</option>
											</select>

										<input type="submit" class="button green small" id="submit"
											value="Submit" />

										Message:
										<textarea name="comments" id="comments" cols="30" rows="10"></textarea>

								</fieldset>
							</form>


text:
package OptimizationTests.ShortMethodsInliningNonVirtualInvokes.InvokeSuperAShortThrowNullSet_001;
// The test checks that stack after NullPointerException occurs is correct despite inlining
class Main {
    final static int iterations = 10;

    public static void main(String[] args) {
        Test test = new Test(iterations);

        short nextThingy = -32768;
        short sumArrElements = 0;
        for(int i = 0; i < iterations; i++) {
            SuperTest.thingiesArray[i] = (short)(nextThingy + 1);
            sumArrElements = (short)(sumArrElements + SuperTest.thingiesArray[i]);
        }

        for(int i = 0; i < iterations; i++) {
            nextThingy = (short)(test.getThingies(SuperTest.thingiesArray, i) + 1);
            if (i == iterations - 1)
                SuperTest.thingiesArray = null;
            test.setThingies(SuperTest.thingiesArray, nextThingy, i);
        }

    }
}


text:
using Hevadea.Framework;
using Hevadea.Framework.Graphic;
using Hevadea.Framework.UI;
using Hevadea.Scenes.Widgets;
using Microsoft.Xna.Framework;

namespace Hevadea.Scenes.Tabs
{
    public class SaveTab : Tab
    {
        public SaveTab(GameState gameState)
        {
            Icon = new Sprite(Resources.TileIcons, new Point(3, 2));

            var container = new LayoutFlow
            {
                Dock = Dock.Fill,
                Flow = LayoutFlowDirection.TopToBottom,
                Marging = 8,
            };

            Content = new LayoutDock()
            {
                Padding = new Spacing(16),
                Children =
                {
                    new WidgetLabel {Text = "Save", Font = Resources.FontAlagard, Dock = Dock.Top},
                    container
                }
            };

            container.AddChild(
                new WidgetButton
                    {
                        Text = "Quick save",
                        Padding = new Spacing(4)
                    }
                    .RegisterMouseClickEvent(gameState.QuickSave)
            );

            container.AddChild(
                new WidgetButton
                    {
                        Text = "Save and Exit",
                        Padding = new Spacing(4)
                    }
                    .RegisterMouseClickEvent(gameState.SaveAndExit)
            );

            container.AddChild(
                new WidgetButton
                    {
                        Text = "Exit",
                        Padding = new Spacing(4)
                    }
                    .RegisterMouseClickEvent(Game.GoToMainMenu)
            );
        }
    }
}


text:
'use strict';
const test = require('tap').test;
const Test = require('../lib/test');
const Observable = require('zen-observable'); // eslint-disable-line import/order

function ava(fn) {
	const a = new Test(fn);
	a.metadata = {callback: false};
	return a;
}

ava.cb = function (fn) {
	const a = new Test(fn);
	a.metadata = {callback: true};
	return a;
};

test('returning an observable from a legacy async fn is an error', t => {
	ava.cb(a => {
		a.plan(2);

		const observable = Observable.of();

		setTimeout(() => {
			a.pass();
			a.pass();
			a.end();
		}, 200);

		return observable;
	}).run().then(result => {
		t.is(result.passed, false);
		t.match(result.reason.message, /Do not return observables/);
		t.end();
	});
});

test('handle throws with thrown observable', t => {
	ava(a => {
		a.plan(1);

		const observable = new Observable(observer => {
			observer.error(new Error());
		});

		return a.throws(observable);
	}).run().then(result => {
		t.is(result.passed, true);
		t.is(result.result.assertCount, 1);
		t.end();
	});
});

test('handle throws with long running thrown observable', t => {
	ava(a => {
		a.plan(1);

		const observable = new Observable(observer => {
			setTimeout(() => {
				observer.error(new Error('abc'));
			}, 2000);
		});

		return a.throws(observable, /abc/);
	}).run().then(result => {
		t.is(result.passed, true);
		t.is(result.result.assertCount, 1);
		t.end();
	});
});

test('handle throws with completed observable', t => {
	ava(a => {
		a.plan(1);

		const observable = Observable.of();
		return a.throws(observable);
	}).run().then(result => {
		t.is(result.passed, false);
		t.is(result.reason.name, 'AssertionError');
		t.end();
	});
});

test('handle throws with regex', t => {
	ava(a => {
		a.plan(1);

		const observable = new Observable(observer => {
			observer.error(new Error('abc'));
		});

		return a.throws(observable, /abc/);
	}).run().then(result => {
		t.is(result.passed, true);
		t.is(result.result.assertCount, 1);
		t.end();
	});
});

test('handle throws with string', t => {
	ava(a => {
		a.plan(1);

		const observable = new Observable(observer => {
			observer.error(new Error('abc'));
		});

		return a.throws(observable, 'abc');
	}).run().then(result => {
		t.is(result.passed, true);
		t.is(result.result.assertCount, 1);
		t.end();
	});
});

test('handle throws with false-positive observable', t => {
	ava(a => {
		a.plan(1);

		const observable = new Observable(observer => {
			observer.next(new Error());
			observer.complete();
		});

		return a.throws(observable);
	}).run().then(result => {
		t.is(result.passed, false);
		t.is(result.reason.name, 'AssertionError');
		t.end();
	});
});

test('handle notThrows with completed observable', t => {
	ava(a => {
		a.plan(1);

		const observable = Observable.of();
		return a.notThrows(observable);
	}).run().then(result => {
		t.is(result.passed, true);
		t.is(result.result.assertCount, 1);
		t.end();
	});
});

test('handle notThrows with thrown observable', t => {
	ava(a => {
		a.plan(1);

		const observable = new Observable(observer => {
			observer.error(new Error());
		});

		return a.notThrows(observable);
	}).run().then(result => {
		t.is(result.passed, false);
		t.is(result.reason.name, 'AssertionError');
		t.end();
	});
});


text:
"""
Copyright (c) 2014-2016 Miroslav Stampar (@stamparm)
See the file 'LICENSE' for copying permission
"""

from core.common import retrieve_content

__url__ = "https://zeustracker.abuse.ch/blocklist.php?download=compromised"
__check__ = "ZeuS"
__info__ = "zeus (malware)"
__reference__ = "abuse.ch"

def fetch():
    retval = {}
    content = retrieve_content(__url__)

    if __check__ in content:
        for line in content.split('\n'):
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            retval[line] = (__info__, __reference__)

    return retval


text:
set -e
MESSAGES=""

function updatePackages() {
  sudo apt update
}

function setupLAMP() {
  sudo systemctl status apache2 > /dev/null && exit
  sudo apt-get install -y lamp-server^
  sudo a2enmod rewrite headers
  sudo systemctl restart apache2
}

function allowZeroDatesInMySql() {
  grep "Allow 00-00-0000" /etc/mysql/mysql.conf.d/mysqld.cnf > /dev/null && return
  sudo tee -a /etc/mysql/mysql.conf.d/mysqld.cnf <<-ALLOW_ZEROS_IN_DATE

# Allow 00-00-0000 00:00:00 as a valid date!
# 18.04 or 18.10 sql_mode="ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
# 20.04 sql_mode="ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
sql_mode="ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
ALLOW_ZEROS_IN_DATE
  sudo systemctl restart mysql
}

function showFinishingMessages() {
  echo -e "\n\e[1;91m${MESSAGES}\e[0m"
}

function mysqlChangeRootAuth() {
  read -esp "Please enter new root mysql password: " rootpass
  echo
  sudo mysql -e "ALTER USER root@localhost IDENTIFIED WITH mysql_native_password BY '$rootpass'; FLUSH PRIVILEGES;"
}

function createVimAdventuresDB() {
  read -esp "Please enter root mysql password: " rootpass
  mysql -u root -p${rootpass} -e "CREATE DATABASE vim_adventures;"
  read -ep "Please enter vim_adventures mysql user: " mysqluser
  echo
  read -esp "Please enter vim_adventures mysql user password: " mysqluserpassword
  echo
  mysql -u root -p${rootpass} -e "CREATE USER '${mysqluser}'@'localhost' IDENTIFIED BY '${mysqluserpassword}'; GRANT ALL PRIVILEGES ON vim_adventures.* TO '${mysqluser}'@'localhost'; FLUSH PRIVILEGES;"
}

updatePackages
setupLAMP
allowZeroDatesInMySql
mysqlChangeRootAuth
createVimAdventuresDB
showFinishingMessages


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

namespace Database.Common
{
    /// <summary>
    /// A class that handles logging.
    /// </summary>
    public static class Logger
    {
        /// <summary>
        /// A queue of the log messages to be written.
        /// </summary>
        private static readonly Queue<Tuple<string, LogLevel, DateTime>> Messages = new Queue<Tuple<string, LogLevel, DateTime>>();

        /// <summary>
        /// A value indicating whether the logger is actually logging.
        /// </summary>
        private static bool _logging = true;

        /// <summary>
        /// The level at which messages will be logged.
        /// </summary>
        private static LogLevel _logLevel;

        /// <summary>
        /// The location to write the log file to.
        /// </summary>
        private static string _logLocation;

        /// <summary>
        /// The name of the log file minus the extension.
        /// </summary>
        private static string _logPrefix;

        /// <summary>
        /// The thread writing the messages to the log files.
        /// </summary>
        private static Thread _logThread;

        /// <summary>
        /// A value indicating whether to also log to the console.
        /// </summary>
        private static bool _logToConsole;

        /// <summary>
        /// A value indicating whether the logging system is running.
        /// </summary>
        private static bool _running = true;

        /// <summary>
        /// Disables the logging mechanism.
        /// </summary>
        public static void Disable()
        {
            lock (Messages)
            {
                Messages.Clear();
                _logging = false;
            }
        }

        /// <summary>
        /// Initializes the logging class.
        /// </summary>
        /// <param name="logLocation">The location to write the log file to.</param>
        /// <param name="logPrefix">The name of the log file minus the extension.</param>
        /// <param name="logLevel">The level at which messages will be logged.</param>
        /// <param name="logToConsole">Whether to also log to the console.</param>
        public static void Init(string logLocation, string logPrefix, LogLevel logLevel, bool logToConsole)
        {
            _logLocation = logLocation;
            _logPrefix = logPrefix;
            _logLevel = logLevel;
            _logToConsole = logToConsole;

            _logThread = new Thread(LogThreadRun);
            _logThread.Start();
        }

        /// <summary>
        /// Log a message.
        /// </summary>
        /// <param name="message">The message to log.</param>
        /// <param name="logLevel">The level at which messages will be logged.</param>
        public static void Log(string message, LogLevel logLevel)
        {
            lock (Messages)
            {
                if (_logging)
                {
                    Messages.Enqueue(new Tuple<string, LogLevel, DateTime>(message, logLevel, DateTime.UtcNow));
                }
            }
        }

        /// <summary>
        /// Shuts down the logging system.
        /// </summary>
        public static void Shutdown()
        {
            _running = false;
        }

        /// <summary>
        /// Flushes the messages to the log file.
        /// </summary>
        private static void FlushMessages()
        {
            StringBuilder text = new StringBuilder();
            lock (Messages)
            {
                while (Messages.Count > 0)
                {
                    var item = Messages.Dequeue();
                    if (item.Item2 <= _logLevel)
                    {
                        text.AppendFormat("[{0} {1} {2}] {3}\n", item.Item3.ToShortDateString(), item.Item3.ToLongTimeString(), Enum.GetName(typeof(LogLevel), item.Item2), item.Item1);
                    }
                }
            }

            File.AppendAllText(Path.Combine(_logLocation, _logPrefix + ".log"), text.ToString());

            if (_logToConsole)
            {
                Console.Write(text.ToString());
            }
        }

        /// <summary>
        /// The run function for the logging thread.
        /// </summary>
        private static void LogThreadRun()
        {
            while (_running)
            {
                FlushMessages();

                Thread.Sleep(100);
            }

            FlushMessages();
        }
    }
}


text:
package org.yetiz.service.rulengine.core.fact;

import org.yetiz.service.rulengine.core.Actional;
import org.yetiz.service.rulengine.core.Evaluatable;
import org.yetiz.service.rulengine.core.Intention;
import org.yetiz.service.rulengine.core.RuleEngineElement;
import org.yetiz.service.rulengine.core.condition.Condition;
import org.yetiz.service.rulengine.core.exception.ConditionJudgeFailedException;
import org.yetiz.service.rulengine.core.pattern.Pattern;

/**
 * Created by yeti on 2014/11/28.
 */
public abstract class Fact extends RuleEngineElement implements Evaluatable {
	private static final long serialVersionUID = -6147855662904682250L;
	protected Intention intention = null;
	private Condition condition = null;

	public Fact() {
		super();
	}

	/**
	 * Create a Fact instance, and set the name of this Fact.
	 *
	 * @param name the name of fact.
	 */
	public Fact(String name) {
		super(name);
	}

	public <R extends Fact> R setCondition(Condition condition) {
		this.condition = condition;
		return ((R) this);
	}

	/**
	 * Get the intention of this Fact.
	 * Attention!!! This method MUST only can be invoke after evaluate() is called.
	 *
	 * @return the intention of this Fact.
	 */
	public abstract Intention getIntention();

	public <R extends Fact> R preEvaluate(Pattern pattern) {
		return ((R) this);
	}

	/**
	 * evaluate the pattern and return callee.
	 * function evaluate will run those functions, preEvaluate,
	 * evaluating and postEvaluate.
	 * @param pattern the pattern be evaluated.
	 * @return the instance of callee.
	 */
	public Fact evaluate(Pattern pattern) {
		return
			preEvaluate(pattern).
				evaluating(pattern).
				postEvaluate(pattern);
	}

	public <R extends Fact> R evaluating(Pattern pattern) {
		if (condition != null)
			try {
				intention = condition.judge(pattern);
			} catch (Throwable t) {
				throw new ConditionJudgeFailedException(t.toString());
			}
		return ((R) this);
	}

	public <R extends Fact> R postEvaluate(Pattern pattern) {
		if (this instanceof Actional) {
			((Actional) this).doAction(pattern);
		}
		if (this instanceof FactTailal) {
			((FactTailal) this).doTail(pattern);
		}
		return ((R) this);
	}

}


text:
<?php

namespace Phlexible\Bundle\IndexerPageBundle\Tests\Indexer;

use Phlexible\Bundle\IndexerBundle\Document\DocumentIdentity;
use Phlexible\Bundle\IndexerPageBundle\Document\PageDocument;
use Phlexible\Bundle\IndexerPageBundle\Indexer\Mapper\BaseDocumentMapper;
use Phlexible\Bundle\IndexerPageBundle\Indexer\PageDocumentDescriptor;
use Phlexible\Bundle\SiterootBundle\Entity\Siteroot;
use Phlexible\Bundle\TreeBundle\ContentTree\ContentTreeNode;
use PHPUnit\Framework\TestCase;

/**
 * Base document mapper test.
 *
 * @author Stephan Wentz <sw@brainbits.net>
 *
 * @covers \Phlexible\Bundle\IndexerPageBundle\Indexer\Mapper\BaseDocumentMapper
 */
class BaseDocumentMapperTest extends TestCase
{
    public function testMapDocument()
    {
        $document = new PageDocument();
        $node = new ContentTreeNode();
        $node->setId(123);
        $node->setTypeId(234);
        $node->setInNavigation(true);
        $siteroot = new Siteroot(345);
        $identity = new PageDocumentDescriptor(new DocumentIdentity('abc'), $node, $siteroot, 'de');

        $applier = new BaseDocumentMapper();
        $applier->mapDocument($document, $identity);

        $this->assertSame($document->get('language'), 'de');
        $this->assertSame($document->get('node_id'), 123);
        $this->assertSame($document->get('type_id'), 234);
        $this->assertSame($document->get('siteroot_id'), 345);
        $this->assertSame($document->get('navigation'), true);
    }
}


text:
package com.perm.kate.api;

import java.io.Serializable;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Wiki page
 *
 */
public class Page implements Serializable{
    private static final long serialVersionUID = 1L;
    public long id;
    public long group_id;
    public String title;

    public static Page parseFromAttachment(JSONObject o) throws NumberFormatException, JSONException{
        Page page = new Page();
        page.title = Api.unescape(o.optString("title"));
        page.id = o.optLong("id");
        page.group_id = o.optLong("group_id");
        return page;
    }
}


text:
<?php

/**
 * Block for additional information in shipping method
 *
 * @category   Mage
 * @package    Mage_Checkout
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Checkout_Block_Onepage_Shipping_Method_Additional extends Mage_Checkout_Block_Onepage_Abstract
{

}


text:
describe RSpotify::Category do

  # Keys generated specifically for the tests. Should be removed in the future
  let(:client_id) { '5ac1cda2ad354aeaa1ad2693d33bb98c' }
  let(:client_secret) { '155fc038a85840679b55a1822ef36b9b' }

  before do
    authenticate_client
  end

  describe 'Category::find' do
    it 'should find right category' do
      category = VCR.use_cassette('category:find:party') do
        RSpotify::Category.find('party')
      end

      expect(category.href)               .to eq 'https://api.spotify.com/v1/browse/categories/party'
      expect(category.icons.first['url']) .to eq 'https://datsnxq1rwndn.cloudfront.net/media/derived/party-274x274_73d1907a7371c3bb96a288390a96ee27_0_0_274_274.jpg'
      expect(category.id)                 .to eq 'party'
      expect(category.name)               .to eq 'Party'
    end

    it 'should find right category with additional attributes' do
      category = VCR.use_cassette('category:find:party:country:BR') do
        RSpotify::Category.find('party', country: 'BR')
      end
      expect(category.href)               .to eq 'https://api.spotify.com/v1/browse/categories/party'
      expect(category.name)               .to eq 'Party'

      category = VCR.use_cassette('category:find:party:locale:es_MX') do
        RSpotify::Category.find('party', locale: 'es_MX')
      end
      expect(category.href)               .to eq 'https://api.spotify.com/v1/browse/categories/party'
      expect(category.name)               .to eq 'Party'
    end
  end

  describe 'Category::list' do
    it 'should get the right categories' do
      categories = VCR.use_cassette('category:list') do
        RSpotify::Category.list
      end

      expect(categories.size)        .to eq 20
      expect(categories.map(&:name)) .to include('Top Lists', 'Country', 'Decades')
    end

    it 'should get the right categories with additional attributes' do
      categories = VCR.use_cassette('category:list:locale:es_MX:limit:10') do
        RSpotify::Category.list(locale: 'es_MX', limit: 10)
      end
      expect(categories.size)        .to eq 10
      expect(categories.map(&:name)) .to include('Dance', 'Pop', 'Chill')

      categories = VCR.use_cassette('category:list:country:BR') do
        RSpotify::Category.list(country: 'BR')
      end
      expect(categories.map(&:name)) .to include('Top Lists', 'Pop', 'Chill')
    end
  end

  describe 'Category#complete!' do
    let(:category) do
      RSpotify::Category.new({'id' => 'party'})
    end

    it 'should fetch the complete information correctly' do
      VCR.use_cassette('category:find:party') do
        category.complete!
      end
      expect(category.href)               .to eq 'https://api.spotify.com/v1/browse/categories/party'
      expect(category.icons.first['url']) .to eq 'https://datsnxq1rwndn.cloudfront.net/media/derived/party-274x274_73d1907a7371c3bb96a288390a96ee27_0_0_274_274.jpg'
      expect(category.name)               .to eq 'Party'
    end
  end

  describe 'Category#playlists' do
    let(:category) do
      # Get party category as a testing sample
      VCR.use_cassette('category:find:party') do
        RSpotify::Category.find('party')
      end
    end

    it 'should get correct playlists' do
      playlists = VCR.use_cassette('category:party:playlists') do
        category.playlists
      end

      expect(playlists)             .to be_an Array
      expect(playlists.size)        .to eq 20
      expect(playlists.first)       .to be_an RSpotify::Playlist
      expect(playlists.map(&:name)) .to include('Teen Party', 'Weekend Hangouts', 'Dance Party')
    end

    it 'should get correct playlists with additional options' do
      playlists = VCR.use_cassette('category:party:playlists:limit:10:offset:20') do
        category.playlists(limit: 10, offset: 20)
      end
      expect(playlists.size)        .to eq 10
      expect(playlists.map(&:name)) .to include('Indie Brunch', 'Hipster Funk', 'Party Hits')

      playlists = VCR.use_cassette('category:party:playlists:country:BR') do
        category.playlists(country: 'BR')
      end
      expect(playlists.map(&:name)) .to include('Lista VIP', 'Sexta', 'Modo Freestyle')
    end
  end
end


text:
from lwm2mthon.defines import LWM2MResourceType

__author__ = 'jacko'

RESOURCE_TLV = 0
RESOURCE_INSTANCE_TLV = 1
MULTIPLE_RESOURCE_TLV = 2
OBJECT_INSTANCE = 4

class TLV(object):
    def __init__(self, tlv_type, children, value, identifier, resource_type):
        self.tlv_type = tlv_type
        self.children = children
        self.value = None
        self.length = None
        if resource_type == LWM2MResourceType.STRING and value is not None:
            self.value = str(value)
            self.length = len(str(value))
        elif (resource_type == LWM2MResourceType.INTEGER or resource_type == LWM2MResourceType.BOOLEAN) \
                and value is not None:
            self.value = int(value)
            if -128 <= self.value <= 127:
                self.length = 1
            elif -32768 <= self.value <= 32767:
                self.length = 2
            elif -2147484648 <= self.value < 2147484647:
                self.length = 4
            else:
                self.length = 8
        self.identifier = int(identifier)
        self.resource_type = resource_type

    def encode(self):
        values = []
        fmt = "!"
        if self.tlv_type == RESOURCE_TLV:
            tmp = 0b11000000
            length = self.length
        elif self.tlv_type == MULTIPLE_RESOURCE_TLV:
            tmp = 0b10000000
            length = self.length
        elif self.tlv_type == RESOURCE_INSTANCE_TLV:
            tmp = 0b01000000
            length = self.length
        else:
            raise NotImplementedError
        if self.identifier >= 256:
            # identifier length on 16 bits
            tmp |= 0b00100000

        if length < 8:
            tmp |= length
        elif length < 256:
            tmp |= 0b00001000
        elif length < 65536:
            tmp |= 0b00010000
        else:
            tmp |= 0b00011000

        fmt += "B"
        values.append(tmp)
        values.append(int(self.identifier))
        if self.identifier < 256:
            fmt += "B"
        else:
            fmt += "H"

        if length >= 8:
            if length < 256:
                values.append(length)
                fmt += "B"
            elif length < 65536:
                values.append(length)
                fmt += "H"
            else:
                msb = (length & 0xFF0000) >> 16
                values.append(msb)
                fmt += "B"
                values.append(length & 0x00FFFF)
                fmt += "H"

        if self.tlv_type == RESOURCE_TLV or self.tlv_type == RESOURCE_INSTANCE_TLV:
            if self.resource_type == LWM2MResourceType.STRING:
                for b in str(self.value):
                    fmt += "c"
                    values.append(b)
            elif self.resource_type == LWM2MResourceType.INTEGER or self.resource_type == LWM2MResourceType.BOOLEAN:
                if self.length == 1:
                    values.append(self.value)
                    fmt += "B"
                elif self.length == 2:
                    values.append(self.value)
                    fmt += "H"
                elif self.length == 4:
                    msb = (self.value & 0xFFFF0000) >> 16
                    values.append(msb)
                    fmt += "H"
                    values.append(self.value & 0x0000FFFF)
                    fmt += "H"
                elif self.length == 8:
                    msb = (self.value & 0xFFFF000000000000) >> 48
                    values.append(msb)
                    fmt += "H"
                    lsb = (self.value & 0x0000FFFF00000000) >> 32
                    values.append(lsb)
                    fmt += "H"

                    msb = (self.value & 0xFFFF0000FFFF0000) >> 16
                    values.append(msb)
                    fmt += "H"
                    lsb = (self.value & 0x000000000000FFFF)
                    values.append(lsb)
                    fmt += "H"
        elif self.tlv_type == MULTIPLE_RESOURCE_TLV:
            pass
        else:
            raise NotImplementedError

        return fmt, values


text:
<?php

namespace REBELinBLUE\Deployer\Repositories\Contracts;

interface ChannelRepositoryInterface
{
    /**
     * @param array $fields
     *
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function create(array $fields);

    /**
     * @param array $fields
     * @param int   $model_id
     *
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function updateById(array $fields, $model_id);

    /**
     * @param int $model_id
     *
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     * @return bool
     */
    public function deleteById($model_id);
}


text:
"""
PDBProp
=======
"""

import gzip
import json
import logging
import os.path as op
import mmtf
import os
from cobra.core import DictList
import pandas as pd
import requests
import deprecation
from Bio.PDB import PDBList
from lxml import etree
from six.moves.urllib_error import URLError
from six.moves.urllib.request import urlopen, urlretrieve

import ssbio.databases.pisa as pisa
import ssbio.utils
from ssbio.protein.structure.structprop import StructProp

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

log = logging.getLogger(__name__)

class PDBProp(StructProp):

    """Store information about a protein structure from the Protein Data Bank.

    Extends the :class:`~ssbio.protein.structure.structprop.StructProp` class to allow initialization of the structure
    by its PDB ID, and then enabling downloads of the structure file as well as parsing its metadata.

    Args:
        ident (str):
        description (str):
        chains (str):
        mapped_chains (str):
        structure_path (str):
        file_type (str): ``pdb``, ``mmCif``, ``xml``, ``mmtf`` - file type for files downloaded from the PDB

    """

    def __init__(self, ident, description=None, chains=None, mapped_chains=None, structure_path=None, file_type=None):
        StructProp.__init__(self, ident, description=description, chains=chains, mapped_chains=mapped_chains,
                            is_experimental=True, structure_path=structure_path, file_type=file_type)
        self.experimental_method = None
        self.resolution = None
        self.date = None
        self.taxonomy_name = None
        self.biological_assemblies = DictList()
        """DictList: A list for storing Bioassembly objects related to this PDB ID"""

    def download_structure_file(self, outdir, file_type=None, load_header_metadata=True, force_rerun=False):
        """Download a structure file from the PDB, specifying an output directory and a file type. Optionally download
        the mmCIF header file and parse data from it to store within this object.

        Args:
            outdir (str): Path to output directory
            file_type (str): ``pdb``, ``mmCif``, ``xml``, ``mmtf`` - file type for files downloaded from the PDB
            load_header_metadata (bool): If header metadata should be loaded into this object, fastest with mmtf files
            force_rerun (bool): If structure file should be downloaded even if it already exists

        """
        ssbio.utils.double_check_attribute(object=self, setter=file_type, backup_attribute='file_type',
                                           custom_error_text='Please set file type to be downloaded from the PDB: '
                                                             'pdb, mmCif, xml, or mmtf')

        # XTODO: check if outfile exists using ssbio.utils.force_rerun, pdblist seems to take long if it exists
        # I know why - it's because we're renaming the ent to pdb. need to have mapping from file type to final extension
        # Then check if file exists, if not then download again
        p = PDBList()
        with ssbio.utils.suppress_stdout():
            structure_file = p.retrieve_pdb_file(pdb_code=self.id, pdir=outdir, file_format=file_type, overwrite=force_rerun)
        if not op.exists(structure_file):
            log.debug('{}: {} file not available'.format(self.id, file_type))
            raise URLError('{}.{}: file not available to download'.format(self.id, file_type))
        else:
            log.debug('{}: {} file saved'.format(self.id, file_type))

            # Rename .ent files to .pdb
            if file_type == 'pdb':
                new_name = structure_file.replace('pdb', '').replace('ent', 'pdb')
                os.rename(structure_file, new_name)
                structure_file = new_name

            self.load_structure_path(structure_file, file_type)
            if load_header_metadata and file_type == 'mmtf':
                self.update(parse_mmtf_header(structure_file))
            if load_header_metadata and file_type != 'mmtf':
                self.update(parse_mmcif_header(download_mmcif_header(pdb_id=self.id, outdir=outdir, force_rerun=force_rerun)))

    def get_pisa_complex_predictions(self, outdir, existing_pisa_multimer_xml=None):
        if not existing_pisa_multimer_xml:
            pisa_xmls = pisa.download_pisa_multimers_xml(pdb_ids=self.id, outdir=outdir,
                                                         save_single_xml_files=True)
        else:
            pisa_xmls = {}
            pisa_xmls[self.id] = existing_pisa_multimer_xml
        pisa_dict = pisa.parse_pisa_multimers_xml(pisa_xmls[self.id], download_structures=True,
                                                  outdir=outdir)

    def __json_encode__(self):
        # TODO: investigate why saving with # does not work!
        to_return = {}
        for x in self.__dict__.keys():
            if x == 'pdb_title' or x == 'description':
                sanitized = ssbio.utils.force_string(getattr(self, x)).replace('#', '-')
            else:
                to_return.update({x: getattr(self, x)})
        return to_return

def parse_mmtf_header(infile):
    """Parse an MMTF file and return basic header-like information.

    Args:
        infile (str): Path to MMTF file

    Returns:
        dict: Dictionary of parsed header

    Todo:
        - Can this be sped up by not parsing the 3D coordinate info somehow?
        - OR just store the sequences when this happens since it is already being parsed.

    """
    infodict = {}

    mmtf_decoder = mmtf.parse(infile)
    infodict['date'] = mmtf_decoder.deposition_date
    infodict['release_date'] = mmtf_decoder.release_date
    try:
        infodict['experimental_method'] = [x.decode() for x in mmtf_decoder.experimental_methods]
    except AttributeError:
        infodict['experimental_method'] = [x for x in mmtf_decoder.experimental_methods]
    infodict['resolution'] = mmtf_decoder.resolution
    infodict['description'] = mmtf_decoder.title

    group_name_exclude = ['HOH']
    chem_comp_type_exclude = ['l-peptide linking', 'peptide linking']
    chemicals = list(set([mmtf_decoder.group_list[idx]['groupName'] for idx in mmtf_decoder.group_type_list if mmtf_decoder.group_list[idx]['chemCompType'].lower() not in chem_comp_type_exclude and mmtf_decoder.group_list[idx]['groupName'] not in group_name_exclude]))
    infodict['chemicals'] = chemicals
    return infodict

def download_mmcif_header(pdb_id, outdir='', force_rerun=False):
    """Download a mmCIF header file from the RCSB PDB by ID.

    Args:
        pdb_id: PDB ID
        outdir: Optional output directory, default is current working directory
        force_rerun: If the file should be downloaded again even if it exists

    Returns:
        str: Path to outfile

    """
    # TODO: keep an eye on https://github.com/biopython/biopython/pull/943 Biopython PR#493 for functionality of this
    # method in biopython. extra file types have not been added to biopython download yet

    pdb_id = pdb_id.lower()
    file_type = 'cif'
    folder = 'header'
    outfile = op.join(outdir, '{}.header.{}'.format(pdb_id, file_type))

    if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
        download_link = 'http://files.rcsb.org/{}/{}.{}'.format(folder, pdb_id, file_type)
        urlretrieve(download_link, outfile)
        log.debug('{}: saved header file'.format(outfile))
    else:
        log.debug('{}: header file already saved'.format(outfile))

    return outfile

def parse_mmcif_header(infile):
    """Parse a couple important fields from the mmCIF file format with some manual curation of ligands.

    If you want full access to the mmCIF file just use the MMCIF2Dict class in Biopython.

    Args:
        infile: Path to mmCIF file

    Returns:
        dict: Dictionary of parsed header

    """
    from Bio.PDB.MMCIF2Dict import MMCIF2Dict

    newdict = {}
    try:
        mmdict = MMCIF2Dict(infile)
    except ValueError as e:
        log.exception(e)
        return newdict

    chemical_ids_exclude = ['HOH']
    chemical_types_exclude = ['l-peptide linking','peptide linking']

    if '_struct.title' in mmdict:
        newdict['pdb_title'] = mmdict['_struct.title']
    else:
        log.debug('{}: No title field'.format(infile))

    if '_struct.pdbx_descriptor' in mmdict:
        newdict['description'] = mmdict['_struct.pdbx_descriptor']
    else:
        log.debug('{}: no description field'.format(infile))

    if '_pdbx_database_status.recvd_initial_deposition_date' in mmdict:
        newdict['date'] = mmdict['_pdbx_database_status.recvd_initial_deposition_date']
    elif '_database_PDB_rev.date' in mmdict:
        newdict['date'] = mmdict['_database_PDB_rev.date']
    else:
        log.debug('{}: no date field'.format(infile))

    if '_exptl.method' in mmdict:
        newdict['experimental_method'] = mmdict['_exptl.method']
    else:
        log.debug('{}: no experimental method field'.format(infile))

    # TODO: refactor how to get resolutions based on experimental method
    if '_refine.ls_d_res_high' in mmdict:
        try:
            if isinstance(mmdict['_refine.ls_d_res_high'], list):
                newdict['resolution'] = [float(x) for x in mmdict['_refine.ls_d_res_high']]
            else:
                newdict['resolution'] = float(mmdict['_refine.ls_d_res_high'])
        except:
            try:
                newdict['resolution'] = float(mmdict['_em_3d_reconstruction.resolution'])
            except:
                log.debug('{}: no resolution field'.format(infile))
    else:
        log.debug('{}: no resolution field'.format(infile))

    if '_chem_comp.id' in mmdict:
        chemicals_filtered = ssbio.utils.filter_list_by_indices(mmdict['_chem_comp.id'],
                                                            ssbio.utils.not_find(mmdict['_chem_comp.type'],
                                                                           chemical_types_exclude,
                                                                           case_sensitive=False))
        chemicals_fitered = ssbio.utils.filter_list(chemicals_filtered, chemical_ids_exclude, case_sensitive=True)
        newdict['chemicals'] = chemicals_fitered
    else:
        log.debug('{}: no chemical composition field'.format(infile))

    if '_entity_src_gen.pdbx_gene_src_scientific_name' in mmdict:
        newdict['taxonomy_name'] = mmdict['_entity_src_gen.pdbx_gene_src_scientific_name']
    else:
        log.debug('{}: no organism field'.format(infile))

    return newdict

def download_sifts_xml(pdb_id, outdir='', force_rerun=False):
    """Download the SIFTS file for a PDB ID.

    Args:
        pdb_id (str): PDB ID
        outdir (str): Output directory, current working directory if not specified.
        force_rerun (bool): If the file should be downloaded again even if it exists

    Returns:
        str: Path to downloaded file

    """
    baseURL = 'ftp://ftp.ebi.ac.uk/pub/databases/msd/sifts/xml/'
    filename = '{}.xml.gz'.format(pdb_id.lower())

    outfile = op.join(outdir, filename.split('.')[0] + '.sifts.xml')

    if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
        response = urlopen(baseURL + filename)
        with open(outfile, 'wb') as f:
            f.write(gzip.decompress(response.read()))

    return outfile

def map_uniprot_resnum_to_pdb(uniprot_resnum, chain_id, sifts_file):
    """Map a UniProt residue number to its corresponding PDB residue number.

    This function requires that the SIFTS file be downloaded,
    and also a chain ID (as different chains may have different mappings).

    Args:
        uniprot_resnum (int): integer of the residue number you'd like to map
        chain_id (str): string of the PDB chain to map to
        sifts_file (str): Path to the SIFTS XML file

    Returns:
        (tuple): tuple containing:

            mapped_resnum (int): Mapped residue number
            is_observed (bool): Indicates if the 3D structure actually shows the residue

    """
    # Load the xml with lxml
    parser = etree.XMLParser(ns_clean=True)
    tree = etree.parse(sifts_file, parser)
    root = tree.getroot()

    my_pdb_resnum = None

    # TODO: "Engineered_Mutation is also a possible annotation, need to figure out what to do with that
    my_pdb_annotation = False

    # Find the right chain (entities in the xml doc)
    ent = './/{http://www.ebi.ac.uk/pdbe/docs/sifts/eFamily.xsd}entity'
    for chain in root.findall(ent):
        # TODO: IMPORTANT - entityId is not the chain ID!!! it is just in alphabetical order!
        if chain.attrib['entityId'] == chain_id:
            # Find the "crossRefDb" tag that has the attributes dbSource="UniProt" and  dbResNum="your_resnum_here"
            # Then match it to the crossRefDb dbResNum that has the attribute dbSource="PDBresnum"

            # Check if uniprot + resnum even exists in the sifts file (it won't if the pdb doesn't contain the residue)
            ures = './/{http://www.ebi.ac.uk/pdbe/docs/sifts/eFamily.xsd}crossRefDb[@dbSource="UniProt"][@dbResNum="%s"]' % uniprot_resnum
            my_uniprot_residue = chain.findall(ures)
            if len(my_uniprot_residue) == 1:
                # Get crossRefDb dbSource="PDB"
                parent = my_uniprot_residue[0].getparent()
                pres = './/{http://www.ebi.ac.uk/pdbe/docs/sifts/eFamily.xsd}crossRefDb[@dbSource="PDB"]'
                my_pdb_residue = parent.findall(pres)
                my_pdb_resnum = int(my_pdb_residue[0].attrib['dbResNum'])

                # Get <residueDetail dbSource="PDBe" property="Annotation">
                # Will be Not_Observed if it is not seen in the PDB
                anno = './/{http://www.ebi.ac.uk/pdbe/docs/sifts/eFamily.xsd}residueDetail[@dbSource="PDBe"][@property="Annotation"]'
                my_pdb_annotation = parent.findall(anno)
                if len(my_pdb_annotation) == 1:
                    my_pdb_annotation = my_pdb_annotation[0].text
                    if my_pdb_annotation == 'Not_Observed':
                        my_pdb_annotation = False
                else:
                    my_pdb_annotation = True
            else:
                return None, False

    return my_pdb_resnum, my_pdb_annotation

def best_structures(uniprot_id, outname=None, outdir=None, seq_ident_cutoff=0.0, force_rerun=False):
    """Use the PDBe REST service to query for the best PDB structures for a UniProt ID.

    More information found here: https://www.ebi.ac.uk/pdbe/api/doc/sifts.html
    Link used to retrieve results: https://www.ebi.ac.uk/pdbe/api/mappings/best_structures/:accession
    The list of PDB structures mapping to a UniProt accession sorted by coverage of the protein and, if the same, resolution.

    Here is the ranking algorithm described by the PDB paper:
    https://nar.oxfordjournals.org/content/44/D1/D385.full

    "Finally, a single quality indicator is also calculated for each entry by taking the harmonic average
    of all the percentile scores representing model and model-data-fit quality measures and then subtracting
    10 times the numerical value of the resolution (in Angstrom) of the entry to ensure that resolution plays
    a role in characterising the quality of a structure. This single empirical 'quality measure' value is used
    by the PDBe query system to sort results and identify the 'best' structure in a given context. At present,
    entries determined by methods other than X-ray crystallography do not have similar data quality information
    available and are not considered as 'best structures'."

    Args:
        uniprot_id (str): UniProt Accession ID
        outname (str): Basename of the output file of JSON results
        outdir (str): Path to output directory of JSON results
        seq_ident_cutoff (float): Cutoff results based on percent coverage (in decimal form)
        force_rerun (bool): Obtain best structures mapping ignoring previously downloaded results

    Returns:
        list: Rank-ordered list of dictionaries representing chain-specific PDB entries. Keys are:
            * pdb_id: the PDB ID which maps to the UniProt ID
            * chain_id: the specific chain of the PDB which maps to the UniProt ID
            * coverage: the percent coverage of the entire UniProt sequence
            * resolution: the resolution of the structure
            * start: the structure residue number which maps to the start of the mapped sequence
            * end: the structure residue number which maps to the end of the mapped sequence
            * unp_start: the sequence residue number which maps to the structure start
            * unp_end: the sequence residue number which maps to the structure end
            * experimental_method: type of experiment used to determine structure
            * tax_id: taxonomic ID of the protein's original organism

    """
    outfile = ''

    if not outdir:
        outdir = ''

    # if output dir is specified but not outname, use the uniprot
    if not outname and outdir:
        outname = uniprot_id

    if outname:
        outname = op.join(outdir, outname)
        outfile = '{}.json'.format(outname)

    # Load a possibly existing json file
    if not ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
        with open(outfile, 'r') as f:
            raw_data = json.load(f)
        log.debug('{}: loaded existing json file'.format(uniprot_id))

    # Otherwise run the web request
    else:
        # TODO: add a checker for a cached file of uniprot -> PDBs - can be generated within gempro pipeline and stored
        response = requests.get('https://www.ebi.ac.uk/pdbe/api/mappings/best_structures/{}'.format(uniprot_id),
                                data={'key': 'value'})
        if response.status_code == 404:
            log.debug('{}: 404 returned, probably no structures available.'.format(uniprot_id))
            raw_data = {uniprot_id: {}}
        else:
            log.debug('{}: Obtained best structures'.format(uniprot_id))
            raw_data = response.json()

        # Write the json file if specified
        if outfile:
            with open(outfile, 'w') as f:
                json.dump(raw_data, f)
            log.debug('{}: Saved json file of best structures'.format(uniprot_id))

    data = dict(raw_data)[uniprot_id]

    # Filter for sequence identity percentage
    if seq_ident_cutoff != 0:
        for result in data:
            if result['coverage'] < seq_ident_cutoff:
                data.remove(result)

    return data

def blast_pdb_df(blast_results):
    """Make a dataframe of BLAST results"""
    cols = ['hit_pdb', 'hit_pdb_chains', 'hit_evalue', 'hit_score', 'hit_num_ident', 'hit_percent_ident',
            'hit_num_similar', 'hit_percent_similar', 'hit_num_gaps', 'hit_percent_gaps']
    return pd.DataFrame.from_records(blast_results, columns=cols)

def _property_table():
    """Download the PDB -> resolution table directly from the RCSB PDB REST service.

    See the other fields that you can get here: http://www.rcsb.org/pdb/results/reportField.do

    Returns:
        Pandas DataFrame: table of structureId as the index, resolution and experimentalTechnique as the columns

    """
    url = 'http://www.rcsb.org/pdb/rest/customReport.csv?pdbids=*&customReportColumns=structureId,resolution,experimentalTechnique,releaseDate&service=wsfile&format=csv'
    r = requests.get(url)
    p = pd.read_csv(StringIO(r.text)).set_index('structureId')
    return p

def get_resolution(pdb_id):
    """Quick way to get the resolution of a PDB ID using the table of results from the REST service

    Returns infinity if the resolution is not available.

    Returns:
        float: resolution of a PDB ID in Angstroms

    TODO:
        - Unit test

    """

    pdb_id = pdb_id.upper()
    if pdb_id not in _property_table().index:
        raise ValueError('PDB ID not in property table')
    else:
        resolution = _property_table().ix[pdb_id, 'resolution']
        if pd.isnull(resolution):
            log.debug('{}: no resolution available, probably not an X-ray crystal structure')
            resolution = float('inf')

    return resolution

def get_release_date(pdb_id):
    """Quick way to get the release date of a PDB ID using the table of results from the REST service

    Returns None if the release date is not available.

    Returns:
        str: Organism of a PDB ID

    """

    pdb_id = pdb_id.upper()
    if pdb_id not in _property_table().index:
        raise ValueError('PDB ID not in property table')
    else:
        release_date = _property_table().ix[pdb_id, 'releaseDate']
        if pd.isnull(release_date):
            log.debug('{}: no release date available')
            release_date = None

    return release_date

def get_num_bioassemblies(pdb_id, cache=False, outdir=None, force_rerun=False):
    """Check if there are bioassemblies using the PDB REST API, and if there are, get the number of bioassemblies
    available.

    See: https://www.rcsb.org/pages/webservices/rest, section 'List biological assemblies'

    Not all PDB entries have biological assemblies available and some have multiple. Details that are necessary to
    recreate a biological assembly from the asymmetric unit can be accessed from the following requests.

    - Number of biological assemblies associated with a PDB entry
    - Access the transformation information needed to generate a biological assembly (nr=0 will return information
      for the asymmetric unit, nr=1 will return information for the first assembly, etc.)

    A query of https://www.rcsb.org/pdb/rest/bioassembly/nrbioassemblies?structureId=1hv4 returns this::

        <nrBioAssemblies structureId="1HV4" hasAssemblies="true" count="2"/>

    Args:
        pdb_id (str): PDB ID
        cache (bool): If the XML file should be downloaded
        outdir (str): If cache, then specify the output directory
        force_rerun (bool): If cache, and if file exists, specify if API should be queried again

    """
    parser = etree.XMLParser(ns_clean=True)

    if not outdir:
        outdir = os.getcwd()
    outfile = op.join(outdir, '{}_nrbiomols.xml'.format(pdb_id))

    if ssbio.utils.force_rerun(force_rerun, outfile):
        page = 'https://www.rcsb.org/pdb/rest/bioassembly/nrbioassemblies?structureId={}'.format(pdb_id)
        req = requests.get(page)

        if req.status_code == 200:
            response = req.text

            # Save the XML file
            if cache:
                with open(outfile, 'w') as f:
                    f.write(response)

            # Parse the XML string
            tree = etree.ElementTree(etree.fromstring(response, parser))
            log.debug('Loaded bioassembly information from REST server')
        else:
            log.error('Request timed out')
            req.raise_for_status()
    else:
        tree = etree.parse(outfile, parser)
        log.debug('{}: Loaded existing XML results'.format(outfile))

    r = tree.getroot()
    has_biomols = r.get('hasAssemblies')
    if has_biomols == 'true':
        has_biomols = True
    else:
        has_biomols = False

    if has_biomols:
        num_biomols = r.get('count')
    else:
        num_biomols = 0

    num_biomols = int(num_biomols)
    return num_biomols

def get_bioassembly_info(pdb_id, biomol_num, cache=False, outdir=None, force_rerun=False):
    """Get metadata about a bioassembly from the RCSB PDB's REST API.

    See: https://www.rcsb.org/pdb/rest/bioassembly/bioassembly?structureId=1hv4&nr=1
    The API returns an XML file containing the information on a biological assembly that looks like this::

        <bioassembly structureId="1HV4" assemblyNr="1" method="PISA" desc="author_and_software_defined_assembly">
            <transformations operator="1" chainIds="A,B,C,D">
                <transformation index="1">
                    <matrix m11="1.00000000" m12="0.00000000" m13="0.00000000" m21="0.00000000" m22="1.00000000" m23="0.00000000" m31="0.00000000" m32="0.00000000" m33="1.00000000"/>
                    <shift v1="0.00000000" v2="0.00000000" v3="0.00000000"/>
                </transformation>
            </transformations>
        </bioassembly>

    Args:
        pdb_id (str): PDB ID
        biomol_num (int): Biological assembly number you are interested in
        cache (bool): If the XML file should be downloaded
        outdir (str): If cache, then specify the output directory
        force_rerun (bool): If cache, and if file exists, specify if API should be queried again

    """
    parser = etree.XMLParser(ns_clean=True)
    #
    # if not outdir:
    #     outdir = os.getcwd()
    # outfile = op.join(outdir, '{}.xml'.format(self.id))
    #
    # if ssbio.utils.force_rerun(force_rerun, outfile):
    #     page = 'https://www.rcsb.org/pdb/rest/bioassembly/bioassembly?structureId={}&nr={}'.format(
    #         self.original_pdb_id, biomol_num)
    #     req = requests.get(page)
    #
    #     if req.status_code == 200:
    #         response = req.text
    #
    #         # Save the XML file
    #         if cache:
    #             with open(outfile, 'w') as f:
    #                 f.write(response)
    #
    #         # Parse the XML string
    #         r = xmltodict.parse(response)
    #         log.debug('Loaded bioassembly information from REST server')
    #     else:
    #         log.error('Request timed out')
    #         req.raise_for_status()
    # else:
    #     with open(outfile, 'r') as f:
    #         r = xmltodict.parse(f.read())
    #     log.debug('{}: Loaded existing XML results'.format(outfile))
    #
    # self.biomol_to_chain_dict[biomol_num] = {'chains': r['bioassembly']['transformations']['@chainIds'],
    #                                          'multiplier': len(r['bioassembly']['transformations']['transformation'])}
    # # TODO: figure out how to store matrices etc.
    #
    # log.info('{}_{}: ')

def download_biomol(pdb_id, biomol_num, outdir, file_type='pdb', force_rerun=False):
    import zlib
    from six.moves.urllib_error import URLError
    from six.moves.urllib.request import urlopen
    import contextlib

    ssbio.utils.make_dir(outdir)
    server_folder = pdb_id[1:3]

    if file_type == 'pdb':
        # server = 'ftp://ftp.wwpdb.org/pub/pdb/data/biounit/coordinates/divided/{}/'.format(server_folder)
        server = 'https://files.rcsb.org/download/'
        server_filename = pdb_id + '.pdb%i.gz' % biomol_num
        local_filename = pdb_id + '_bio%i.pdb' % biomol_num
        outfile = op.join(outdir, local_filename)

    elif file_type.lower() == 'mmcif' or file_type.lower() == 'cif':
        server = 'ftp://ftp.wwpdb.org/pub/pdb/data/biounit/mmCIF/divided/{}/'.format(server_folder)
        server_filename = pdb_id + '-assembly%i.cif.gz' % biomol_num
        local_filename = pdb_id + '_bio%i.cif' % biomol_num
        outfile = op.join(outdir, local_filename)

    else:
        raise ValueError('Biological assembly only available in PDB or mmCIF file types.')

    if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
        download_link = op.join(server, server_filename)
        try:
            with contextlib.closing(urlopen(download_link)) as f:
                decompressed_data = zlib.decompress(f.read(), 16 + zlib.MAX_WBITS)
                with open(op.join(outdir, local_filename), 'wb') as f:
                    f.write(decompressed_data)
        except URLError as e:
            print(e)
            return None

    return outfile

########################################################################################################################
########################################################################################################################
# DEPRECATED FUNCTIONS
########################################################################################################################
########################################################################################################################

@deprecation.deprecated(deprecated_in="1.0", removed_in="2.0",
                        details="Use Biopython's PDBList.retrieve_pdb_file function instead")
def download_structure(pdb_id, file_type, outdir='', only_header=False, force_rerun=False):
    """Download a structure from the RCSB PDB by ID. Specify the file type desired.

    Args:
        pdb_id: PDB ID
        file_type: pdb, pdb.gz, mmcif, cif, cif.gz, xml.gz, mmtf, mmtf.gz
        outdir: Optional output directory
        only_header: If only the header file should be downloaded
        force_rerun: If the file should be downloaded again even if it exists

    Returns:
        str: Path to outfile

    """
    # method in biopython. extra file types have not been added to biopython download yet

    pdb_id = pdb_id.lower()
    file_type = file_type.lower()
    file_types = ['pdb', 'pdb.gz', 'mmcif', 'cif', 'cif.gz', 'xml.gz', 'mmtf', 'mmtf.gz']
    if file_type not in file_types:
        raise ValueError('Invalid file type, must be either: pdb, pdb.gz, cif, cif.gz, xml.gz, mmtf, mmtf.gz')

    if file_type == 'mmtf':
        file_type = 'mmtf.gz'

    if file_type.endswith('.gz'):
        gzipped = True
    else:
        gzipped = False

    if file_type == 'mmcif':
        file_type = 'cif'

    if only_header:
        folder = 'header'
        outfile = op.join(outdir, '{}.header.{}'.format(pdb_id, file_type))
    else:
        folder = 'download'
        outfile = op.join(outdir, '{}.{}'.format(pdb_id, file_type))

    if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
        if file_type == 'mmtf.gz' or file_type == 'mmtf':
            mmtf_api = '1.0'
            download_link = 'http://mmtf.rcsb.org/v{}/full/{}.mmtf.gz'.format(mmtf_api, pdb_id)
        else:
            download_link = 'http://files.rcsb.org/{}/{}.{}'.format(folder, pdb_id, file_type)

        urlretrieve(download_link, outfile)

        if gzipped:
            outfile = ssbio.utils.gunzip_file(infile=outfile,
                                              outfile=outfile.strip('.gz'),
                                              outdir=outdir,
                                              delete_original=False,
                                              force_rerun_flag=force_rerun)

        log.debug('{}: saved structure file'.format(outfile))
    else:
        if file_type == 'mmtf.gz':
            outfile = op.join(outdir, '{}.{}'.format(pdb_id, 'mmtf'))
        log.debug('{}: structure file already saved'.format(outfile))

    return outfile


text:
class RequestTracker {
  // Dispatches API handlers and serves static assets.
  static middleware(request, response, next) {
    var handler = RequestTracker.API[request.url] || RequestTracker.default;
    handler(request, response, next);
  }

  // Handles requests for URLs that are not part of the API.
  static default(request, response, next) {
    // Store the request details.
    RequestTracker.requests.push({
      method: request.method,
      url: request.url
    });
    // Tell the browser to cache the assets.
    response.setHeader('cache-control', 'public, max-age=315360000');
    // Serve the
    next();
  }

  // Register a middleware handler that runs when it's URL is requested.
  static register(url, handler) {
    RequestTracker.API[url] = handler;
  }
}

// The list of requests.
RequestTracker.requests = [];

// The request handlers keyed by URL.
RequestTracker.API = {};

// Get the list of requests as JSON.
RequestTracker.register('/requests', (request, response) => {
  response.setHeader('content-type', 'text/json');
  response.end(JSON.stringify(RequestTracker.requests));
});

// Clear the list of requests.
RequestTracker.register('/reset', (request, response) => {
  RequestTracker.requests = [];
  response.end('OK');
});

module.exports = RequestTracker;


text:
package com.hazelcast.kubernetes;

import com.hazelcast.test.HazelcastTestSupport;
import org.junit.Test;

public class KubernetesPropertiesTest
        extends HazelcastTestSupport {

    @Test
    public void privateConstructorTest() {
        assertUtilityConstructor(KubernetesProperties.class);
    }

}


text:
```
title: Jeremyfa
type: link
layout: link
href: 'http://jeremyfa.com'
cms:
    name: Jeremyfa
    url: 'http://jeremyfa.com'
```
http://jeremyfa.com


text:
@interface DLSDayTime : RLMObject <EKMappingProtocol>

@property NSString *dayName;
@property NSString *open;
@property NSString *close;
@property BOOL isHoliday;

@end

RLM_ARRAY_TYPE(DLSDayTime);

@interface DLSTimetableObject : RLMObject <EKMappingProtocol>

@property DLSDayTime *monday;
@property DLSDayTime *tuesday;
@property DLSDayTime *wednesday;
@property DLSDayTime *thursday;
@property DLSDayTime *friday;
@property DLSDayTime *saturday;
@property DLSDayTime *sunday;

@end

RLM_ARRAY_TYPE(DLSTimetableObject);


text:
<?php

function login_user($user_name, $user_password)
{
    $user_query = "SELECT `user_id`, `login_name`
            FROM `user_table`
            WHERE `login_name` = '$user_name' AND
                `password` = MD5( CONCAT( `password_salt`, '$user_password' ) ) AND
                `account_closed_date` IS NULL AND
                ( `expiration_date` IS NULL OR `expiration_date` >= DATE(NOW()) )";

    $user = db_fetch($user_query);
    if ($user) {
        $login_query = "UPDATE  `user_table`
            SET `last_login_date` = NOW()
            WHERE `user_id` = '${user['user_id']}' ";
        db_execute($login_query);

        $cookie = set_session_id($user['user_id']);
        header("Location: todo.php");
    } else {
        set_user_message("Login failed.  Either the user name or the password was incorrect, or else this user account does not exist or has expired.", 'warning');
    }
}

?>


text:
Ext.define('KitchenSink.view.binding.Selection', {
    extend: 'Ext.Container',

    //<example>
    otherContent: [{
        type: 'ViewModel',
        path: 'modern/src/view/binding/SelectionModel.js'
    }, {
        type: 'ViewModel',
        path: 'modern/src/model/Person.js'
    }],
    //</example>

    referenceHolder: true,

    viewModel: 'binding-selection',

    layout: {
        type: 'hbox',
        align: 'stretch'
    },

    items: [{
        xtype: 'list',
        flex: 1,
        itemTpl: '{lastName}, {firstName}',
        bind: '{people}',
        reference: 'peopleList'
    }, {
        xtype: 'formpanel',
        flex: 1,
        items: {
            xtype: 'fieldset',
            instructions: [
                'The form is bound to the selection in the list. As the form ',
                'fields change, the models in the list are automatically updated ',
                'with the field input.'
            ].join(''),
            items: [{
                xtype: 'textfield',
                label: 'First Name',
                bind: '{peopleList.selection.firstName}'
            }, {
                xtype: 'textfield',
                label: 'Last Name',
                bind: '{peopleList.selection.lastName}'
            }]
        }
    }]
});


text:
package loader

import (
	"github.com/pagarme/teleport/batcher"
	"github.com/pagarme/teleport/client"
	"github.com/pagarme/teleport/database"
)

type Loader struct {
	BatchSize  int
	db         *database.Database
	target     *client.Client
	targetName string
	batcher    *batcher.Batcher
}

func New(db *database.Database, target *client.Client, targetName string, batchSize int) *Loader {
	batcher := batcher.New(db, map[string]*client.Client{
		targetName: target,
	})

	return &Loader{
		db:         db,
		target:     target,
		targetName: targetName,
		batcher:    batcher,
		BatchSize:  batchSize,
	}
}

func (l *Loader) Load() error {
	events, err := l.db.GetEvents("building")

	if err != nil {
		return err
	}

	eventBatches, err := l.getDMLBatchEvents(events)

	if err != nil {
		return err
	}

	if len(eventBatches) == 0 {
		// Start new initial load
		_, err = l.createDDLBatch()

		if err != nil {
			return err
		}

		// Create DML events
		eventBatches, err = l.createDMLEvents()

		if err != nil {
			return err
		}
	}

	// Resume initial load (from existing events or new events)
	return l.resumeDMLEvents(eventBatches)
}


text:
Properties
----------
Ply is configured via property files.  There are two directories where ply looks for property files.  The first is located
at `$PLY_HOME/config` and represents the system defaults.  The second is located at directory `.ply/config` relative to the project directory.
This directory is created for you when initializing a project; i.e., `ply init`.

The files within these directories are simply unix style property files.  The name of the property file
is considered to be the context (and if there is a '.' in the file name that after the period is the scope, see [Scopes](Scopes.md) for
a general description of scopes).

Any property defined within the system configuration directory can be overridden within the project's local config
directory.  To override a property locally, create a property file within the `.ply/config` directory with the same name
and assign your overridden value to the same property name.  For instance, the source directory used during compilation
is a property defined within the `$PLY_HOME/config/project.properties` file named `src.dir`.  To override this for
a project, you would add a property named `src.dir` within the `.ply/config/project.properties` file.

Because interacting with these property files is a common task, ply provides tools to assist

    $ ply --usage

Some examples:

To get all locally defined properties (across all contexts):

    $ ply get

To get all properties (including system properties):

    $ ply get-all

To get all local properties with context `project` (i.e., those defined within the `project.properties` file)

    $ ply get from project

To get all properties starting with _name_

    $ ply get-all name*

To get all properties within the `compiler` context starting with _warn_

    $ ply get-all warn* from compiler

To set _version_ within the `project` context to be _2.0_

    $ ply set version=2.0 in project

To set a property named _url_ in a context called `environ` to _http://mydomain.com_ (note, the property file will be created if it doesn't exist).

    $ ply set "url=http://mydomain.com" in environ

To delete the property _url_ from the context `environ` (note, if after removal of _url_ there are no properties left the whole `environ.properties` file will be deleted)

    $ ply rm url from environ

Ad-Hoc Properties
-----------------

Property values can also be set for a single execution.  These ad-hoc properties are command line arguments specified with the `-P` directive and are only valid for that particular execution (are not saved for subsequent executions).  For instance, to disable the java compiler's warnings only for the particular execution of `compile` one would:

    $ ply compile -Pcompiler.java.warningsLevel=none

The next time `compile` is run the java compiler's warnings will revert to the value within the properties files as normal.

Accessing Property Values From Scripts
-------------------------------------

Any script can directly read these property files during execution, however, ply does the heavy lifting by resolving the
properties and passing them as environmental variables to each invoked script.  The resolution of properties files
involves collecting all properties for all contexts (for the given scope; again see [Scopes](Scopes.md) for a general description
of what scopes are) and overriding properties appropriately.

Ply passes the properties in the following format: `ply_context.propName=propValue`.  That is the environment variable name
is `ply_context.propName` and the value is `propValue`.  The first four characters `ply_` are just to disambiguate ply
properties from other environment variables.  The next part is the context.  The context is the property file name (without
the scope), so in the last example above the context is `environ`.  The `propName` and `propValue` are self-explanatory.
If a property within a context is defined in the system defaults but overridden by the local project, only the local
project's overridden property is passed.
For example; the `$PLY_HOME/config/compiler.properties` file contains a property named _warnings_ whose value is _true_.
If the local project overrides this to false

    $ ply set warnings=false in compiler

then only the local override is passed to scripts (i.e., scripts will see one environment variable named `ply_compiler.warnings` with
value `false`).

Note, the delimiter between the `context` and the `propName` within the environment variable name is changed to an
underscore character when the execution is a shell script (in an attempt to make the variable name shell-safe).  If
the property name contains period characters these characters are changed to underscores as well.  Other non-shell-safe
characters are left as is so take warning when creating shell scripts.


text:
<?xml version="1.0"?>
<tool name="HbVar" id="hbvar">

	<description>Human Hemoglobin Variants and Thalassemias</description>

	<command/>

	<inputs action="http://globin.bx.psu.edu/cgi-bin/hbvar/query_vars3" check_values="false" method="get" target="_top">
		<display>go to HbVar database $GALAXY_URL $tool_id</display>
		<param name="GALAXY_URL" type="baseurl" value="/tool_runner/hbvar" />
		<param name="tool_id" type="hidden" value = "hbvar"/>
	</inputs>

	<uihints minwidth="800"/>

	<code file="hbvar_filter.py"/>

	<outputs>
		<data name="output" format="txt" />
	</outputs>

	<options sanitize="False" refresh="True"/>

</tool>


text:
package ru.job4j.buffer;

public class Buffer {
    private StringBuffer buffer = new StringBuffer();

    public void add(int value) {
        System.out.print(value);
        this.buffer.append(value);
    }

    @Override
    public String toString() {
        return this.buffer.toString();
    }
}