text:
namespace schwa { namespace third_party { namespace re2 {

Thread::Thread() {
  pid_ = 0;
  running_ = 0;
  joinable_ = 0;
}

Thread::~Thread() {
}

void *startThread(void *v) {
  Thread* t = (Thread*)v;
  t->Run();
  return 0;
}

void Thread::Start() {
  CHECK(!running_);
  pthread_create(&pid_, 0, startThread, this);
  running_ = true;
  if (!joinable_)
    pthread_detach(pid_);
}

void Thread::Join() {
  CHECK(running_);
  CHECK(joinable_);
  void *val;
  pthread_join(pid_, &val);
  running_ = 0;
}

void Thread::SetJoinable(bool j) {
  CHECK(!running_);
  joinable_ = j;
}

} } }  // namespace


text:
package org.xillium.base.beans;

import java.lang.reflect.*;
import java.beans.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;

public class BeanNode implements TreeNode {
    /**
     * Creates a root node.
     */
    public BeanNode(Object bean) {
        this(bean, null, 0, null);
    }

    protected BeanNode(Object bean, BeanNode parent, int index, String label) {
        _bean = bean;
        if (bean != null) {
            try {
                _properties = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();
            } catch (IntrospectionException x) {
                _properties = null;
            }
        }
        _parent = parent;
        _index = index;
        _label = label;
    }

    public BeanNode setFieldsVisible(boolean visible) {
        _fieldsVisible = visible;
        return this;
    }

    public Enumeration<BeanNode> children() {
        if (_list == null) {
            _list = childrenList();
        }
        return Collections.enumeration(_list);
    }

    public boolean getAllowsChildren() {
        return !isLeaf();
    }

    public TreeNode getChildAt(int index) {
        if (_list == null) {
            _list = childrenList();
        }
        return _list.get(index);
    }

    public int getChildCount() {
        if (_list == null) {
            _list = childrenList();
        }
        return _list.size();
    }

    public int getIndex(TreeNode node) {
        return ((BeanNode)node)._index;
    }

    public TreeNode getParent() {
        return _parent;
    }

    public boolean isLeaf() {
        if (_bean == null) {
            return true;
        } else {
            Class<?> type = _bean.getClass();
            return Beans.isPrimitive(type) || Beans.isDisplayable(type);
        }
    }

    public String toString() {
        if (_bean == null) {
            return _label != null ? _label : "[null]";
        } else {
            return _label != null ? (_label + '[' + _bean.getClass().getName() + ']') : _bean.getClass().getName();
        }
    }

    protected List<BeanNode> childrenList() {
        ArrayList<BeanNode> list = new ArrayList<BeanNode>();
        if (isLeaf()) {
            return list;
        } else {
            if (Iterable.class.isInstance(_bean)) {
                Iterator<?> iterator = ((Iterable<?>)_bean).iterator();
                int index = 0;
                while (iterator.hasNext()) {
                    list.add(new BeanNode(iterator.next(), this, index, String.valueOf(index)));
                    ++index;
                }
            } else {
                int index = 0;
                if (_fieldsVisible) {
                    Field[] fields = _bean.getClass().getFields();
                    for (int i = 0; i < fields.length; ++i) {
                        try {
                            list.add(new BeanNode(fields[i].get(_bean), this, index, fields[i].getName()));
                        } catch (Exception x) {
                            list.add(new BeanNode(x, this, index, x.getClass().getName()));
                        }
                        ++index;
                    }
                }
                for (int i = 0; i < _properties.length; ++i) {
                    try {
                        Method reader = _properties[i].getReadMethod();
                        if (reader != null) {
                            list.add(new BeanNode(reader.invoke(_bean), this, index, _properties[i].getDisplayName()));
                        }
                    } catch (Exception x) {
                        list.add(new BeanNode(x, this, index, x.getClass().getName()));
                    }
                    ++index;
                }
            }
            return list;
        }
    }

    private final Object _bean;
    private final int _index;
    private final BeanNode _parent;
    private final String _label;
    private PropertyDescriptor[] _properties;
    private List<BeanNode> _list;
    private boolean _fieldsVisible = false;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Object Inspector");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTree tree = new JTree(new BeanNode(frame).setFieldsVisible(true));
        frame.getContentPane().add(new JScrollPane(tree), java.awt.BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class RedisServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Jedis jedis = new Jedis("10.16.33.62", 8359);
        jedis.auth("1duvtlet0j:cf090196754d78b7090854a916426092728a1e30");
        System.out.println(jedis.lpush("sohu", "sohu-java"));

        PrintWriter writer = response.getWriter();
        writer.println("Hello, sohu!");
        writer.close();

    }
}


text:
import 'aurelia-polyfills';
import { initialize } from 'aurelia-pal-browser';
import { WebpackLoader } from 'aurelia-loader-webpack';

initialize();

let bootstrapQueue = [];
let sharedLoader = null;
let Aurelia = null;

function onBootstrap(callback) {
  return new Promise((resolve, reject) => {
    if (sharedLoader) {
      resolve(callback(sharedLoader));
    } else {
      bootstrapQueue.push(() => {
        try {
          resolve(callback(sharedLoader));
        } catch (e) {
          reject(e);
        }
      });
    }
  });
}

function ready(global) {
  return new Promise((resolve, reject) => {
    if (global.document.readyState === 'complete') {
      resolve(global.document);
    } else {
      global.document.addEventListener('DOMContentLoaded', completed);
      global.addEventListener('load', completed);
    }

    function completed() {
      global.document.removeEventListener('DOMContentLoaded', completed);
      global.removeEventListener('load', completed);
      resolve(global.document);
    }
  });
}

function handleApp(loader, appHost) {
  return config(loader, appHost, appHost.getAttribute('aurelia-app'));
}

function config(loader, appHost, configModuleId) {
  const aurelia = new Aurelia(loader);
  aurelia.host = appHost;
  aurelia.configModuleId = configModuleId || null;

  if (configModuleId) {
    return loader.loadModule(configModuleId).then(customConfig => customConfig.configure(aurelia));
  }

  aurelia.use.standardConfiguration().developmentLogging();

  return aurelia.start().then(() => aurelia.setRoot());
}

function run() {
  return ready(window).then(doc => {
    const appHost = doc.querySelectorAll('[aurelia-app]');
    const loader = new WebpackLoader();
    loader.loadModule('aurelia-framework').then(m => {
      Aurelia = m.Aurelia;
      for (let i = 0, ii = appHost.length; i < ii; ++i) {
        handleApp(loader, appHost[i]).catch(console.error.bind(console));
      }

      sharedLoader = loader;
      for (let i = 0, ii = bootstrapQueue.length; i < ii; ++i) {
        bootstrapQueue[i]();
      }
      bootstrapQueue = null;
    });
  });
}

export function bootstrap(configure) {
  return onBootstrap(loader => {
    const aurelia = new Aurelia(loader);
    return configure(aurelia);
  });
}

run();


text:
using System;
using System.Globalization;
using Xunit;

namespace System.Globalization.Tests
{
    public class NumberStylesAllowDecimalPoint
    {
        // PosTest1: Verify value of NumberStyles.AllowDecimalPoint
        [Fact]
        public void TestAllowDecimalPoint()
        {
            int expected = 0x00000020;
            int actual = (int)NumberStyles.AllowDecimalPoint;
            Assert.Equal(expected, actual);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Change SYSTEM "https://itk.org/migrationv4/ITKMigration.dtd">
<Change>
  <Title>
    ITK_EXTERNAL preprocsssor directive removed.
  </Title>

  <Author>
    Hans Johnson
  </Author>

  <Description>
    <![CDATA[
    The defintion of ITK_EXPORT was empty in all cases

    This has been identified since 2003 as not being necessary
    for builds.  On Windows the EXPORT needs to be per library,
    and that is not controlled by CMake now.

    The PrintSelfCheck.tcl was the only remenant need for
    This patch, and that is no longer being used, so that
    file as been removed.

    The ITK_EXPORT define was set to nothing and had no
    known remaining purpose.  It was removed to make the
    over all code easier to understand.  There was,
    understandably, a bit of confusion about the
    need for this being pervasive in the code.

    It is currently backwards compatible to have
    this in code, but at some future point it will
    be removed (and is currently removed when
    ITK_FUTURE_LEGACY_REMOVE is set)
    ]]>
  </Description>

  <SampleCode>
    <Old>
       class ITK_EXTERN ImageBase
    </Old>
    <New>
       class ImageBase
    </New>
  </SampleCode>

    <Gerrit-ChangeId>
     I91573177a9bec05ccc44e5f875fe977a4e6cb1d6
    </Gerrit-ChangeId>

  <FileList>
    Almost every class header file
  </FileList>

<MigrationFix-Automatic>
  <Old>
    class  *ITK_EXTERN  *
  </Old>
  <New>
    class
  </New>
</MigrationFix-Automatic>
</Change>


text:
// Copyright (c) 2019 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ICSharpCode.WpfDesign.Extensions
{
	/// <summary>
	/// Manages extension creation for a design context.
	/// </summary>
	public sealed class ExtensionManager
	{
		readonly DesignContext _context;

		internal ExtensionManager(DesignContext context)
		{
			Debug.Assert(context != null);
			this._context = context;

			context.Services.RunWhenAvailable<IComponentService>(
				delegate(IComponentService componentService) {
					componentService.ComponentRegistered += OnComponentRegistered;
				});
		}

		void OnComponentRegistered(object sender, DesignItemEventArgs e)
		{
			e.Item.SetExtensionServers(this, GetExtensionServersForItem(e.Item));
		}

		/// <summary>
		/// Re-applies extensions from the ExtensionServer to the specified design items.
		/// </summary>
		void ReapplyExtensions(IEnumerable<DesignItem> items, ExtensionServer server)
		{
			foreach (DesignItem item in items) {
				if (item != null) {
					item.ReapplyExtensionServer(this, server);
				}
			}
		}

		#region Manage ExtensionEntries
		sealed class ExtensionEntry
		{
			internal readonly Type ExtensionType;
			internal readonly ExtensionServer Server;
			internal readonly List<Type> OverriddenExtensionTypes = new List<Type>();
			internal readonly int Order;

			public ExtensionEntry(Type extensionType, ExtensionServer server, Type overriddenExtensionType, int order)
			{
				this.ExtensionType = extensionType;
				this.Server = server;
				this.OverriddenExtensionTypes.Add(overriddenExtensionType);
				this.Order = order;
			}

			public ExtensionEntry(Type extensionType, ExtensionServer server, List<Type> overriddenExtensionTypes, int order)
			{
				this.ExtensionType = extensionType;
				this.Server = server;
				this.OverriddenExtensionTypes = overriddenExtensionTypes;
				this.Order = order;
			}
		}

		Dictionary<Type, List<ExtensionEntry>> _extensions = new Dictionary<Type, List<ExtensionEntry>>();

		void AddExtensionEntry(Type extendedItemType, ExtensionEntry entry)
		{
			List<ExtensionEntry> list;
			if (!_extensions.TryGetValue(extendedItemType, out list)) {
				list = _extensions[extendedItemType] = new List<ExtensionEntry>();
			}
			list.Add(entry);
		}

		/// <summary>
		/// Remove a Extension form a Type, so it is not used!
		/// </summary>
		/// <param name="extendedItemType"></param>
		/// <param name="extensionType"></param>
		public void RemoveExtension(Type extendedItemType, Type extensionType)
		{
			List<ExtensionEntry> list;
			if (!_extensions.TryGetValue(extendedItemType, out list))
			{
				list = _extensions[extendedItemType] = new List<ExtensionEntry>();
			}
			list.RemoveAll(x => x.ExtensionType == extensionType);
		}

		List<ExtensionEntry> GetExtensionEntries(Type extendedItemType)
		{
			List<ExtensionEntry> result = new List<ExtensionEntry>();
			List<Type> overriddenExtensions = new List<Type>();
			IEnumerable<ExtensionEntry> ie = _extensions.Where(x => x.Key.IsAssignableFrom(extendedItemType)).SelectMany(x => x.Value);
			foreach (ExtensionEntry entry in ie) {
				if (!overriddenExtensions.Contains(entry.ExtensionType)) {
					overriddenExtensions.AddRange(entry.OverriddenExtensionTypes);

					result.RemoveAll(x => overriddenExtensions.Contains(x.ExtensionType));
					result.Add(entry);
				}
			}
			return result.OrderBy(x => x.Order).ToList();
		}

		/// <summary>
		/// Gets all the types of all extensions that are applied to the specified item type.
		/// </summary>
		public IEnumerable<Type> GetExtensionTypes(Type extendedItemType)
		{
			if (extendedItemType == null)
				throw new ArgumentNullException("extendedItemType");
			foreach (ExtensionEntry entry in GetExtensionEntries(extendedItemType)) {
				yield return entry.ExtensionType;
			}
		}
		#endregion

		#region Create Extensions
		static readonly ExtensionEntry[] emptyExtensionEntryArray = new ExtensionEntry[0];

		IEnumerable<ExtensionEntry> GetExtensionEntries(DesignItem extendedItem)
		{
			if (extendedItem.Component == null)
				return emptyExtensionEntryArray;
			else
				return GetExtensionEntries(extendedItem.ComponentType);
		}

		ExtensionServer[] GetExtensionServersForItem(DesignItem item)
		{
			Debug.Assert(item != null);

			HashSet<ExtensionServer> servers = new HashSet<ExtensionServer>();
			foreach (ExtensionEntry entry in GetExtensionEntries(item)) {
				servers.Add(entry.Server);
			}
			return servers.ToArray();
		}

		internal IEnumerable<Extension> CreateExtensions(ExtensionServer server, DesignItem item, Type extensionType = null)
		{
			Debug.Assert(server != null);
			Debug.Assert(item != null);

			foreach (ExtensionEntry entry in GetExtensionEntries(item)) {
				if (entry.Server == server && (extensionType == null || entry.ExtensionType == extensionType)) {

					var disabledExtensions = Extension.GetDisabledExtensions(item.View);
					if (string.IsNullOrEmpty(disabledExtensions) || !disabledExtensions.Split(';').Contains(entry.ExtensionType.Name))
						yield return server.CreateExtension(entry.ExtensionType, item);
				}
			}
		}

		#endregion

		#region RegisterAssembly
		HashSet<Assembly> _registeredAssemblies = new HashSet<Assembly>();

		/// <summary>
		/// Registers extensions from the specified assembly.
		/// </summary>
		public void RegisterAssembly(Assembly assembly)
		{
			if (assembly == null)
				throw new ArgumentNullException("assembly");

//			object[] assemblyAttributes = assembly.GetCustomAttributes(typeof(IsWpfDesignerAssemblyAttribute), false);
//			if (assemblyAttributes.Length == 0)
//				return;

			if (!_registeredAssemblies.Add(assembly)) {
				// the assembly already is registered, don't try to register it again.
				return;
			}

//			IsWpfDesignerAssemblyAttribute isWpfDesignerAssembly = (IsWpfDesignerAssemblyAttribute)assemblyAttributes[0];
//			foreach (Type type in isWpfDesignerAssembly.UsePrivateReflection ? assembly.GetTypes() : assembly.GetExportedTypes()) {
			foreach (Type type in assembly.GetTypes()) {
				object[] extensionForAttributes = type.GetCustomAttributes(typeof(ExtensionForAttribute), false);
				if (extensionForAttributes.Length == 0)
					continue;

				foreach (ExtensionForAttribute designerFor in extensionForAttributes) {
					ExtensionServer server = GetServerForExtension(type);
					ExtensionAttribute extensionAttribute = type.GetCustomAttributes(typeof(ExtensionAttribute), false).FirstOrDefault() as ExtensionAttribute;
					AddExtensionEntry(designerFor.DesignedItemType, new ExtensionEntry(type, server,  designerFor.OverrideExtensions.ToList(), extensionAttribute != null ? extensionAttribute.Order : 0));
				}
			}
		}
		#endregion

		#region Extension Server Creation
		// extension server type => extension server instance
		Dictionary<Type, ExtensionServer> _extensionServers = new Dictionary<Type, ExtensionServer>();

		ExtensionServer GetServerForExtension(Type extensionType)
		{
			Debug.Assert(extensionType != null);

			object[] extensionServerAttributes = extensionType.GetCustomAttributes(typeof(ExtensionServerAttribute), true);
			if (extensionServerAttributes.Length != 1)
				throw new DesignerException("Extension types must have exactly one [ExtensionServer] attribute.");

			return GetExtensionServer((ExtensionServerAttribute)extensionServerAttributes[0]);
		}

		/// <summary>
		/// Gets the extension server for the specified extension server attribute.
		/// </summary>
		public ExtensionServer GetExtensionServer(ExtensionServerAttribute attribute)
		{
			if (attribute == null)
				throw new ArgumentNullException("attribute");

			Type extensionServerType = attribute.ExtensionServerType;

			ExtensionServer server;
			if (_extensionServers.TryGetValue(extensionServerType, out server))
				return server;

			server = (ExtensionServer)Activator.CreateInstance(extensionServerType);
			server.InitializeExtensionServer(_context);
			_extensionServers[extensionServerType] = server;
			server.ShouldApplyExtensionsInvalidated += delegate(object sender, DesignItemCollectionEventArgs e) {
				ReapplyExtensions(e.Items, (ExtensionServer)sender);
			};
			return server;
		}
		#endregion

		#region Special extensions (CustomInstanceFactory and DefaultInitializer)
		static readonly object[] emptyObjectArray = new object[0];

		/// <summary>
		/// Create an instance of the specified type using the specified arguments.
		/// The instance is created using a CustomInstanceFactory registered for the type,
		/// or using reflection if no instance factory is found.
		/// </summary>
		public object CreateInstanceWithCustomInstanceFactory(Type instanceType, object[] arguments)
		{
			if (instanceType == null)
				throw new ArgumentNullException("instanceType");
			if (arguments == null)
				arguments = emptyObjectArray;

			foreach (Type extensionType in GetExtensionTypes(instanceType)) {
				if (typeof(CustomInstanceFactory).IsAssignableFrom(extensionType)) {
					CustomInstanceFactory factory = (CustomInstanceFactory)Activator.CreateInstance(extensionType);
					return factory.CreateInstance(instanceType, arguments);
				}
			}
			return CustomInstanceFactory.DefaultInstanceFactory.CreateInstance(instanceType, arguments);
		}

		/// <summary>
		/// Applies all DefaultInitializer extensions on the design item.
		/// </summary>
		public void ApplyDefaultInitializers(DesignItem item)
		{
			if (item == null)
				throw new ArgumentNullException("item");

			foreach (ExtensionEntry entry in GetExtensionEntries(item)) {
				if (typeof(DefaultInitializer).IsAssignableFrom(entry.ExtensionType)) {
					DefaultInitializer initializer = (DefaultInitializer)Activator.CreateInstance(entry.ExtensionType);
					initializer.InitializeDefaults(item);
				}
			}
		}

		/// <summary>
		/// Applies all DefaultInitializer extensions on the design item.
		/// </summary>
		public void ApplyDesignItemInitializers(DesignItem item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            foreach (ExtensionEntry entry in GetExtensionEntries(item)) {
                if (typeof(DesignItemInitializer).IsAssignableFrom(entry.ExtensionType)) {
                    DesignItemInitializer initializer = (DesignItemInitializer)Activator.CreateInstance(entry.ExtensionType);
                    initializer.InitializeDesignItem(item);
                }
            }
        }
		#endregion
	}
}


text:
package com.huawei.agilete.base.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.io.FileUtils;

/**
 *
 * @author lWX200287
 *
 */
public class ReadConfig {
    private Properties properties = null;
    private StringBuffer path;

    public ReadConfig(){

    }

    public Properties get(){
        if(null == properties){
            StringBuffer filePah=new StringBuffer(getPath());
            filePah.append("conf\\config.xml");
            File file = new File(filePah.toString());
            if(file.isFile()&&file.exists()){
                //InputStreamReader read;
                InputStream read;
                try {
                    //read = new InputStreamReader(new FileInputStream(file),"UTF-8");
                    read = new FileInputStream(file);
                    properties = new Properties();
                    //properties.load(read);
                    properties.loadFromXML(read);
                    read.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return properties;
            }
            return null;
        }else{
            return properties;
        }
    }

    public String getTemple(String fileName){
        String readContent = "";
        StringBuffer filePah=new StringBuffer(getPath());
        filePah.append("conf/schemaTemple/");
        filePah.append(fileName);
        File file=new File(filePah.toString());
        try {
            readContent = FileUtils.readFileToString(file,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return readContent;
    }

    public String getIps(String fileName){
        String readContent = "";
        StringBuffer filePah=new StringBuffer(getPath());
        filePah.append("conf/schemaTemple/");
        filePah.append(fileName);
        File file=new File(filePah.toString());
        try {
            readContent = FileUtils.readFileToString(file,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return readContent;
    }

    public StringBuffer getPath() {
        if(null == path || "".equals(path.toString())){
        	path = new StringBuffer();
    		String filePah = ReadConfig.class.getResource("/").getPath();
    		filePah = filePah.replace("%20", " ");
    		path.append(filePah.substring(1,filePah.lastIndexOf("classes/")));
        }
        return path;
    }

    public static void main(String[] args) {

    }
}


text:
<?php

/**
 * Catalog Search Controller
 *
 * @category   Mage
 * @package    Mage_CatalogSearch
 * @module     Catalog
 */
class Mage_CatalogSearch_AjaxController extends Mage_Core_Controller_Front_Action
{
    public function suggestAction()
    {
        if (!$this->getRequest()->getParam('q', false)) {
            $this->getResponse()->setRedirect(Mage::getSingleton('core/url')->getBaseUrl());
        }

        $this->getResponse()->setBody($this->getLayout()->createBlock('catalogsearch/autocomplete')->toHtml());
    }
}


text:
export interface ITitusServiceJobProcesses {
  [key: string]: boolean;
}


text:
package com.funkyandroid.droidcon.uk.droidconsched.io;

import com.funkyandroid.droidcon.uk.droidconsched.io.model.CheckIns;
import com.funkyandroid.droidcon.uk.droidconsched.io.model.Events;
import com.funkyandroid.droidcon.uk.droidconsched.io.model.Users;

/**
 * API for interacting with the server stored data.
 *
 * @author Al Sutton, Funky Android Ltd. (http://funkyandroid.com/)
 */
public class ConferenceAPI {
    public static final String DEFAULT_ROOT_URL = "https://www.googleapis.com/";
    public static final String DEFAULT_SERVICE_PATH = "googledevelopers/v1/";
    public static final String DEFAULT_BASE_URL = "https://www.googleapis.com/googledevelopers/v1/";

    public ConferenceAPI()
    {
    }

    public CheckIns checkIns()
    {
        return new CheckIns();
    }

    public Events events()
    {
        return new Events();
    }

    public Users users()
    {
        return new Users();
    }
}


text:
<?php

const anti_scrapping_addon_name = 'anti_scrapping_robot';
const anti_scrapping_addon_version = '0.1';

if (constant('APP_AREA') == 'customer') {
	cw_include('addons/' . anti_scrapping_addon_name . '/include/func.anti_scrapping.php');

	cw_addons_set_controllers(
		array('post', 'init/robot.php', 'addons/' . anti_scrapping_addon_name . '/init/robot.php')
	);

	cw_addons_set_hooks(
		array('post', 'cw_product_search', 'cw_anti_scrapping_product_search'),
		array('post', 'cw_product_get', 'cw_anti_scrapping_product_get')
	);
}


text:
package org.analogweb.core;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.analogweb.AttributesHandler;
import org.analogweb.RequestValueResolver;
import org.analogweb.RequestValueResolvers;
import org.analogweb.util.Maps;

public class DefaultReqestValueResolvers implements RequestValueResolvers {

	protected static final Class<? extends RequestValueResolver> DEFAULT_RESOLVER_CLASS = ParameterValueResolver.class;
	private final Map<Key, RequestValueResolver> resolverMap;

	public DefaultReqestValueResolvers(
			List<? extends RequestValueResolver> resolvers) {
		this.resolverMap = Maps.newConcurrentHashMap();
		for (RequestValueResolver resolver : resolvers) {
			if (resolver != null) {
				this.resolverMap
						.put(Key.valueOf(resolver.getClass()), resolver);
			}
		}
	}

	@Override
	public RequestValueResolver findDefaultRequestValueResolver() {
		return findRequestValueResolver(getDefaultRequestValueResolverClass());
	}

	@Override
	public RequestValueResolver findRequestValueResolver(
			Class<? extends RequestValueResolver> resolverClass) {
		if (resolverClass == null) {
			return getResolverMap().get(
					Key.valueOf(getDefaultRequestValueResolverClass()));
		}
		RequestValueResolver resolver = getResolverMap().get(
				Key.valueOf(resolverClass));
		if (resolver == null) {
			return getResolverMap().get(
					Key.valueOf(getDefaultRequestValueResolverClass()));
		}
		return resolver;
	}

	@Override
	public AttributesHandler findAttributesHandler(
			Class<? extends AttributesHandler> handlerClass) {
		RequestValueResolver resolver = findRequestValueResolver(handlerClass);
		if (resolver instanceof AttributesHandler) {
			return (AttributesHandler) resolver;
		}
		return null;
	}

	@Override
	public Collection<RequestValueResolver> all() {
		return getResolverMap().values();
	}

	protected final Map<Key, RequestValueResolver> getResolverMap() {
		return this.resolverMap;
	}

	protected Class<? extends RequestValueResolver> getDefaultRequestValueResolverClass() {
		return DEFAULT_RESOLVER_CLASS;
	}

	protected static class Key implements Serializable {

		private static final long serialVersionUID = 1L;
		private int hashCode;
		private final String name;

		private Key(Class<? extends RequestValueResolver> resolverClass) {
			this.name = resolverClass.getCanonicalName();
			calculateEquality(resolverClass);
		}

		private void calculateEquality(
				Class<? extends RequestValueResolver> resolverClass) {
			Class<?> target = resolverClass;
			this.hashCode = target.hashCode();
		}

		static Key valueOf(Class<? extends RequestValueResolver> resolverClass) {
			return new Key(resolverClass);
		}

		@Override
		public int hashCode() {
			return this.hashCode;
		}

		@Override
		public boolean equals(Object other) {
			if (other instanceof Key) {
				Key otherKey = (Key) other;
				if (name.equals(otherKey.name)) {
					return true;
				}
			}
			return false;
		}
	}

}


text:
from wsgiref.util import FileWrapper
from django.core.serializers.json import DjangoJSONEncoder
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from patient.models import *
from datetime import datetime, date
import json
import subprocess
import os

def generateID():
    return ''.join(random.sample(set(string.letters.upper()), 3) + random.sample(string.digits, 5))

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

# Create your views here.
@login_required
def index(request):
    return render(request, 'index.html')

def patient_get(request):
    response_data = {}
    if request.method == 'GET':
        if not request.GET.get('query', ''):
            response_data['status'] = 'success'
            response_data['message'] = Patient.objects.all()
        else:
            query = request.GET['query']
            data = Patient.objects.filter(
                Q(first_name__icontains=query) | Q(last_name__icontains=query) | Q(identifier__icontains=query)
            )
            response_data['status'] = 'success'
            response_data['message'] = list(data.values())

        return HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), content_type='application/json')
    response_data['status'] = 'error'
    response_data['message'] = 'Method not allowed!'
    return HttpResponse(json.dumps(response_data), content_type='application/json')

@login_required
def patient_index(request):
    return render(request, 'patient/index.html', {'query': request.GET.get('query', '')})

@login_required
def patient_create(request):
    if request.method == 'POST':
        fields = ['first_name', 'last_name', 'birthdate', 'address', 'city', 'province', 'country', 'phone_number']
        empty_field = []
        for field in fields:
            if not request.POST.get(field, ''):
                empty_field.append(field)
        if empty_field:
            messages.error(request, 'Please fill out these fields: %s' % ', '.join(empty_field))
        else:
            identifier = generateID()
            user = User.objects.create_user(identifier, password=identifier,
                first_name=request.POST['first_name'], last_name=request.POST['last_name'])
            patient = user.patient_set.create(
                identifier=identifier,
                first_name=request.POST['first_name'],
                last_name=request.POST['last_name'],
                birthdate=request.POST['birthdate'],
                address=request.POST['address'],
                city=request.POST['city'],
                province=request.POST['province'],
                country=request.POST['country'],
                phone_number=request.POST['phone_number']
            )
            patient.save()
            return HttpResponseRedirect(reverse('patient.views.patient_show', args=(patient.id,)))
    data = {}
    name = request.GET.get('name', '').split(' ')
    if name:
        data['first_name'] = ' '.join(name[:-1])
        data['last_name'] = name[-1]
    data['birthdate'] = request.GET.get('birthdate', '')
    data['gender'] = request.GET.get('gender', '')
    return render(request, 'patient/create.html', {'data': data})

@login_required
def patient_show(request, patient_id):
    patient = Patient.objects.get(id=patient_id)
    patient.age = calculate_age(patient.birthdate)
    visits = patient.visit_set.order_by('-date_created')
    if visits:
        last_visit = visits[0]
    else:
        last_visit = None
    vitals = patient.vitals_set.order_by('-date_created')
    if vitals:
        vitals = vitals[0]
    upcoming = patient.appointment_set.filter(date__gte=date.today()).order_by('date')
    if upcoming:
        upcoming = upcoming[0]
    data = {
        'patient': patient,
        'screenings': patient.screening_set.all(),
        'lab_results': patient.labresult_set.order_by('-date_created').all(),
        'treatments': patient.treatment_set.all(),
        'appointments': patient.appointment_set.filter(date__lt=date.today()),
        'visits': visits,
        'last_visit': last_visit,
        'vitals': vitals,
        'upcoming_appt': upcoming
    }
    return render(request, 'patient/show.html', data)

def screening_create(request, patient_id):
    if request.method == 'POST':
        fields = [
            'diagnosis',
            'hiv',
            'tb_exposure'
        ]
        empty_field = []
        for field in fields:
            if not request.POST.get(field, ''):
                empty_field.append(field)
        if empty_field:
            messages.error(request, 'Please fill out these fields: %s' % ', '.join(empty_field))
        else:
            user = User.objects.get(id=1)
            patient = Patient.objects.get(id=patient_id)
            screening = patient.screening_set.create(
                cough = request.POST.get('cough', False),
                haemoptysis = request.POST.get('haemoptysis', False),
                chest_pain = request.POST.get('chest_pain', False),
                weight_loss = request.POST.get('weight_loss', False),
                fatigue = request.POST.get('fatigue', False),
                fever = request.POST.get('fever', False),
                night_sweats = request.POST.get('night_sweats', False),
                chills = request.POST.get('chills', False),
                other_symptoms = request.POST.get('other_symptoms', False),
                diagnosis = request.POST.get('diagnosis', ''),
                tb_patient_status = request.POST.get('tb_patient_status', 0),
                meningitis = request.POST.get('meningitis', False),
                pregnant = request.POST.get('pregnant', False),
                immunocompromised = request.POST.get('immunocompromised', False),
                malnutrition = request.POST.get('malnutrition', False),
                coinfection = request.POST.get('coinfection', False),
                comorbid = request.POST.get('comorbid', False),
                hiv = request.POST['hiv'],
                tb_exposure = request.POST['tb_exposure'],
                creator = user
            )
            messages.success(request, 'TB screening form recorded.')
            return HttpResponseRedirect(reverse('patient.views.patient_show', args=(patient.id,)))
    patient = Patient.objects.get(id=patient_id)
    patient.age = calculate_age(patient.birthdate)
    return render(request, 'screening/create.html', {'patient': patient})

def screening_show(request, patient_id, screening_id):
    patient = Patient.objects.get(id=patient_id)
    patient.age = calculate_age(patient.birthdate)
    screening = Screening.objects.get(id=screening_id)
    return render(request, 'screening/show.html', {'patient': patient, 'screening': screening})

def visit_create(request, patient_id):
    if request.method == 'POST':
        fields = ['diagnoses', 'notes']
        empty_field = []
        for field in fields:
            if not request.POST.get(field, ''):
                empty_field.append(field)
        if empty_field:
            messages.error(request, 'Please fill out these fields: %s' % ', '.join(empty_field))
        else:
            user = User.objects.get(id=1)
            patient = Patient.objects.get(id=patient_id)
            visit = patient.visit_set.create(
                diagnoses=request.POST['diagnoses'],
                notes=request.POST['notes'],
                creator=user
            )
            messages.success(request, 'Visit notes recorded.')
            return HttpResponseRedirect(reverse('patient.views.patient_show', args=(patient.id,)))
    patient = Patient.objects.get(id=patient_id)
    patient.age = calculate_age(patient.birthdate)
    return render(request, 'visit/create.html', {'patient': patient})

def vitals_create(request, patient_id):
    if request.method == 'POST':
        fields = ['height', 'weight', 'temperature', 'pulse', 'respiratory_rate', 'bp_systole', 'bp_diastole']
        empty_field = []
        for field in fields:
            if not request.POST.get(field, ''):
                empty_field.append(field)
        if empty_field:
            messages.error(request, 'Please fill out these fields: %s' % ', '.join(empty_field))
        else:
            user = User.objects.get(id=1)
            patient = Patient.objects.get(id=patient_id)
            vitals = patient.vitals_set.create(
                height=request.POST['height'],
                weight=request.POST['weight'],
                temperature=request.POST['temperature'],
                pulse=request.POST['pulse'],
                respiratory_rate=request.POST['respiratory_rate'],
                bp_systole=request.POST['bp_systole'],
                bp_diastole=request.POST['bp_diastole'],
                creator=user
            )
            messages.success(request, 'Vitals recorded.')
            return HttpResponseRedirect(reverse('patient.views.patient_show', args=(patient.id,)))
    patient = Patient.objects.get(id=patient_id)
    patient.age = calculate_age(patient.birthdate)
    return render(request, 'vitals/create.html', {'patient': patient})

def vitals_trend(request, patient_id, column):
    patient = Patient.objects.get(id=patient_id)
    patient.age = calculate_age(patient.birthdate)
    vitals = patient.vitals_set.order_by('date_created')
    labels = '"%s"' % ','.join([v.date_created.strftime('%Y-%m-%d') for v in vitals])
    data = ','.join([str(v) for v in vitals.values_list(column, flat=True)])
    column_name = column.replace('_', ' ').title()
    return render(request, 'vitals/trend.html', {'patient': patient, 'labels': labels, 'data': data, 'column_name': column_name})

def appointment_create(request, patient_id):
    if request.method == 'POST':
        fields = ['service_type', 'agenda', 'date']
        empty_field = []
        for field in fields:
            if not request.POST.get(field, ''):
                empty_field.append(field)
        if empty_field:
            messages.error(request, 'Please fill out these fields: %s' % ', '.join(empty_field))
            print 'Please fill out these fields: %s' % ', '.join(empty_field)
        else:
            user = User.objects.get(id=1)
            patient = Patient.objects.get(id=patient_id)
            appointment = patient.appointment_set.create(
                service_type=request.POST['service_type'],
                agenda=request.POST['agenda'],
                date=request.POST['date'],
                creator=user
            )
            messages.success(request, 'Appointment scheduled.')
            newdate = request.POST['date'].replace(" ", "-")
            newdate = newdate.replace(":", "-")
            uri = "tbdc://tp=0&sv=%s&dt=%s" % (request.POST['service_type'], newdate)
            print uri
            send_SMS('Appointment scheduled with dr. %s on %s. Add to schedule: %s' % (user.last_name, appointment.date, uri), patient.phone_number)
            return HttpResponseRedirect(reverse('patient.views.patient_show', args=(patient.id,)))
    patient = Patient.objects.get(id=patient_id)
    patient.age = calculate_age(patient.birthdate)
    return render(request, 'appointment/create.html', {'patient': patient})

def appointment_show(request, patient_id, appointment_id):
    patient = Patient.objects.get(id=patient_id)
    patient.age = calculate_age(patient.birthdate)
    appointment = Appointment.objects.get(id=appointment_id)
    return render(request, 'appointment/show.html', {'patient': patient, 'appointment': appointment})

def handle_api(request, obj):
    response_data = {}
    if request.method == 'GET':
        fields = ['patient_id']
        empty_field = []
        for field in fields:
            if not request.GET.get(field, ''):
                empty_field.append(field)
        if empty_field:
            response_data['status'] = 'error'
            response_data['message'] = 'You have not set the parameter for %s' % ', '.join(empty_field)
        else:
            data = obj.objects.filter(patient__identifier=request.GET['patient_id']) # filter(date_created__gte=datetime.today())
            response_data['status'] = 'success'
            response_data['message'] = list(data.values())

        return HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), content_type='application/json')
    response_data['status'] = 'error'
    response_data['message'] = 'Method not allowed!'
    return HttpResponse(json.dumps(response_data), content_type='application/json')

def appointment_get(request):
    return handle_api(request, Appointment)

@login_required
def treatment_create(request, patient_id):
    if request.method == 'POST':
        fields = ['medication[]', 'dosage[]', 'freq_day[]', 'freq_week[]', 'start_date[]', 'end_date[]']
        empty_field = []
        for field in fields:
            if not request.POST.getlist(field, ''):
                print request.POST.getlist(field)
                empty_field.append(field)
        if empty_field:
            messages.error(request, 'Please fill out these fields: %s' % ', '.join(empty_field))
        else:
            user = User.objects.get(id=1)
            patient = Patient.objects.get(id=patient_id)
            medications = request.POST.getlist('medication[]')
            dosages = request.POST.getlist('dosage[]')
            freq_days = request.POST.getlist('freq_day[]')
            freq_weeks = request.POST.getlist('freq_week[]')
            start_dates = request.POST.getlist('start_date[]')
            end_dates = request.POST.getlist('end_date[]')
            for i in range(len(request.POST.getlist('medication[]'))):
                treatment = patient.treatment_set.create(
                    medication=medications[i],
                    dosage=dosages[i],
                    freq_day=freq_days[i],
                    freq_week=freq_weeks[i],
                    start_date=start_dates[i],
                    end_date=end_dates[i],
                    creator=user
                )
            newsdate = start_dates[i].replace(" ", "-")
            newsdate = newsdate.replace(":", "-")
            newedate = end_dates[i].replace(" ", "-")
            newedate = newedate.replace(":", "-")
            uri = "tbdc://tp=1&md=%s&fd=%s&fw=%s&sd=%s&ed=%s" % (medications[i], freq_days[i], freq_weeks[i], newsdate, newedate)
            print uri
            send_SMS('Please get the medication (%s) before %s. Add to shedule: %s' % (medications[i], start_dates[i], uri), patient.phone_number)
            messages.success(request, 'Medications added.')
            return HttpResponseRedirect(reverse('patient.views.patient_show', args=(patient.id,)))
    patient = Patient.objects.get(id=patient_id)
    patient.age = calculate_age(patient.birthdate)
    return render(request, 'treatment/create.html', {'patient': patient})

def treatment_get(request):
    return handle_api(request, Treatment)

def lab_result_afb_store(creator, filename):
    parameters = filename.split('_')
    result = int(parameters[0])
    identifier = parameters[-1].split('.')[0]
    patient = Patient.objects.get(identifier=identifier)
    if result == 0:
        result = 'MTB Negative'
    else:
        result = 'MTB Positive (%d)' % int(parameters[0])
    lab_result = LabResult(patient=patient, test_name='Microscopic AFB', img=filename, result=result, creator=creator)
    lab_result.save()
    send_SMS('Your BTA test result is ready. Contact lab to find out about the diagnosis.', patient.phone_number)

def lab_result_create(request):
    return render(request, 'labresult/index.html')

@csrf_exempt
def lab_result_store(request):
    response_data = {}
    if request.method == 'POST':
        fields = ['username', 'password', 'patient_id']
        empty_field = []
        for field in fields:
            if not request.POST.get(field, ''):
                empty_field.append(field)
        if empty_field or 'photo' not in request.FILES:
            response_data['status'] = 'error'
            response_data['message'] = 'Please fill out these fields: %s' % ', '.join(empty_field)
        elif request.FILES['photo'].name.split('.')[-1].lower() not in ['jpg','jpeg']:
            response_data['status'] = 'error'
            response_data['message'] = 'Invalid file extension! (.jpg needed)'
        else:
            user = authenticate(username=request.POST.get('username',''), password=request.POST.get('password',''))
            if user is not None:
                try:
                    patient = Patient.objects.get(identifier=request.POST['patient_id'])
                    filename = handle_upload(request, field_name='photo')
                    extension = filename.split('.')[-1]
                    response_data['status'] = 'success'
                    response_data['message'] = 'Photo uploaded!'

                    import threading
                    t = threading.Thread(target=save_result, args=(filename, user,))
                    t.start()
                except Exception, e:
                    response_data['status'] = 'error'
                    response_data['message'] = str(e)
            else:
                response_data['status'] = 'error'
                response_data['message'] = 'Invalid username or password!'

        return HttpResponse(json.dumps(response_data), content_type='application/json')
    response_data['status'] = 'error'
    response_data['message'] = 'Method not allowed!'
    return HttpResponse(json.dumps(response_data), content_type='application/json')

def save_result(filename, user):
    path_to_matlab = os.path.join(settings.BASE_DIR, 'media/')
    currentdir = os.getcwd()
    os.chdir(path_to_matlab)
    os.system("%s/run_tbdetect.sh /usr/local/MATLAB/MATLAB_Runtime/v85/ %s" % (path_to_matlab, filename))
    print "Matlab ran!"
    import time
    time.sleep(10)
    os.chdir(currentdir)
    filenames = os.listdir(settings.MEDIA_ROOT + 'result')
    for f in filenames:
        print f
        if filename in f:
            lab_result_afb_store(user, f)

def lab_result_show(request, patient_id, lab_result_id):
    patient = Patient.objects.get(id=patient_id)
    patient.age = calculate_age(patient.birthdate)
    lab_result = LabResult.objects.get(id=lab_result_id)
    user = lab_result.creator
    return render(request, 'labresult/show.html', {'patient': patient, 'lab_result': lab_result, 'user': user})

def prevalence(request):
    return render(request, 'prevalence.html')

def handle_upload(request, field_name):
    today = datetime.today()
    extension = request.FILES[field_name].name.split('.')[-1]
    filename = today.strftime("%y%m%d_%H%M%S") + '_' + request.POST.get('patient_id','') + '.' + extension
    with open(settings.MEDIA_ROOT +  "/target/"  + filename, 'wb+') as dest:
        for chunk in request.FILES[field_name].chunks():
            dest.write(chunk)
        return filename

def send_SMS(text, phone_number):
    # subprocess.Popen('echo "%s" | gammu sendsms TEXT %s' % (text, phone_number))
    try:
        path_to_gammu = os.path.join(settings.BASE_DIR, 'gammu/bin/smsdrc')
        subprocess.Popen("gammu-smsd-inject -c %s TEXT %s -text \"%s\"" % (path_to_gammu, phone_number, text))
    except:
        pass


text:
/*  This file is part of Openrouteservice.
 *
 *  Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the
 *  GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.

 *  This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *  See the GNU Lesser General Public License for more details.

 *  You should have received a copy of the GNU Lesser General Public License along with this library;
 *  if not, see <https://www.gnu.org/licenses/>.
 */
package org.heigit.ors.servlet.filters;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

class GZIPResponseWrapper extends HttpServletResponseWrapper {
	protected HttpServletResponse origResponse;
	protected GZIPResponseStream responseStream = null;
	protected PrintWriter writer = null;

	public GZIPResponseWrapper(HttpServletResponse response) {
		super(response);
		origResponse = response;
	}

	public GZIPResponseStream createOutputStream() throws IOException {
		return new GZIPResponseStream(origResponse);
	}

	public void finishResponse() {
		try {
			if (writer != null)
				writer.close();
			else {
				if (responseStream != null && !responseStream.isClosed())
					responseStream.close();
			}
		} catch (IOException e) {
			// do nothing
		}
	}

	public void flushBuffer() throws IOException {
		if (responseStream != null && !responseStream.isClosed())
			responseStream.flush();
	}

	public ServletOutputStream getOutputStream() throws IOException {
		if (writer != null)
			throw new IllegalStateException("getWriter() has already been called!");

		if (responseStream == null)
			responseStream = createOutputStream();

		return (responseStream);
	}

	public PrintWriter getWriter() throws IOException {
		if (writer != null)
			return (writer);

		if (responseStream != null)
			throw new IllegalStateException("getOutputStream() has already been called!");

		responseStream = createOutputStream();
		writer = new PrintWriter(new OutputStreamWriter(responseStream, StandardCharsets.UTF_8));
		return (writer);
	}

	public void setContentLength(int length) {
		// nothing to do
	}
}


text:
require "spec_helper"

describe Humanoid::Criterion::Complex do

  let(:complex) { Humanoid::Criterion::Complex.new(:key => :field, :operator => "$gt") }

  describe "#initialize" do

    it "sets the key" do
      complex.key.should == :field
    end

    it "sets the operator" do
      complex.operator.should == "$gt"
    end

  end

end


text:
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
import json
import datetime
from tracking.models import Pageview, Visitor
from website.models import Jurisdiction, JurisdictionRating

class Command(BaseCommand):
    args = 'No argument needed'
    help = 'Find the most popular jurisdictions'
    # url names that are for sure not specific jurisdiction
    skip_names = ['browse', 'search', 'autocomplete', 'answer_uploadfile', ]

    def handle(self, *args, **options):
        jurisdiction_unique_users = {}

        #find all the UserPageView for the last 7 days
        today = datetime.datetime.now()
        d = datetime.timedelta(hours=-24)
        start_date = today + d
        #print 'Updating most popular jurisdictions for days after: ' + str(start_date)
        user_page_views = Pageview.objects.filter(view_time__gt=start_date)
        #print 'Number of user page views: ' + str(len(user_page_views))

        for user_page_view in user_page_views:
            #print 'Datetime: ' + str(user_page_view.last_page_view_date)
            if user_page_view.url.startswith('/jurisdiction/'):
                name_for_url = user_page_view.url.replace('/jurisdiction/', '')
                name_for_url = name_for_url.partition('/')[0]
                if name_for_url in self.skip_names:
                    continue
                if name_for_url.isdigit():
                    #search for jurisdiction by id
                    jurisdictions = Jurisdiction.objects.filter(id=name_for_url)
                else:
                    #search for jurisdiction by name for url
                    jurisdictions = Jurisdiction.objects.filter(name_for_url=name_for_url)
                if len(jurisdictions) > 0:
                    jurisdiction = jurisdictions[0] #just get 1st
                #print 'name_for_url: ' + name_for_url
                #print 'jurisdiction: ' + jurisdiction.show_jurisdiction()

                #remember jurisdiction unique users
                try:
                    jurisdiction_unique_users[jurisdiction.id]
                except:
                    jurisdiction_unique_users[jurisdiction.id] = []
                if user_page_view.visitor.session_key not in jurisdiction_unique_users[jurisdiction.id]:
                    jurisdiction_unique_users[jurisdiction.id].append(user_page_view.visitor.session_key)
                #print 'jurisdiction_unique_users' + str(jurisdiction_unique_users)

        #find the jurisdiction with most unique users
        jurisdiction_unique_users_counts = []
        for jid, user_list in jurisdiction_unique_users.iteritems():
            jurisdiction_unique_users_counts.append([jid, len(user_list)])
        jurisdiction_unique_users_counts.sort(key=lambda x: x[1], reverse=True) #sort by user count
        jurisdiction_unique_users_counts = jurisdiction_unique_users_counts[0:10] #only top 10

        #save data in JurisdictionRating
        jurisdiction_ratings = JurisdictionRating.objects.filter(rating_type='V')
        for jurisdiction_rating in jurisdiction_ratings:
            jurisdiction_rating.delete()
        rank = 1
        for jid, count in jurisdiction_unique_users_counts:
            jurisdiction_rating = JurisdictionRating(rating_type='V', rank=rank, value=count)
            jurisdiction = Jurisdiction.objects.get(id=jid)
            jurisdiction_rating.jurisdiction = jurisdiction
            jurisdiction_rating.create_datetime = today
            jurisdiction_rating.save()
            print str(rank) + ': ' +jurisdiction.show_jurisdiction() + ', unique views: ' + str(count)
            rank += 1

        '''#just for testing
        print 'Recently updated: '
        jurisdictions = JurisdictionRating.recently_updated()
        for jurisdiction in jurisdictions:
            print jurisdiction.show_jurisdiction()

        #just for testing
        print 'Most popular: '
        jurisdictions = JurisdictionRating.most_popular()
        for jurisdiction in jurisdictions:
            print jurisdiction.show_jurisdiction()'''


text:
package org.scalatest.examples.funspec

import org.scalatest.FunSpec

class SetSpec extends FunSpec {

  describe("A Set") {
    describe("when empty") {
      it("should have size 0") {
        assert(Set.empty.size === 0)
      }

      it("should produce NoSuchElementException when head is invoked") {
        intercept[NoSuchElementException] {
          Set.empty.head
        }
      }
    }
  }
}


text:
require 'fileutils'

def install(file)
  puts "Installing: #{file}"
  target = File.join(File.dirname(__FILE__), '..', '..', '..', file)
  if File.exists?(target)
    puts "target #{target} already exists, skipping"
  else
    FileUtils.cp File.join(File.dirname(__FILE__), file), target
  end
end

install File.join( 'script', 'yarb_server' )
install File.join( 'config', 'yarb.yml' )

puts IO.read(File.join(File.dirname(__FILE__), 'README'))


text:
This is a POC project of a Lua module to authenticate CAS users on NGINX before reaching the application.

## How the module works
After authenticating, the following cookies are created:

usrtoken: is a sha1 + base64 signed cookie with a secret

usrid: is a base64 signed cookie representing the CAS username

## Configuration
Edit the nginx configuration: config/default

Replace $cas_server with your CAS ticket authentication URL

Replace $secret with a secretive token

## Example
The example rails application demonstrates how to verify the signed cookie


text:
package net.tutorial.service;

import net.tutorial.misc.FilenameInputStreamPair;
import net.tutorial.service.credential.ObjectStorageCredential;
import org.openstack4j.api.OSClient;
import org.openstack4j.model.common.Identifier;
import org.openstack4j.model.common.Payload;
import org.openstack4j.model.common.Payloads;
import org.openstack4j.model.storage.object.SwiftAccount;
import org.openstack4j.model.storage.object.SwiftObject;
import org.openstack4j.openstack.OSFactory;

import java.util.List;

/**
 * Created by pongpantola.
 */
public class ObjectStorageService {
    private OSClient os = null;
    private SwiftAccount account = null;

    public ObjectStorageService() {
        ObjectStorageCredential osCred = new ObjectStorageCredential();

        Identifier domainIdent = Identifier.byName(osCred.domainName);
        Identifier projectIdent = Identifier.byName(osCred.project);

        os = OSFactory.builderV3()
                .endpoint(osCred.auth_url)
                .credentials(osCred.userId, osCred.password)
                .scopeToProject(projectIdent, domainIdent)
                .authenticate();

        account = os.objectStorage().account().get();
    }

    public boolean createContainer(String cName) {
        return os.objectStorage().containers().create(cName).isSuccess();
    }

    public boolean deleteContainer(String cName) {
        return os.objectStorage().containers().delete(cName).isSuccess();
    }

    public String putFile(String cName, String fName, Payload payload) {
        return os.objectStorage().objects().put(cName, fName, payload);
    }

    public boolean deleteFile(String cName, String fName) {
        return os.objectStorage().objects().delete(cName, fName).isSuccess();
    }

    private SwiftObject getSwiftObject(String cName, String fName) {
        return os.objectStorage().objects().get(cName, fName);
    }

    /*
    public SwiftAccount getAccount() {
        account = os.objectStorage().account().get();
        return account;
    }*/

    public List<? extends SwiftObject> listAllObjects(String cName) {
        return os.objectStorage().objects().list(cName);
    }

    public String putFile(String cName, FilenameInputStreamPair fiPair) {
        Payload payload = Payloads.create(fiPair.getInputStream());
        return putFile(cName, fiPair.getFilename(), payload);
    }

    public FilenameInputStreamPair getFile(String cName, String fName) {
        SwiftObject swiftObj = getSwiftObject(cName, fName);
        FilenameInputStreamPair fiPair = new FilenameInputStreamPair(swiftObj.getName(), swiftObj.download().getInputStream(), swiftObj.getMimeType());
        return fiPair;
    }

    /*
    public String uploadFile(String cName, HttpServletRequest request) {
        FilenameInputStreamPair fiPair = HTTPUtility.upload(request);
        Payload payload = Payloads.create(fiPair.getInputStream());
        return putFile(cName, fiPair.getFilename(), payload);
    }

    public String uploadFile(String cName, String fName, HttpServletRequest request) {
        FilenameInputStreamPair fiPair = HTTPUtility.upload(request);
        Payload payload = Payloads.create(fiPair.getInputStream());
        return putFile(cName, fName, payload);
    }

    public void downloadFile(String cName, String fName, HttpServletResponse response) {
        SwiftObject swiftObj = getFile(cName, fName);
        FilenameInputStreamPair fiPair = new FilenameInputStreamPair(swiftObj.getName(), swiftObj.download().getInputStream(), swiftObj.getMimeType());
        HTTPUtility.download(fiPair, response);
    }
    */

}


text:
package com.helger.commons.collection.impl;

import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;

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

import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.CollectionHelper;

/**
 * A special ordered {@link Set} based interface with extended functionality
 * based on {@link ICommonsSet}.
 *
 * @author Philip Helger
 * @param <ELEMENTTYPE>
 *        Set element type
 */
public interface ICommonsOrderedSet <ELEMENTTYPE> extends ICommonsSet <ELEMENTTYPE>
{
  @Override
  @Nonnull
  @ReturnsMutableCopy
  default <T> ICommonsOrderedSet <T> createInstance ()
  {
    return new CommonsLinkedHashSet <> ();
  }

  @Override
  @Nonnull
  @ReturnsMutableCopy
  default ICommonsOrderedSet <ELEMENTTYPE> getAll (@Nullable final Predicate <? super ELEMENTTYPE> aFilter)
  {
    if (aFilter == null)
      return getClone ();

    final ICommonsOrderedSet <ELEMENTTYPE> ret = createInstance ();
    findAll (aFilter, ret::add);
    return ret;
  }

  @Override
  @Nonnull
  @ReturnsMutableCopy
  default <DSTTYPE> ICommonsOrderedSet <DSTTYPE> getAllMapped (@Nonnull final Function <? super ELEMENTTYPE, DSTTYPE> aMapper)
  {
    final ICommonsOrderedSet <DSTTYPE> ret = createInstance ();
    findAllMapped (aMapper, ret::add);
    return ret;
  }

  @Override
  @Nonnull
  @ReturnsMutableCopy
  default <DSTTYPE> ICommonsOrderedSet <DSTTYPE> getAllMapped (@Nullable final Predicate <? super ELEMENTTYPE> aFilter,
                                                               @Nonnull final Function <? super ELEMENTTYPE, DSTTYPE> aMapper)
  {
    final ICommonsOrderedSet <DSTTYPE> ret = createInstance ();
    findAllMapped (aFilter, aMapper, ret::add);
    return ret;
  }

  @Override
  @Nonnull
  @ReturnsMutableCopy
  default <DSTTYPE extends ELEMENTTYPE> ICommonsOrderedSet <DSTTYPE> getAllInstanceOf (@Nonnull final Class <DSTTYPE> aDstClass)
  {
    final ICommonsOrderedSet <DSTTYPE> ret = createInstance ();
    findAllInstanceOf (aDstClass, ret::add);
    return ret;
  }

  @Nullable
  default ELEMENTTYPE getFirst ()
  {
    return getFirst (null);
  }

  @Nullable
  default ELEMENTTYPE getFirst (@Nullable final ELEMENTTYPE aDefault)
  {
    return isEmpty () ? aDefault : iterator ().next ();
  }

  @Nullable
  default ELEMENTTYPE getLast ()
  {
    return getLast (null);
  }

  @Nullable
  default ELEMENTTYPE getLast (@Nullable final ELEMENTTYPE aDefault)
  {
    return isEmpty () ? aDefault : CollectionHelper.getLastElement (this);
  }

  @Nonnull
  @ReturnsMutableCopy
  ICommonsOrderedSet <ELEMENTTYPE> getClone ();
}


text:
using System;
using System.Linq;
using IrcD.Modes.UserModes;

namespace IrcD.Core
{
    public class ServerStats
    {
        readonly IrcDaemon _ircDaemon;

        public ServerStats(IrcDaemon ircDaemon)
        {
            _ircDaemon = ircDaemon;
        }

        public int ServerCount
        {
            get
            {
                return 1;
            }
        }

        public int ServiceCount
        {
            get
            {
                return _ircDaemon.Sockets.Count(s => s.Value.IsService);
            }
        }

        public int UserCount => _ircDaemon.Nicks.Count - ServiceCount;

        public int OperatorCount
        {
            get
            {
                return _ircDaemon.Sockets.Count(s => s.Value.Modes.Exist<ModeOperator>());
            }
        }

        public int LocalOperatorCount
        {
            get
            {
                return _ircDaemon.Sockets.Count(s => s.Value.Modes.Exist<ModeLocalOperator>());
            }
        }

        public int UnknowConnectionCount
        {
            get
            {
                return _ircDaemon.Sockets.Count(s => !s.Value.IsAcceptSocket);
            }
        }

        public int ChannelCount => _ircDaemon.Channels.Count;

        public int ClientCount => _ircDaemon.Nicks.Count;

        public TimeSpan Uptime => DateTime.Now - _ircDaemon.ServerCreated;
    }
}


text:
package org.efaps.ui.wicket.pages.content.grid;

import java.util.UUID;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.efaps.admin.dbproperty.DBProperties;
import org.efaps.ui.wicket.components.FormContainer;
import org.efaps.ui.wicket.components.footer.FooterPanel;
import org.efaps.ui.wicket.components.gridx.GridXPanel;
import org.efaps.ui.wicket.components.modalwindow.ModalWindowContainer;
import org.efaps.ui.wicket.models.objects.PagePosition;
import org.efaps.ui.wicket.models.objects.grid.UIGrid;
import org.efaps.ui.wicket.pages.AbstractMergePage;
import org.efaps.ui.wicket.pages.content.AbstractContentPage;
import org.efaps.ui.wicket.resources.AbstractEFapsHeaderItem;
import org.efaps.ui.wicket.resources.EFapsContentReference;
import org.efaps.util.EFapsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class GridPage.
 *
 * @author The eFaps Team
 */
public class GridPage
    extends AbstractMergePage
{

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /**
     * Reference to the style sheet.
     */
    private static final EFapsContentReference CSS = new EFapsContentReference(GridPage.class, "GridPage.css");

    /**
     * Logging instance used in this class.
     */
    private static final Logger LOG = LoggerFactory.getLogger(GridPage.class);

    public GridPage(final PageParameters _pageParameters)
    {
        this(Model.of(UIGrid.get(UUID.fromString(_pageParameters.get("id").toString()), PagePosition.CONTENT)), null);
    }

    /**
     * Instantiates a new grid page.
     *
     * @param _model the model
     */
    public GridPage(final IModel<UIGrid> _model)
    {
        this(_model, null);
    }

    /**
     * Instantiates a new grid page.
     *
     * @param _model the model
     * @param _modal the modal window this page is opened in to have a handle on it
     */
    public GridPage(final IModel<UIGrid> _model,
                    final ModalWindowContainer _modal)
    {
        super(_model);
        try {
            add2Page(new Label("pageTitle", DBProperties.getProperty("Logo.Version.Label")));
            add(new Label("titel", _model.getObject().getTitle()));
            add(new ModalWindowContainer("modal"));

            final FormContainer form = new FormContainer("form")
            {

                /** The Constant serialVersionUID. */
                private static final long serialVersionUID = 1L;

                @Override
                protected void onComponentTag(final ComponentTag _tag)
                {
                    super.onComponentTag(_tag);
                    _tag.put("action", "");
                }
            };
            add(form);

            @SuppressWarnings("unchecked")
            final GridXPanel panel = new GridXPanel("gridPanel", (IModel<UIGrid>) getDefaultModel());
            form.add(panel);

            final UIGrid uiGrid = (UIGrid) getDefaultModelObject();
            switch (uiGrid.getCommand().getTargetMode()) {
                case CONNECT:
                case SEARCH:
                    form.add(new FooterPanel("footer", Model.of(uiGrid), _modal));
                    break;
                default:
                    form.add(new WebMarkupContainer("footer").setVisible(false));
                    break;
            }
        } catch (final EFapsException e) {
            GridPage.LOG.error("Catched", e);
        }
    }

    @Override
    public void renderHead(final IHeaderResponse _response)
    {
        super.renderHead(_response);
        _response.render(AbstractEFapsHeaderItem.forCss(GridPage.CSS));
        _response.render(AbstractEFapsHeaderItem.forCss(AbstractContentPage.CSS));
    }
}


text:
EDeNseq is a tool for fast clustering and classification of (metagenomics) reads.

# 1. Installation

EDeNseq requires C++11 support! GCC 4.8 should be sufficient.

1. clone or download EDeNseq

	`git clone https://github.com/steffenheyne/EDeNseq.git`

2. Then change into source folder: `cd EDeNseq/src`

3. Build it with: `make`  - that's it!

# 2. Example: classify metagenomic reads against bacterial genomes

The folder [`test_data/`](https://github.com/steffenheyne/EDeNseq/blob/master/test_data/)
contains the test files for the following test run (please adapt path names):

```EDeNseq -a CLASSIFY -i test_data/test.reads.fna.gz
--index_seqs test_data/test.genomes.fa.gz  --index_bed test_data/test.small.bed
--numThreads 4  -b 30 -F 5 --num_hash_shingles 3 --num_repeat_hash_functions 3
-r 4 -d 7 --min_radius 4 --min_distance 7 --seq_window 70 --index_seq_shift 10
--seq_shift 9 --pure_approximate_sim 0```

- [**`test_data/test.reads.fna.gz`**](https://github.com/steffenheyne/EDeNseq/blob/master/test_data/test.reads.fna.gz) contains 231.578 sequences (100nt) sampled from 29 bacterial chromosomes
- [**`test_data/test.genomes.fa.gz`**](https://github.com/steffenheyne/EDeNseq/blob/master/test_data/test.genomes.fa.gz) contains 62 bacterial chromosomes
- [**`test_data/test.small.bed`**](https://github.com/steffenheyne/EDeNseq/blob/master/test_data/test.small.bed)
indicates regions from the genomes that will be indexed and against that reads are classified.
In the given example BED file, column 4 contains the taxonomic id (NCBI) at the organism level.
Although there are 62 different entries/sequences given, they map to only 29 organisms.
Hence, reads are classified between these 29 organisms. The output file [**`test.reads.fna.gz.classified.tab.gz`**](https://github.com/steffenheyne/EDeNseq/blob/master/test_data/test.reads.fna.gz.classified.tab.txt)
gives a mapping table in the header.

- The command above produces the index file **`test.small.bed.bhi`** and a results file **`test.reads.fna.gz.classified.tab.gz`**.
An example output is shown in
[**`test_data/test.reads.fna.gz.classified.tab.txt`**](https://github.com/steffenheyne/EDeNseq/blob/master/test_data/test.reads.fna.gz.classified.tab.txt)
When re-running the same command the existing index file (*.bhi) is used and not created again.
All lines in the result file starting with "#" are header lines.
The tags "#HIST_IDX" give the mapping between the internal ID and the
feature ID provided in the BED file.

- [**`test_data/test.log`**](https://github.com/steffenheyne/EDeNseq/blob/master/test_data/test.log) shows the terminal output of the above example

# 3. Sequence Classification

EDeNseq classifies sequences (e.g. reads) against an index of genomes or
any desired set of target sequences.

Sequence classifciation mode is started with

```EdENseq -a CLASSIFY```

Please see all available parameters with

```EdENseq -a CLASSIFY -h``` or ```EdENseq -a CLASSIFY -H```

## 3.1 Build the Index

### 3.1.1 Index BED File

In order to build the index, EDeNseq needs a BED file and fasta file.
The BED file is used to define regions on sequences that are
indexed under a certain label.

The labeling makes the whole classification procedure very powerful and
general, as this can be the sequence name (BED column 1) or a certain feature
identifier (BED file column 4). This allows to index different
sequences under the same label. For example, genomes of different
strains or related organisms, homologue transcripts or sequences of a certain
RNA family (Rfam).

The BED file has the following format:

`<SEQNAME>	<START>	<END>	<LABEL>	0	.	<SEQ_DESC>	<LABEL_DESC>`

The first 4 cols are required. Columns 7 and 8 are optional, but then also
columns 5 and 6 have to be provided.

`<LABEL>` can be any string or number. Internally each unique label is mapped to
a number.

`<LABEL_DESC>` is used to annotate the results.

During indexing, EDeNseq scans through the fasta file and for each found seq,
it selects all provided regions in BED file for that sequence and index them.
This means also that nothing is indexed for a seq without BED entry as well as
if there is a BED entry without sequence in the FASTA file.

### 3.1.2 Create BED file for large fasta file

One can use samtools for this purpose: `samtools faidx my_genomes.fa.gz`

Then best use `awk` or a simlar tool to get the columns in the right order!

### 3.1.3 Index Parameters

## 3.2 Sequences for Classification

## 3.3 Result Output

# 4. Sequence Clustering

EDeNseq can be used to cluster large-scale sequence dataset.

In clustering mode, no BED file is necessary and all
provided sequences are used!

**NOTE:** Clustering is under development!

# Notes

## Download bacterial reference genomes from NCBI

Here is an example about creating the index file for bacterial reference genomes.

1. Get table with reference genomes from NCBI ftp server (prok_reference_genomes.txt)
2. Download latest version for each refseq entry via eutils in fasta format, zip it and save it in $outdir

`wget ftp://ftp.ncbi.nlm.nih.gov/genomes/GENOME_REPORTS/prok_reference_genomes.txt`

`outdir="refseq_bact_genomes"; mkdir -p $outdir;`

`for i in $(cat prok_reference_genomes.txt | awk '{FS="\t";OFS="\t";if (NR==1) next; split($4,CHR,","); for (i in CHR){gsub(" ","_",$3);print CHR[i]}}'); do
	get "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nuccore&id="$i"&rettype=fasta&retmode=text" -q -O - | gzip > $outdir/$i.fa.gz;
done`


text:
class AddImageUrlColumnToText < ActiveRecord::Migration[5.1]
  def change
    add_column :texts, :image_url, :string
  end
end


text:
package com.avalara.avatax.services.avacert2;

import java.util.Calendar;
import java.util.Date;

public class CertificateRequestGetRequest  implements java.io.Serializable {

    /**
     * Company Code
     */
    private java.lang.String companyCode;

    /**
     * Customer Code
     */
    private java.lang.String customerCode;
    /**
     * Request Status
     */
    private CertificateRequestStatus requestStatus;
    /**
     * From Date
     */
    private java.util.Calendar modFromDate;

    /**
     * To Date
     */
    private java.util.Calendar modToDate;

     /**
     * Method to initialize the Object of CertificateRequestGetRequest Class with default values
     */
    public CertificateRequestGetRequest() {

        requestStatus= CertificateRequestStatus.ALL;
        Calendar fromDate = Calendar.getInstance();
        Calendar toDate = Calendar.getInstance();
        fromDate.set(1,0,1,0,0,0);
        toDate.set(9999,11,31,23,59,59);
        this.modFromDate=fromDate;
        this.modToDate=toDate;

    }

    /**
     *  Method to initialize the Object of CertificateRequestGetRequest Class with parametrised values
     * @param companyCode
     * @param customerCode
     * @param requestStatus
     * @param modFromDate
     * @param modToDate
     */
    public CertificateRequestGetRequest(
           java.lang.String companyCode,
           java.lang.String customerCode,
           CertificateRequestStatus requestStatus,
           java.util.Calendar modFromDate,
           java.util.Calendar modToDate) {
           this.companyCode = companyCode;
           this.customerCode = customerCode;
           this.requestStatus = requestStatus;
           this.modFromDate = modFromDate;
           this.modToDate = modToDate;
    }

    /**
     * Gets the companyCode value for this CertificateRequestGetRequest.
     *
     * @return companyCode
     */
    public java.lang.String getCompanyCode() {
        return companyCode;
    }

    /**
     * Sets the companyCode value for this CertificateRequestGetRequest.
     *
     * @param companyCode
     */
    public void setCompanyCode(java.lang.String companyCode) {
        this.companyCode = companyCode;
    }

    /**
     * Gets the customerCode value for this CertificateRequestGetRequest.
     *
     * @return customerCode
     */
    public java.lang.String getCustomerCode() {
        return customerCode;
    }

    /**
     * Sets the customerCode value for this CertificateRequestGetRequest.
     *
     * @param customerCode
     */
    public void setCustomerCode(java.lang.String customerCode) {
        this.customerCode = customerCode;
    }

    /**
     * Gets the requestStatus value for this CertificateRequestGetRequest.
     *
     * @return requestStatus
     */
    public CertificateRequestStatus getRequestStatus() {
        return requestStatus;
    }

    /**
     * Sets the requestStatus value for this CertificateRequestGetRequest.
     *
     * @param requestStatus
     */
    public void setRequestStatus(CertificateRequestStatus requestStatus) {
        this.requestStatus = requestStatus;
    }

    /**
     * Gets the modFromDate value for this CertificateRequestGetRequest.
     *
     * @return modFromDate
     */
    public java.util.Calendar getModFromDate() {
        return modFromDate;
    }

    /**
     * Sets the modFromDate value for this CertificateRequestGetRequest.
     *
     * @param modFromDate
     */
    public void setModFromDate(java.util.Calendar modFromDate) {
        this.modFromDate = modFromDate;
    }

    /**
     * Gets the modToDate value for this CertificateRequestGetRequest.
     *
     * @return modToDate
     */
    public java.util.Calendar getModToDate() {
        return modToDate;
    }

    /**
     * Sets the modToDate value for this CertificateRequestGetRequest.
     *
     * @param modToDate
     */
    public void setModToDate(java.util.Calendar modToDate) {
        this.modToDate = modToDate;
    }

    private java.lang.Object __equalsCalc = null;

      /**
     * Determines whether the specified Object is equal to the current Object.
     * Note: In current implementation all Java Strings members of the two
     * objects must be exactly alike, including in case, for equal to return true.
     * @param obj
     * @return true or false, indicating if the two objects are equal.
     */
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof CertificateRequestGetRequest)) return false;
        CertificateRequestGetRequest other = (CertificateRequestGetRequest) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.companyCode==null && other.getCompanyCode()==null) ||
             (this.companyCode!=null &&
              this.companyCode.equals(other.getCompanyCode()))) &&
            ((this.customerCode==null && other.getCustomerCode()==null) ||
             (this.customerCode!=null &&
              this.customerCode.equals(other.getCustomerCode()))) &&
            ((this.requestStatus==null && other.getRequestStatus()==null) ||
             (this.requestStatus!=null &&
              this.requestStatus.equals(other.getRequestStatus()))) &&
            ((this.modFromDate==null && other.getModFromDate()==null) ||
             (this.modFromDate!=null &&
              this.modFromDate.equals(other.getModFromDate()))) &&
            ((this.modToDate==null && other.getModToDate()==null) ||
             (this.modToDate!=null &&
              this.modToDate.equals(other.getModToDate())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;

     /**
        *  Serves as a hash function for a particular type,
        * suitable for use in hashing algorithms and data
        * structures like a hash table.
        * @return  hash code for this CertificateRequestGetRequest object
        * @see java.lang.Object#hashCode
        */
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getCompanyCode() != null) {
            _hashCode += getCompanyCode().hashCode();
        }
        if (getCustomerCode() != null) {
            _hashCode += getCustomerCode().hashCode();
        }
        if (getRequestStatus() != null) {
            _hashCode += getRequestStatus().hashCode();
        }
        if (getModFromDate() != null) {
            _hashCode += getModFromDate().hashCode();
        }
        if (getModToDate() != null) {
            _hashCode += getModToDate().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(CertificateRequestGetRequest.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CertificateRequestGetRequest"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("companyCode");
        elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CompanyCode"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("customerCode");
        elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CustomerCode"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("requestStatus");
        elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "RequestStatus"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CertificateRequestStatus"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("modFromDate");
        elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ModFromDate"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("modToDate");
        elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ModToDate"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}