text:
package io.loli.sc.server.social.weibo;

import io.loli.sc.server.social.parent.AuthInfo;
import io.loli.sc.server.social.parent.AuthManager;
import io.loli.sc.server.social.parent.UserInfo;
import io.loli.util.bean.Pair;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class WeiboAuthManager extends AuthManager {
    private String authUrl = null;
    private String tokenUrl = null;

    public WeiboAuthManager(AuthInfo info) {
        this.info = info;
        this.authUrl = "https://api.weibo.com/oauth2/authorize?client_id=" + info.getId()
            + "&response_type=code&redirect_uri=" + info.getUrl();
        this.tokenUrl = "https://api.weibo.com/oauth2/access_token?client_id=" + info.getId() + "&client_secret="
            + info.getSecret() + "&grant_type=authorization_code&redirect_uri=" + info.getUrl();
    }

    @Override
    public String getAuthUrl() {
        return authUrl;
    }

    @Override
    public Pair<String, Long> getAccessToken(String code) {
        tokenUrl = tokenUrl + "&code=" + code;
        String result = "";
        String accessToken = "";
        long timeout = 0l;
        try {
            result = this.post(tokenUrl, new ArrayList<>());
            if (StringUtils.isNotBlank(result)) {
                JSONObject obj = new JSONObject(result);
                try {
                    // 如果获取accession_token成功了,下面这句一定会抛出异常
                    String error = obj.getString("error");
                    logger.info("Result is not valid: result=[" + result + "], error is" + error);
                    throw new NullPointerException("Error occurred: " + error);
                } catch (JSONException e) {
                    accessToken = obj.getString("access_token");
                    timeout = obj.getLong("expires_in");
                }
            } else {
                throw new NullPointerException("Result is null while getting token");
            }
        } catch (IOException e) {
            logger.warning("Failed to get accesstoken, url=[" + tokenUrl + "], code=[" + code + "], error is: \n" + e);
        }

        return new Pair<>(accessToken, timeout);
    }

    @Override
    public String refresh(String token) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public UserInfo getUserInfo(String accessToken) {
        String uid = this.getUid(accessToken);
        return getUserInfoByUid(accessToken, uid);
    }

    private String getUid(String accessToken) {
        String userinfoUrl = "https://api.weibo.com/2/account/get_uid.json";
        userinfoUrl += "?access_token=" + accessToken;
        String result = "";
        try {
            result = this.get(userinfoUrl);
        } catch (IOException e) {
            logger.warning("Error occurred while get user info: " + e);
        }
        String id = "";
        if (StringUtils.isNotBlank(result)) {
            JSONObject obj = null;
            try {
                obj = new JSONObject(result);
                // 如果获取accession_token成功了,下面这句一定会抛出异常
                String error = obj.getString("error");
                logger.info("Result is not valid: result=[" + result + "], error is" + error);
                throw new NullPointerException("Error occurred: " + error);
            } catch (JSONException e) {
                id = String.valueOf(obj.getLong("uid"));
            }
        } else {
            throw new NullPointerException("id is null");
        }
        return id;
    }

    private UserInfo getUserInfoByUid(String accessToken, String uid) {
        String userinfoUrl = "https://api.weibo.com/2/users/show.json";
        userinfoUrl += "?access_token=" + accessToken + "&uid=" + uid;
        String result = "";
        try {
            result = this.get(userinfoUrl);
        } catch (IOException e) {
            logger.warning("Error occurred while get user info: " + e);
        }
        UserInfo info = new UserInfo();
        if (StringUtils.isNotBlank(result)) {
            JSONObject obj = null;
            try {
                obj = new JSONObject(result);

                // 如果获取accession_token成功了,下面这句一定会抛出异常
                String error = obj.getString("error");
                logger.info("Result is not valid: result=[" + result + "], error is" + error);
                throw new NullPointerException("Error occurred: " + error);
            } catch (JSONException e) {
                info.setId(uid);
                info.setUsername(obj.getString("screen_name"));
            }
        } else {
            throw new NullPointerException("id is null");
        }
        return info;
    }

    @Override
    public boolean cancel(String accessToken) {
        String cancelUrl = "https://api.weibo.com/oauth2/revokeoauth2" + "?access_token=" + accessToken;
        String result = "";
        try {
            result = this.get(cancelUrl);
        } catch (IOException e) {
            e.printStackTrace();
            logger.warning(e.getMessage());
        }
        JSONObject obj = new JSONObject(result);
        return "true".equals(obj.getString("result"));
    }
}


text:
/*
 * Macros, definitions, and data structures specific to the IBM PowerPC
 * STB03xxx "Redwood" evaluation board.
 *
 * Author: Armin Kuster <akuster@mvista.com>
 *
 * 2001 (c) MontaVista, Software, Inc.  This file is licensed under
 * the terms of the GNU General Public License version 2.  This program
 * is licensed "as is" without any warranty of any kind, whether express
 * or implied.
 */

#ifdef __KERNEL__
#ifndef __ASM_REDWOOD5_H__
#define __ASM_REDWOOD5_H__

/* Redwood5 has an STB04xxx core */
#include <platforms/4xx/ibmstb4.h>

#ifndef __ASSEMBLY__
typedef struct board_info {
	unsigned char	bi_s_version[4];	/* Version of this structure */
	unsigned char	bi_r_version[30];	/* Version of the IBM ROM */
	unsigned int	bi_memsize;		/* DRAM installed, in bytes */
	unsigned int	bi_dummy;		/* field shouldn't exist */
	unsigned char	bi_enetaddr[6];		/* Ethernet MAC address */
	unsigned int	bi_intfreq;		/* Processor speed, in Hz */
	unsigned int	bi_busfreq;		/* Bus speed, in Hz */
	unsigned int	bi_tbfreq;		/* Software timebase freq */
} bd_t;
#endif /* !__ASSEMBLY__ */

#define SMC91111_BASE_ADDR	0xf2000300
#define SMC91111_REG_SIZE	16
#define SMC91111_IRQ		28

#ifdef MAX_HWIFS
#undef MAX_HWIFS
#endif
#define MAX_HWIFS		1

#define _IO_BASE	0
#define _ISA_MEM_BASE	0
#define PCI_DRAM_OFFSET	0

#define BASE_BAUD		(378000000 / 18 / 16)

#define PPC4xx_MACHINE_NAME	"IBM Redwood5"

#endif /* __ASM_REDWOOD5_H__ */
#endif /* __KERNEL__ */

redpajama_set_name: RedPajamaGithub


text:
/*
 *
 * Default headers for API calls
 *
 */

function getDefaultHeders (state) {
  if (state && state.auth && state.auth.authToken) {
    return {
      Authorization: `Bearer ${state.auth.authToken}`,
    }
  }

  return {}
}

export default getDefaultHeders


text:
============
Installation
============

The app depends on PyWPS and several other libraries that are listed in
``requirements.txt``. It is advisable to run it using a python virtualenv to prevent package instalation problems::

    $ virtualenv -p python3 pywps_flask_env
    $ cd pywps_flask_dir
    $ . bin/activate
    $ git clone https://github.com/geopython/pywps-flask
    $ cd pywps-flask
    $ pip3 install -r requirements.txt

If python virtualenv is not an option::

    $ git clone https://github.com/geopython/pywps-flask
    $ cd pywps-flask
    $ pip3 install -r requirements.txt

For Debian based systems you will need to install GDAL with::

    $ sudo apt-get install python3-gdal

When using only using `requirement.txt`, the `pywps-flask` will run for the directory that was pulled from github, for a system wise installation is it advisable to use `setup.py`::

    $ git clone https://github.com/geopython/pywps-flask
    $ cd pywps-flask
    $ python3 setup.py install

=======
Running
=======

Simply run the python file::

    $ python3 demo.py -a

The flag `-a` will bind to the ip range `0.0.0.0` and is normally the safest option access to `pypwps-flask`

The `-d`  option will run pywps-flask as daemon and to stop it is necessary to determine the PID and kill it, one trick is to use fuser to determine PID, and then use it to kill the process::

    $ fuser tcp/5000
    $ kill -15 <PID RETURNED PREVIOUSLY>

==============
Docker  images
==============

The docker folder contains 2 subfolders, each subfolder contains a differente pywps implementation.

Folder ``flask``  has the default pywps-flask implementation using only Flask while folder ``nginx``  implements pywps using Nginx and Green unicorn as WSGI server. While folder ``ubuntu`` has the same images but using phusion image (ubuntu 18.04)

Flask-Alpine (basic)
--------------------

Basic pywps image is based on Alpine 3.8 and will run the native Flask service, this is not apropriate for production. The docker file can be found in: ``docker/alpine/flask/Dockerfile``

To build the image (inside the folder with the Dockerfile)::

    $ docker build -t pywps/flask-alpine .

And to run it::

    $ docker run -p 5000:5000 pywps/flask-alpine:latest

Pywps will be available in  the following URL::

    $ http://localhost:5000

Gunicorn-Alpine (production)
----------------------------

This image implements the previous ``flask-alpine image`` (you need to build it first, or it will be automatically pulled from dockerhub) but wrapping flask in a WSGI server (gunicorn) where each worker runs a an app. This image allows for the following environment variables:

 - GU_WORKERS - Numer or workers. Gunicorn uses a set of workers to run pywps (normally ``workers = (2 * cpu) + 1``).  (default: 5)
 - GU_PORT  - Port running Gunicorn (default:8081)

Gunicorn-Alpine is locate in folder ``docker/alpine/gunicorn/Dockerfile``

This image can already be implemented in production but it is advisable to use Nginx for HTTP load balance and Gunicorn as WSGI server (see below)

To build the image (inside the folder with the Dockerfile)::

    $ docker build -t pywps/gunicorn-alpine:latest .

And to run it::

    $ docker run -p 8081:8081 -it pywps/gunicorn-alpine:latest

or::

    $ docker run -e GU_WORKERS=10 -e GU_PORT=8082  -p 8082:8082 -it pywps/gunicorn-alpine:latest

Pywps will be available at the following URL::

    $ http://localhost:8082

Nginx-Alpine
------------

This is the complete stack intented for production, to have a stack we require to use ``docker-compose``
to build two images: ``pywps/gunicorn-alpine:latest``  and ``pywps/nginx-alpine:latest``

Those images will be pulled from dockerhub, but they can compiled locally by building Flask-Alpine, Gunicron-Alpine and Nginx-Alpine, in this case only showing for nginx::

   $ cd docker/alpine/nginx/Dockerfile
   $ docker build -t pywps/nginx-alpine:latest .

Then the stack can be started using docker compose::

   $ docker-compose up

In this case pywps (only the WPS) will be avalable on::

    http://localhost

Flask-Ubuntu (basic)
--------------------

The same as ``Flask-Ubuntu`` but using phusion image (ubuntu 18.04)::

    $ cd docker/ubuntu/flask
    $ docker build -t pywps/flask-ubuntu:latest .

And to run it::

    $ docker run -p 5000:5000 pywps/flask-ubuntu

Nginx-Ubuntu (production)
-------------------------

This image is based on ``Flask-Ubuntu`` and will require it (either build locally or pull from dockerhub). This image has Nginx and Gunicorn totally integrated as services in a docker image::

   $ cd docker/ubuntu/nginx
   $ docker build -t pywps/nginx-ubuntu .

And to run it::

   $ docker run -p 80:80 pywps/nginx-ubuntu

It is possible to set the number of Gunicorn workers:

* GU_WORKERS - Numer or workers.  (default: 5)

e.g::

   $ docker run -e GU_WORKERS=10 -p 80:80 pywps/nginx-ubuntu

Volumes
-------

Named volumes allow for container content to be available in the host system. The most important folders in pywps containers are:

* /pywps-flask/logs
* /pywps-flask/outputs
* /pywps-flask/processes

And file:
* /pywps-flask/pywps.cfg

Named volumes need to be created prior to ``docker run``::

    $ docker volume create pywps_logs
    $ docker volume create pywps_outputs
    $ docker volume create pywps_processes

To check the path on the host to volume and other information::

   $ docker volume ls pywps_processes

To run a docker will all the volumes available in the host::

  $ docker run -p 5000:5000 -v pywps_logs:/pywps-flask/pywps_logs \
                            -v pywps_outputs:/pywps-flask/pywps_outputs \
                            -v pywps_processes:/pywps-flask/pywps_processes \
                            -v pywps_cfg:/pywps-flask/pywps.cfg  pywps/flask-alpine:latest

THE END
=======


text:
{{game.title}}

Category:

{{game.category}}

{{game.price}}

        X
        <form class="col-md-12" ng-submit="mc.addNewDiscussion()">

Post and Play!

              Topic:
              <input class="form-inserts" name="topic" type="text" ng-model="mc.addTopic">

              Post Content:
              <textarea  class="form-inserts" name="comment" ng-model="mc.addPost"></textarea>

              <button class="form-submit" type="submit">Submit</button>

        </form>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
    <ModulePrefs title="Authorized Apps" >
        <Require feature="pubsub-2"/>
    </ModulePrefs>
    <Content type="html" view="default">
        <![CDATA[

        <link rel="stylesheet" type="text/css" href="js/ui/css/main.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/smoothness/jquery-ui-1.10.3.custom.min.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/smoothness/jqueryui-themeroller.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/dialog.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap-theme.css">

Manage your authorized applications.

View details

        ]]>
    </Content>

    <Content type="html" view="home">
        <![CDATA[

        <link rel="stylesheet" type="text/css" href="js/ui/css/main.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap-theme.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap-missing.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/bootstrap-theme.min.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/dialog.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/smoothness/jquery-ui-1.10.3.custom.min.css">
        <link rel="stylesheet" type="text/css" href="js/ui/css/smoothness/jqueryui-themeroller.css">

        <form id="gadgetForm" class="form-horizontal">

        </form>
        ]]>
    </Content>
</Module>


text:
package com.wedian.site.common.template.directive;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wedian.site.common.utils.Filter;
import com.wedian.site.common.utils.FreemarkerUtils;
import com.wedian.site.common.utils.Order;
import com.wedian.site.common.utils.StringUtils;
import org.apache.commons.beanutils.PropertyUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang3.ArrayUtils;

/**
 * 模板指令 - 基类
 *
 * @author wanliang Team
 * @version 3.0
 */
public abstract class BaseDirective implements TemplateDirectiveModel {

	/** "使用缓存"参数名称 */
	private static final String USE_CACHE_PARAMETER_NAME = "useCache";
	/** "缓存区域"参数名称 */
	private static final String CACHE_REGION_PARAMETER_NAME = "cacheRegion";
	/** "ID"参数名称 */
	private static final String ID_PARAMETER_NAME = "id";
	/** "数量"参数名称 */
	private static final String COUNT_PARAMETER_NAME = "count";
	/** "排序"参数名称 */
	private static final String ORDER_BY_PARAMETER_NAME = "orderBy";
	/** 排序项分隔符 */
	private static final String ORDER_BY_ITEM_SEPARATOR = "\\s*,\\s*";
	/** 排序字段分隔符 */
	private static final String ORDER_BY_FIELD_SEPARATOR = "\\s+";

	/**
	 * 使用缓存
	 *
	 * @param env
	 *            Environment
	 * @param params
	 *            参数
	 * @return 使用缓存
	 */
	protected boolean useCache(Environment env, Map<String, TemplateModel> params) throws TemplateModelException {
		Boolean useCache = FreemarkerUtils.getParameter(USE_CACHE_PARAMETER_NAME, Boolean.class, params);
		return useCache != null ? useCache : true;
	}

	/**
	 * 获取缓存区域
	 *
	 * @param env
	 *            Environment
	 * @param params
	 *            参数
	 * @return 缓存区域
	 */
	protected String getCacheRegion(Environment env, Map<String, TemplateModel> params) throws TemplateModelException {
		String cacheRegion = FreemarkerUtils.getParameter(CACHE_REGION_PARAMETER_NAME, String.class, params);
		return cacheRegion != null ? cacheRegion : env.getTemplate().getName();
	}

	/**
	 * 获取ID
	 *
	 * @param params
	 *            参数
	 * @return ID
	 */
	protected Long getId(Map<String, TemplateModel> params) throws TemplateModelException {
		return FreemarkerUtils.getParameter(ID_PARAMETER_NAME, Long.class, params);
	}

	/**
	 * 获取数量
	 *
	 * @param params
	 *            参数
	 * @return 数量
	 */
	protected Integer getCount(Map<String, TemplateModel> params) throws TemplateModelException {
		return FreemarkerUtils.getParameter(COUNT_PARAMETER_NAME, Integer.class, params);
	}

	/**
	 * 获取筛选
	 *
	 * @param params
	 *            参数
	 * @param type
	 *            参数类型
	 * @param ignoreProperties
	 *            忽略属性
	 * @return 筛选
	 */
	protected List<Filter> getFilters(Map<String, TemplateModel> params, Class<?> type, String... ignoreProperties) throws TemplateModelException {
		List<Filter> filters = new ArrayList<Filter>();
		PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
		for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
			String propertyName = propertyDescriptor.getName();
			Class<?> propertyType = propertyDescriptor.getPropertyType();
			if (!ArrayUtils.contains(ignoreProperties, propertyName) && params.containsKey(propertyName)) {
				Object value = FreemarkerUtils.getParameter(propertyName, propertyType, params);
				filters.add(Filter.eq(propertyName, value));
			}
		}
		return filters;
	}

	/**
	 * 获取排序
	 *
	 * @param params
	 *            参数
	 * @param ignoreProperties
	 *            忽略属性
	 * @return 排序
	 */
	protected List<Order> getOrders(Map<String, TemplateModel> params, String... ignoreProperties) throws TemplateModelException {
		String orderBy = StringUtils.trim(FreemarkerUtils.getParameter(ORDER_BY_PARAMETER_NAME, String.class, params));
		List<Order> orders = new ArrayList<Order>();
		if (StringUtils.isNotEmpty(orderBy)) {
			String[] orderByItems = orderBy.split(ORDER_BY_ITEM_SEPARATOR);
			for (String orderByItem : orderByItems) {
				if (StringUtils.isNotEmpty(orderByItem)) {
					String property = null;
					Order.Direction direction = null;
					String[] orderBys = orderByItem.split(ORDER_BY_FIELD_SEPARATOR);
					if (orderBys.length == 1) {
						property = orderBys[0];
					} else if (orderBys.length >= 2) {
						property = orderBys[0];
						try {
							direction = Order.Direction.valueOf(orderBys[1]);
						} catch (IllegalArgumentException e) {
							continue;
						}
					} else {
						continue;
					}
					if (!ArrayUtils.contains(ignoreProperties, property)) {
						orders.add(new Order(property, direction));
					}
				}
			}
		}
		return orders;
	}

	/**
	 * 设置局部变量
	 *
	 * @param name
	 *            名称
	 * @param value
	 *            变量值
	 * @param env
	 *            Environment
	 * @param body
	 *            TemplateDirectiveBody
	 */
	protected void setLocalVariable(String name, Object value, Environment env, TemplateDirectiveBody body) throws TemplateException, IOException {
		TemplateModel sourceVariable = FreemarkerUtils.getVariable(name, env);
		FreemarkerUtils.setVariable(name, value, env);
		body.render(env.getOut());
		FreemarkerUtils.setVariable(name, sourceVariable, env);
	}

	/**
	 * 设置局部变量
	 *
	 * @param variables
	 *            变量
	 * @param env
	 *            Environment
	 * @param body
	 *            TemplateDirectiveBody
	 */
	protected void setLocalVariables(Map<String, Object> variables, Environment env, TemplateDirectiveBody body) throws TemplateException, IOException {
		Map<String, Object> sourceVariables = new HashMap<String, Object>();
		for (String name : variables.keySet()) {
			TemplateModel sourceVariable = FreemarkerUtils.getVariable(name, env);
			sourceVariables.put(name, sourceVariable);
		}
		FreemarkerUtils.setVariables(variables, env);
		body.render(env.getOut());
		FreemarkerUtils.setVariables(sourceVariables, env);
	}

}


text:
#pragma once
#include <BWAPI.h>
#include <BWSAL/UnitGroup.h>
namespace BWSAL
{
  /*! \brief
   *  Monitors unit creation, discovery/evasion etc and maintains indexed lists of all visible units.
   *  Proides fast and straightforward ways to query for various subsets of the set of visible units.
   */
  class UnitGroupManager : public BWAPI::AIModule
  {
    public:
      static UnitGroupManager* create();
      static UnitGroupManager* getInstance();
      static void destroy();
      virtual void onUnitDiscover( BWAPI::Unit unit );
      virtual void onUnitEvade( BWAPI::Unit unit );
      virtual void onUnitMorph( BWAPI::Unit unit );
      virtual void onUnitRenegade( BWAPI::Unit unit );
      friend UnitGroup AllUnits();
      friend UnitGroup SelectAll();
      friend UnitGroup SelectAll( BWAPI::UnitType type );
      friend UnitGroup SelectAllEnemy();
      friend UnitGroup SelectAllEnemy( BWAPI::UnitType type );
      friend UnitGroup SelectAll( BWAPI::Player player, BWAPI::UnitType type );
    private:
      UnitGroupManager();
      ~UnitGroupManager();
      std::map< BWAPI::Unit, BWAPI::Player > unitOwner;
      std::map< BWAPI::Unit, BWAPI::UnitType > unitType;
      std::map< BWAPI::Player, std::map< BWAPI::UnitType, UnitGroup > > data;
      std::map< BWAPI::Player, UnitGroup > allOwnedUnits;
      UnitGroup allUnits;
      BWAPI::Player neutral;
      static UnitGroupManager* s_UnitGroupManager;
  };

  //! Return a UnitGroup containing all visible units
  UnitGroup AllUnits();

  //! Return a UnitGroup containing all (owned) visible units
  UnitGroup SelectAll();

  //! Return a UnitGroup containing all (owned) visible units of this UnitType
  UnitGroup SelectAll( BWAPI::UnitType type );

  //! Return a UnitGroup containing all visible enemy units
  UnitGroup SelectAllEnemy();

  //! Return a UnitGroup containing all visible enemy units of this UnitType
  UnitGroup SelectAllEnemy( BWAPI::UnitType type );

  //! Return a UnitGroup containing all visible units owned by the provided Player of this UnitType
  UnitGroup SelectAll( BWAPI::Player player, BWAPI::UnitType type );
}


text:
/*======================================================================
 FILE: ICalPeriodType.java
 CREATOR: structConverter 01/11/02
======================================================================*/

package net.cp.jlibical;

public class ICalPeriodType
{
	public ICalPeriodType(long obj)
	{
		init(obj);
	}

	public ICalPeriodType()
	{
	}

	public ICalPeriodType(long aStart, long aEnd, long aDuration)
	{
		init(aStart, aEnd, aDuration);
	}

	public void setStart(ICalTimeType lcl_arg0)
	{
		start = lcl_arg0;
	}
	public ICalTimeType getStart()
	{
		return start;
	}

	public void setEnd(ICalTimeType lcl_arg0)
	{
		end = lcl_arg0;
	}
	public ICalTimeType getEnd()
	{
		return end;
	}

	public void setDuration(ICalDurationType lcl_arg0)
	{
		duration = lcl_arg0;
	}
	public ICalDurationType getDuration()
	{
		return duration;
	}

	private void init(long aStart, long aEnd, long aDuration)
	{
		start = new ICalTimeType(aStart);
		end = new ICalTimeType(aEnd);
		duration = new ICalDurationType(aDuration);
	}

	private native void init(long obj);

    private native static void initFIDs();

    static {
		System.loadLibrary("ical_jni");
		initFIDs();
    }

	private ICalTimeType		start = new ICalTimeType();
	private ICalTimeType		end = new ICalTimeType();
	private ICalDurationType	duration = new ICalDurationType();
}


text:
.class Lcom/android/gallery3d/app/MoviePlayer$12;
.super Ljava/lang/Object;
.source "MoviePlayer.java"

# interfaces
.implements Landroid/view/View$OnTouchListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/gallery3d/app/MoviePlayer;->init(Lcom/android/gallery3d/app/MovieActivity;Lcom/mediatek/gallery3d/ext/IMovieItem;Z)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/gallery3d/app/MoviePlayer;

# direct methods
.method constructor <init>(Lcom/android/gallery3d/app/MoviePlayer;)V
    .locals 0
    .parameter

    .prologue
    .line 762
    iput-object p1, p0, Lcom/android/gallery3d/app/MoviePlayer$12;->this$0:Lcom/android/gallery3d/app/MoviePlayer;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onTouch(Landroid/view/View;Landroid/view/MotionEvent;)Z
    .locals 1
    .parameter "v"
    .parameter "event"

    .prologue
    .line 765
    iget-object v0, p0, Lcom/android/gallery3d/app/MoviePlayer$12;->this$0:Lcom/android/gallery3d/app/MoviePlayer;

    #getter for: Lcom/android/gallery3d/app/MoviePlayer;->mController:Lcom/android/gallery3d/app/MovieControllerOverlay;
    invoke-static {v0}, Lcom/android/gallery3d/app/MoviePlayer;->access$100(Lcom/android/gallery3d/app/MoviePlayer;)Lcom/android/gallery3d/app/MovieControllerOverlay;

    move-result-object v0

    invoke-virtual {v0}, Lcom/android/gallery3d/app/MovieControllerOverlay;->show()V

    .line 766
    const/4 v0, 0x1

    return v0
.end method


text:
PSBTAnalysis AnalyzePSBT(PartiallySignedTransaction psbtx)
{
    // Go through each input and build status
    PSBTAnalysis result;

    bool calc_fee = true;

    CAmount in_amt = 0;

    result.inputs.resize(psbtx.tx->vin.size());

    for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
        PSBTInput& input = psbtx.inputs[i];
        PSBTInputAnalysis& input_analysis = result.inputs[i];

        // We set next role here and ratchet backwards as required
        input_analysis.next = PSBTRole::EXTRACTOR;

        // Check for a UTXO
        CTxOut utxo;
        if (psbtx.GetInputUTXO(utxo, i)) {
            if (!MoneyRange(utxo.nValue) || !MoneyRange(in_amt + utxo.nValue)) {
                result.SetInvalid(strprintf("PSBT is not valid. Input %u has invalid value", i));
                return result;
            }
            in_amt += utxo.nValue;
            input_analysis.has_utxo = true;
        } else {
            if (input.non_witness_utxo && psbtx.tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
                result.SetInvalid(strprintf("PSBT is not valid. Input %u specifies invalid prevout", i));
                return result;
            }
            input_analysis.has_utxo = false;
            input_analysis.is_final = false;
            input_analysis.next = PSBTRole::UPDATER;
            calc_fee = false;
        }

        if (!utxo.IsNull() && utxo.scriptPubKey.IsUnspendable()) {
            result.SetInvalid(strprintf("PSBT is not valid. Input %u spends unspendable output", i));
            return result;
        }

        // Check if it is final
        if (!utxo.IsNull() && !PSBTInputSigned(input)) {
            input_analysis.is_final = false;

            // Figure out what is missing
            SignatureData outdata;
            bool complete = SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, 1, &outdata);

            // Things are missing
            if (!complete) {
                input_analysis.missing_pubkeys = outdata.missing_pubkeys;
                input_analysis.missing_redeem_script = outdata.missing_redeem_script;
                input_analysis.missing_witness_script = outdata.missing_witness_script;
                input_analysis.missing_sigs = outdata.missing_sigs;

                // If we are only missing signatures and nothing else, then next is signer
                if (outdata.missing_pubkeys.empty() && outdata.missing_redeem_script.IsNull() && outdata.missing_witness_script.IsNull() && !outdata.missing_sigs.empty()) {
                    input_analysis.next = PSBTRole::SIGNER;
                } else {
                    input_analysis.next = PSBTRole::UPDATER;
                }
            } else {
                input_analysis.next = PSBTRole::FINALIZER;
            }
        } else if (!utxo.IsNull()){
            input_analysis.is_final = true;
        }
    }

    // Calculate next role for PSBT by grabbing "minimum" PSBTInput next role
    result.next = PSBTRole::EXTRACTOR;
    for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
        PSBTInputAnalysis& input_analysis = result.inputs[i];
        result.next = std::min(result.next, input_analysis.next);
    }
    assert(result.next > PSBTRole::CREATOR);

    if (calc_fee) {
        // Get the output amount
        CAmount out_amt = std::accumulate(psbtx.tx->vout.begin(), psbtx.tx->vout.end(), CAmount(0),
            [](CAmount a, const CTxOut& b) {
                if (!MoneyRange(a) || !MoneyRange(b.nValue) || !MoneyRange(a + b.nValue)) {
                    return CAmount(-1);
                }
                return a += b.nValue;
            }
        );
        if (!MoneyRange(out_amt)) {
            result.SetInvalid(strprintf("PSBT is not valid. Output amount invalid"));
            return result;
        }

        // Get the fee
        CAmount fee = in_amt - out_amt;
        result.fee = fee;

        // Estimate the size
        CMutableTransaction mtx(*psbtx.tx);
        CCoinsView view_dummy;
        CCoinsViewCache view(&view_dummy);
        bool success = true;

        for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
            PSBTInput& input = psbtx.inputs[i];
            Coin newcoin;

            if (!SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, 1, nullptr, true) || !psbtx.GetInputUTXO(newcoin.out, i)) {
                success = false;
                break;
            } else {
                mtx.vin[i].scriptSig = input.final_script_sig;
                mtx.vin[i].scriptWitness = input.final_script_witness;
                newcoin.nHeight = 1;
                view.AddCoin(psbtx.tx->vin[i].prevout, std::move(newcoin), true);
            }
        }

        if (success) {
            CTransaction ctx = CTransaction(mtx);
            size_t size = GetVirtualTransactionSize(ctx, GetTransactionSigOpCost(ctx, view, STANDARD_SCRIPT_VERIFY_FLAGS));
            result.estimated_vsize = size;
            // Estimate fee rate
            CFeeRate feerate(fee, size);
            result.estimated_feerate = feerate;
        }

    }

    return result;
}


text:
package edu.ptu.javatest._20_ooad._21_create;
////-XX:+TraceClassLoading ,类加载安全机制,类加载时间不知,可能造成内存浪费
public class SingleInstance {
    public static  SingleInstance singleinstance=new SingleInstance();
    static {
        System.out.println("SingleInstance  load=================");
    }
    public static SingleInstance getSingleinstance() {
        return singleinstance;
    }
    private SingleInstance(){}
}


text:
.modal
{
	overflow: hidden;
}
body
{
	left: 10px;
	top: 10px;
	overflow: hidden;
}
#maincontainer
{
	width: 900px;
	height: 700px;
}
#messagecontainer
{
	width: 600px;
	height: 400px;
	resize: none;
	overflow: scroll;
	overflow-x: hidden;
}

#userlist li { text-align: center; cursor: pointer }
#channellist li { text-align: center; cursor: pointer }
#privlist li { text-align: center; cursor: pointer }

.btn
{
	width: 140px;
}

#messagecontainer a:hover
{
	color: red;
}


text:
SSH
===

Provides for an easier use of [SSH][1] by setting up [ssh-agent][2].

Settings
--------

### Identities

To load multiple identities, add the following line to *zpreztorc*:

```sh
zstyle ':prezto:module:ssh:load' identities 'id_rsa' 'id_dsa' 'id_github'
```

Authors
-------

*The authors of this module should be contacted via the [issue tracker][3].*

  - [Sorin Ionescu](https://github.com/sorin-ionescu)

[1]: http://www.openssh.com
[2]: http://www.openbsd.org/cgi-bin/man.cgi?query=ssh-agent&sektion=1
[3]: https://github.com/zsh-users/prezto/issues


text:
package com.google.cloud.solutions.sampleapps.orchestration.statuspublisher.server;

import com.google.cloud.solutions.sampleapps.orchestration.common.GceCurrentStatus;
import com.google.cloud.solutions.sampleapps.orchestration.common.GceCurrentStatus.Status;
import com.google.cloud.solutions.sampleapps.orchestration.common.GceStats;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Handler for a request for the status of the instance.
 */
public class StatusPublisher extends HttpServlet {
  private static final Logger logger = Logger.getLogger(StatusPublisher.class.getName());

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    doGet(req, res);
  }

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    logger.info("Getting status");
    res.setContentType("application/json");
    res.setHeader("Cache-Control", "no-cache");
    PrintWriter out = res.getWriter();
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    /*
     * 1. Check the current status. If the current status is PREPARING_FOR_SHUTDOWN, check if there
     * are any more leased tasks. If no, then change the status to READY_FOR_SHUTDOWN.
     */
    if (GceCurrentStatus.getCurrentStatus() == Status.READY_TO_SHUT_DOWN) {
      out.println(gson.toJson(new GceStats(Status.READY_TO_SHUT_DOWN)));
    } else if (GceCurrentStatus.getCurrentStatus() == Status.PREPARING_TO_SHUT_DOWN) {
      if (checkWhetherReadyToShutDown()) {
        GceCurrentStatus.setCurrentStatus(Status.READY_TO_SHUT_DOWN);
        out.println(gson.toJson(new GceStats(Status.READY_TO_SHUT_DOWN)));
      } else {
        out.println(gson.toJson(new GceStats(Status.PREPARING_TO_SHUT_DOWN)));
      }
    } else {
      SystemStatsReporter reporter = (SystemStatsReporter) getServletContext()
          .getAttribute(StatusPublisherServletContext.SYSTEM_STATS_REPORTER);
      out.println(gson.toJson(reporter.getStats()));
    }
  }

  private boolean checkWhetherReadyToShutDown() {
    // This is a simplified implementation. In a production setting,
    // one could for instance check the number of currently leased tasks.
    return true;
  }
}


text:
module ActionView
  module CollectionCaching # :nodoc:
    extend ActiveSupport::Concern

    included do
      # Fallback cache store if Action View is used without Rails.
      # Otherwise overridden in Railtie to use Rails.cache.
      mattr_accessor :collection_cache, default: ActiveSupport::Cache::MemoryStore.new
    end

    private
      def cache_collection_render(instrumentation_payload, view, template)
        return yield unless @options[:cached]

        # Result is a hash with the key represents the
        # key used for cache lookup and the value is the item
        # on which the partial is being rendered
        keyed_collection = collection_by_cache_keys(view, template)

        # Pull all partials from cache
        # Result is a hash, key matches the entry in
        # `keyed_collection` where the cache was retrieved and the
        # value is the value that was present in the cache
        cached_partials  = collection_cache.read_multi(*keyed_collection.keys)
        instrumentation_payload[:cache_hits] = cached_partials.size

        # Extract the items for the keys that are not found
        # Set the uncached values to instance variable @collection
        # which is used by the caller
        @collection = keyed_collection.reject { |key, _| cached_partials.key?(key) }.values

        # If all elements are already in cache then
        # rendered partials will be an empty array
        #
        # If the cache is missing elements then
        # the block will be called against the remaining items
        # in the @collection.
        rendered_partials = @collection.empty? ? [] : yield

        index = 0
        fetch_or_cache_partial(cached_partials, order_by: keyed_collection.each_key) do
          # This block is called once
          # for every cache miss while preserving order.
          rendered_partials[index].tap { index += 1 }
        end
      end

      def callable_cache_key?
        @options[:cached].respond_to?(:call)
      end

      def collection_by_cache_keys(view, template)
        seed = callable_cache_key? ? @options[:cached] : ->(i) { i }

        digest_path = view.digest_path_from_virtual(template.virtual_path)

        @collection.each_with_object({}) do |item, hash|
          hash[expanded_cache_key(seed.call(item), view, template, digest_path)] = item
        end
      end

      def expanded_cache_key(key, view, template, digest_path)
        key = view.combined_fragment_cache_key(view.cache_fragment_name(key, virtual_path: template.virtual_path, digest_path: digest_path))
        key.frozen? ? key.dup : key # #read_multi & #write may require mutability, Dalli 2.6.0.
      end

      # `order_by` is an enumerable object containing keys of the cache,
      # all keys are  passed in whether found already or not.
      #
      # `cached_partials` is a hash. If the value exists
      # it represents the rendered partial from the cache
      # otherwise `Hash#fetch` will take the value of its block.
      #
      # This method expects a block that will return the rendered
      # partial. An example is to render all results
      # for each element that was not found in the cache and store it as an array.
      # Order it so that the first empty cache element in `cached_partials`
      # corresponds to the first element in `rendered_partials`.
      #
      # If the partial is not already cached it will also be
      # written back to the underlying cache store.
      def fetch_or_cache_partial(cached_partials, order_by:)
        order_by.map do |cache_key|
          cached_partials.fetch(cache_key) do
            yield.tap do |rendered_partial|
              collection_cache.write(cache_key, rendered_partial)
            end
          end
        end
      end
  end
end


text:
SYNONYM

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

#### Published in
Syll. fung. (Abellini) 5: 652 (1887)

#### Original name
Laschia crustacea Jungh., 1839

### Remarks
null


text:
'use strict';function _asyncToGenerator(fn) {return function () {var gen = fn.apply(this, arguments);return new Promise(function (resolve, reject) {function step(key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {return Promise.resolve(value).then(function (value) {step("next", value);}, function (err) {step("throw", err);});}}return step("next");});};}

const utils = require('jest-matcher-utils'); const matchers = require('./matchers');const spyMatchers = require('./spyMatchers');const toThrowMatchers = require('./toThrowMatchers');var _require = require('./jasmine-utils');const equals = _require.equals;var _require2 =

require('./asymmetric-matchers');const any = _require2.any,anything = _require2.anything,arrayContaining = _require2.arrayContaining,objectContaining = _require2.objectContaining,stringContaining = _require2.stringContaining,stringMatching = _require2.stringMatching;

const GLOBAL_STATE = Symbol.for('$$jest-matchers-object');

class JestAssertionError extends Error {}

const isPromise = obj => {
  return (
    !!obj && (
    typeof obj === 'object' || typeof obj === 'function') &&
    typeof obj.then === 'function');

};

if (!global[GLOBAL_STATE]) {
  Object.defineProperty(global, GLOBAL_STATE, {
    value: {
      matchers: Object.create(null),
      state: {
        assertionCalls: 0,
        expectedAssertionsNumber: null,
        isExpectingAssertions: false,
        suppressedErrors: [] } } });

}

const expect = actual => {
  const allMatchers = global[GLOBAL_STATE].matchers;
  const expectation = {
    not: {},
    rejects: { not: {} },
    resolves: { not: {} } };

  Object.keys(allMatchers).forEach(name => {
    expectation[name] = makeThrowingMatcher(allMatchers[name], false, actual);
    expectation.not[name] = makeThrowingMatcher(
    allMatchers[name],
    true,
    actual);

    expectation.resolves[name] = makeResolveMatcher(
    name,
    allMatchers[name],
    false,
    actual);

    expectation.resolves.not[name] = makeResolveMatcher(
    name,
    allMatchers[name],
    true,
    actual);

    expectation.rejects[name] = makeRejectMatcher(
    name,
    allMatchers[name],
    false,
    actual);

    expectation.rejects.not[name] = makeRejectMatcher(
    name,
    allMatchers[name],
    true,
    actual);

  });

  return expectation;
};

const getMessage = message => {
  // for performance reasons some of the messages are evaluated
  // lazily
  if (typeof message === 'function') {
    message = message();
  }

  if (!message) {
    message = utils.RECEIVED_COLOR(
    'No message was specified for this matcher.');

  }
  return message;
};

const makeResolveMatcher = (
matcherName,
matcher,
isNot,
actual) => _asyncToGenerator(
function* () {for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {args[_key] = arguments[_key];}
  const matcherStatement = `.resolves.${isNot ? 'not.' : ''}${matcherName}`;
  if (!isPromise(actual)) {
    throw new JestAssertionError(
    utils.matcherHint(matcherStatement, 'received', '') +
    '\n\n' +
    `${utils.RECEIVED_COLOR('received')} value must be a Promise.\n` +
    utils.printWithType('Received', actual, utils.printReceived));

  }

  let result;
  try {
    result = yield actual;
  } catch (e) {
    throw new JestAssertionError(
    utils.matcherHint(matcherStatement, 'received', '') +
    '\n\n' +
    `Expected ${utils.RECEIVED_COLOR('received')} Promise to resolve, ` +
    'instead it rejected to value\n' +
    `  ${utils.printReceived(e)}`);

  }
  return makeThrowingMatcher(matcher, isNot, result).apply(null, args);
});

const makeRejectMatcher = (
matcherName,
matcher,
isNot,
actual) => _asyncToGenerator(
function* () {for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {args[_key2] = arguments[_key2];}
  const matcherStatement = `.rejects.${isNot ? 'not.' : ''}${matcherName}`;
  if (!isPromise(actual)) {
    throw new JestAssertionError(
    utils.matcherHint(matcherStatement, 'received', '') +
    '\n\n' +
    `${utils.RECEIVED_COLOR('received')} value must be a Promise.\n` +
    utils.printWithType('Received', actual, utils.printReceived));

  }

  let result;
  try {
    result = yield actual;
  } catch (e) {
    return makeThrowingMatcher(matcher, isNot, e).apply(null, args);
  }

  throw new JestAssertionError(
  utils.matcherHint(matcherStatement, 'received', '') +
  '\n\n' +
  `Expected ${utils.RECEIVED_COLOR('received')} Promise to reject, ` +
  'instead it resolved to value\n' +
  `  ${utils.printReceived(result)}`);

});

const makeThrowingMatcher = (
matcher,
isNot,
actual) =>
{
  return function throwingMatcher() {
    let throws = true;
    const matcherContext = Object.assign(
    // When throws is disabled, the matcher will not throw errors during test
    // execution but instead add them to the global matcher state. If a
    // matcher throws, test execution is normally stopped immediately. The
    // snapshot matcher uses it because we want to log all snapshot
    // failures in a test.
    { dontThrow: () => throws = false },
    global[GLOBAL_STATE].state,
    {
      equals,
      isNot,
      utils });

    let result;

    try {for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {args[_key3] = arguments[_key3];}
      result = matcher.apply(matcherContext, [actual].concat(args));
    } catch (error) {
      // Remove this and deeper functions from the stack trace frame.
      Error.captureStackTrace(error, throwingMatcher);
      throw error;
    }

    _validateResult(result);

    global[GLOBAL_STATE].state.assertionCalls++;

    if (result.pass && isNot || !result.pass && !isNot) {
      // XOR
      const message = getMessage(result.message);
      const error = new JestAssertionError(message);
      // Passing the result of the matcher with the error so that a custom
      // reporter could access the actual and expected objects of the result
      // for example in order to display a custom visual diff
      error.matcherResult = result;
      // Remove this function from the stack trace frame.
      Error.captureStackTrace(error, throwingMatcher);

      if (throws) {
        throw error;
      } else {
        global[GLOBAL_STATE].state.suppressedErrors.push(error);
      }
    }
  };
};

expect.extend = matchers => {
  Object.assign(global[GLOBAL_STATE].matchers, matchers);
};

expect.anything = anything;
expect.any = any;
expect.objectContaining = objectContaining;
expect.arrayContaining = arrayContaining;
expect.stringContaining = stringContaining;
expect.stringMatching = stringMatching;

const _validateResult = result => {
  if (
  typeof result !== 'object' ||
  typeof result.pass !== 'boolean' ||
  result.message &&
  typeof result.message !== 'string' &&
  typeof result.message !== 'function')
  {
    throw new Error(
    'Unexpected return from a matcher function.\n' +
    'Matcher functions should ' +
    'return an object in the following format:\n' +
    '  {message?: string | function, pass: boolean}\n' +
    `'${utils.stringify(result)}' was returned`);

  }
};

// add default jest matchers
expect.extend(matchers);
expect.extend(spyMatchers);
expect.extend(toThrowMatchers);

expect.addSnapshotSerializer = () => void 0;
expect.assertions = expected => {
  global[GLOBAL_STATE].state.expectedAssertionsNumber = expected;
};
expect.hasAssertions = expected => {
  utils.ensureNoExpected(expected, '.hasAssertions');
  global[GLOBAL_STATE].state.isExpectingAssertions = true;
};
expect.setState = state => {
  Object.assign(global[GLOBAL_STATE].state, state);
};
expect.getState = () => global[GLOBAL_STATE].state;

module.exports = expect;


text:
/*
 * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
 * Use is subject to license terms.
 *
 * Copyright (c) 2012, Intel Corporation.
 */
/*
 * This file is part of Lustre, http://www.lustre.org/
 * Lustre is a trademark of Sun Microsystems, Inc.
 */

#define DEBUG_SUBSYSTEM S_LNET
#include "../../include/linux/lnet/lib-lnet.h"

static int config_on_load;
module_param(config_on_load, int, 0444);
MODULE_PARM_DESC(config_on_load, "configure network at module load");

static struct mutex lnet_config_mutex;

static int
lnet_configure(void *arg)
{
	/* 'arg' only there so I can be passed to cfs_create_thread() */
	int rc = 0;

	mutex_lock(&lnet_config_mutex);

	if (!the_lnet.ln_niinit_self) {
		rc = LNetNIInit(LUSTRE_SRV_LNET_PID);
		if (rc >= 0) {
			the_lnet.ln_niinit_self = 1;
			rc = 0;
		}
	}

	mutex_unlock(&lnet_config_mutex);
	return rc;
}

static int
lnet_unconfigure(void)
{
	int refcount;

	mutex_lock(&lnet_config_mutex);

	if (the_lnet.ln_niinit_self) {
		the_lnet.ln_niinit_self = 0;
		LNetNIFini();
	}

	mutex_lock(&the_lnet.ln_api_mutex);
	refcount = the_lnet.ln_refcount;
	mutex_unlock(&the_lnet.ln_api_mutex);

	mutex_unlock(&lnet_config_mutex);
	return (refcount == 0) ? 0 : -EBUSY;
}

static int
lnet_ioctl(unsigned int cmd, struct libcfs_ioctl_data *data)
{
	int rc;

	switch (cmd) {
	case IOC_LIBCFS_CONFIGURE:
		return lnet_configure(NULL);

	case IOC_LIBCFS_UNCONFIGURE:
		return lnet_unconfigure();

	default:
		/* Passing LNET_PID_ANY only gives me a ref if the net is up
		 * already; I'll need it to ensure the net can't go down while
		 * I'm called into it */
		rc = LNetNIInit(LNET_PID_ANY);
		if (rc >= 0) {
			rc = LNetCtl(cmd, data);
			LNetNIFini();
		}
		return rc;
	}
}

static DECLARE_IOCTL_HANDLER(lnet_ioctl_handler, lnet_ioctl);

static int __init
init_lnet(void)
{
	int rc;

	mutex_init(&lnet_config_mutex);

	rc = lnet_init();
	if (rc != 0) {
		CERROR("lnet_init: error %d\n", rc);
		return rc;
	}

	rc = libcfs_register_ioctl(&lnet_ioctl_handler);
	LASSERT(rc == 0);

	if (config_on_load) {
		/* Have to schedule a separate thread to avoid deadlocking
		 * in modload */
		(void) kthread_run(lnet_configure, NULL, "lnet_initd");
	}

	return 0;
}

static void __exit
fini_lnet(void)
{
	int rc;

	rc = libcfs_deregister_ioctl(&lnet_ioctl_handler);
	LASSERT(rc == 0);

	lnet_fini();
}

MODULE_AUTHOR("Peter J. Braam <braam@clusterfs.com>");
MODULE_DESCRIPTION("LNet v3.1");
MODULE_LICENSE("GPL");
MODULE_VERSION("1.0.0");

module_init(init_lnet);
module_exit(fini_lnet);


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Dagger « PrimeDroid</title>
  <meta name="description" content="Dagger is a very popular dependency injection library created by the team at Square. Although Jake Wharton is associated with it, he has mentioned in his tal...">

  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://localhost:4000/archivers/dagger">
  <link rel="alternate" type="application/rss+xml" title="PrimeDroid" href="http://localhost:4000/feed.xml">

    PrimeDroid

        About

        Category

Dagger

Apr 29, 2016

Dagger is a very popular dependency injection library created by the team at Square. Although Jake Wharton is associated with it, he has mentioned in his talks that the idea and initial development for Dagger was done by Jesse Wilson and Bob Lee (these two were also
involved in the development of the another popular D.I.  library - Guice at Google). Dagger uses a Directed Acyclic Graph(DAG) to map the different creational classes and hence the name DAGger. The folks at Google advocate against the use of DI frameworks on account of
these frameworks using reflection and give example of Guice. However, Dagger was designed to avoid this issue and does not use reflection at all and instead uses static dependency to build the ObjectGraph. To be honest, I don't know understand everything of what I have
written in the last two sentences, but it just sounded so cool and so trustworthy that I felt inclined to use it. Once I started using it, I realized the awesome power especially as my app grew. We will be using Dagger 2 for this tutorial.

Step 1: Dagger setup with Ggradle files

Modify the build.gradle file for your project to include the neenbedankt plugin:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Modify the module gradle file to include dagger and provide the jsr annotation (make sure to include the neenbedankt info. at the top of this file):

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.primedroid.primedagger"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:24.0.0-alpha1'

    apt 'com.google.dagger:dagger-compiler:2.2'
    compile 'com.google.dagger:dagger:2.2'
    provided 'javax.annotation:jsr250-api:1.0'
}

Step 2: Fruit class

In this project we will be creating a Fruit class, which we will be injecting in the MainActivity.class. The class will look as follows:

public class Fruit {
    private String name;
    private String color;
    private int weight;
    private static Fruit fruit;

    private Fruit(String name, String color, int weight){
        this.name = name;
        this.color = color;
        this.weight = weight;

    }

    @Override
    public String toString() {
        return fruit.name+" "+fruit.color+" "+fruit.weight;
    }

    public static Fruit getFruit(){
        if (fruit!=null) {
            return fruit;
        } else {
            fruit = new Fruit("Apple", "red", 10);
            return fruit;
        }
    }

}

Step 3: App module

Dagger is all about modules. You will need an App module to start with and then a MyApp module for your object. We will do the MyApp module after the object class creation. Here is the app module:

@Module
public class AppModule {
    Application mApplication;

    public AppModule(Application application) {
        mApplication = application;
    }

    @Provides
    @Singleton
    Application providesApplication() {
        return mApplication;
    }

}

Step 4: Fruit module and component

Fruit module is the engine through which Dagger will get a Fruit object:

@Module
public class FruitModule {
    String fruitName;

    public FruitModule(String fruitName){
        this.fruitName = fruitName;
    }

    @Provides
    @Singleton
        // Application reference must come from AppModule.class
    Fruit providesFruit(Application application) {
        return Fruit.getFruit();
    }
}

Fruit component is the interface used to inject the Fruit object inside the MainActivity.class:

@Singleton
@Component(modules={AppModule.class, FruitModule.class})
public interface FruitComponent {
    void inject(MainActivity activity);
}

Step 5: MyApp module

The MyApp module is the last piece in the puzzle:

public class MyApp extends Application {
    private FruitComponent mFruitComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        mFruitComponent = DaggerFruitComponent.builder().appModule(new AppModule(this))
                .fruitModule(new FruitModule("Apple"))
                .build();

    }

    public FruitComponent getFruitComponent() {
        return mFruitComponent;
    }
}

Don't forget to specify this app in the manifest. For the application tag, add the name as .MyApp.

Step 6: Use Dagger to create the object

Now got to MainActivity.class and first inject mFruit and then create it use the MyApp application context:

public class MainActivity extends Activity {
    @Inject
    Fruit mFruit;
    @Inject
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ((MyApp) getApplication()).getFruitComponent().inject(this);
        Log.d("STRINGFRUITNAME", mFruit.toString() );
    }

You can access the sample project at the following location:

https://github.com/sastagi/primedagger

If you want to go in depth, take a look at the following take by the man himself:

https://www.parleys.com/tutorial/architecting-android-applications-dagger

Please enable JavaScript to view the comments powered by Disqus.

comments powered by Disqus

Santosh Astagi

Android developer.

    GitHub

    Twitter

    Email

Newest Posts

RxJava Introduction

Dagger

Handler Thread

Sync Adapter

Account authenticator

TOC

© 2016 Santosh Astagi


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revisâo do gênero Amauroderma (Polyporaceae); Estudos baseados nas microestruturas do basidiocarpo 274 (1968)

#### Original name
Amauroderma schomburgkii f. gusmanianum J.S. Furtado

### Remarks
null


text:
package versioned

import (
	glog "github.com/golang/glog"
	discovery "k8s.io/client-go/discovery"
	rest "k8s.io/client-go/rest"
	flowcontrol "k8s.io/client-go/util/flowcontrol"
	testgroupv1 "k8s.io/kube-gen/test/clientset/versioned/typed/testgroup/v1"
)

type Interface interface {
	Discovery() discovery.DiscoveryInterface
	TestgroupV1() testgroupv1.TestgroupV1Interface
	// Deprecated: please explicitly pick a version if possible.
	Testgroup() testgroupv1.TestgroupV1Interface
}

// Clientset contains the clients for groups. Each group has exactly one
// version included in a Clientset.
type Clientset struct {
	*discovery.DiscoveryClient
	testgroupV1 *testgroupv1.TestgroupV1Client
}

// TestgroupV1 retrieves the TestgroupV1Client
func (c *Clientset) TestgroupV1() testgroupv1.TestgroupV1Interface {
	return c.testgroupV1
}

// Deprecated: Testgroup retrieves the default version of TestgroupClient.
// Please explicitly pick a version.
func (c *Clientset) Testgroup() testgroupv1.TestgroupV1Interface {
	return c.testgroupV1
}

// Discovery retrieves the DiscoveryClient
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
	if c == nil {
		return nil
	}
	return c.DiscoveryClient
}

// NewForConfig creates a new Clientset for the given config.
func NewForConfig(c *rest.Config) (*Clientset, error) {
	configShallowCopy := *c
	if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {
		configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)
	}
	var cs Clientset
	var err error
	cs.testgroupV1, err = testgroupv1.NewForConfig(&configShallowCopy)
	if err != nil {
		return nil, err
	}

	cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)
	if err != nil {
		glog.Errorf("failed to create the DiscoveryClient: %v", err)
		return nil, err
	}
	return &cs, nil
}

// NewForConfigOrDie creates a new Clientset for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *Clientset {
	var cs Clientset
	cs.testgroupV1 = testgroupv1.NewForConfigOrDie(c)

	cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)
	return &cs
}

// New creates a new Clientset for the given RESTClient.
func New(c rest.Interface) *Clientset {
	var cs Clientset
	cs.testgroupV1 = testgroupv1.New(c)

	cs.DiscoveryClient = discovery.NewDiscoveryClient(c)
	return &cs
}


text:
package com.snkinard.coding;

/**
 * Imagine a 2d mario level that consists of consecutive rectangles of width 1 and
 * heights defined by the input: an array of integers. Lets say that we want to fill
 * all of the "valleys" in the level up with water. Write an algorithm that calculates
 * the area of the water that is necessary to fill all valleys.
 *
 * For example, say this was the input {6, 2, 4, 3, 7, 2, 3, 5, 4, 2, 3, 1}. Then we could
 * visualize the level like this using numbers for the rectangles and '~' for water:
 *
 *         7
 * 6 ~ ~ ~ 7
 * 6 ~ ~ ~ 7 ~ ~ 5
 * 6 ~ 4 ~ 7 ~ ~ 5 4
 * 6 ~ 4 3 7 ~ 3 5 4 ~ 3
 * 6 2 4 3 7 2 3 5 4 2 3
 * 6 2 4 3 7 2 3 5 4 2 3 1
 *
 * The total area of the water would be 15.
 */
public class SuperMarioLevel {

    /**
     * O(N)
     *
     * @param heights
     * @return
     */
    public static int fillLevel(int[] heights) {

        // lots of crap to keep track of
        int waterArea = 0;
        int segmentArea = 0;
        int currentIndex = 0;
        int startIndex = 0;
        int startHeight = heights[startIndex];
        int currentHeight = heights[startIndex];

        // iterate through the entire level
        while (currentIndex < heights.length) {
            currentHeight = heights[currentIndex++];
            if (currentHeight < startHeight) {
                // add to the current area and keep moving
                segmentArea += startHeight - currentHeight;
            } else {
                // set new startHeight and add to total area
                startHeight = currentHeight;
                waterArea += segmentArea;
                // reset segment area and start index
                segmentArea = 0;
                startIndex = currentIndex - 1;
            }
        }

        // test for edge case
        if (currentHeight < startHeight) {

            // again a ton of variables to help track all the things
            segmentArea = 0;
            int endIndex = startIndex;
            startIndex = heights.length - 1;
            currentIndex = startIndex;
            startHeight = currentHeight;

            // iterate backwards until you hit the peak that was found earlier
            while (currentIndex > endIndex) {
                currentHeight = heights[currentIndex--];
                if (currentHeight < startHeight) {
                    // add current area and keep moving
                    segmentArea += startHeight - currentHeight;
                } else {
                    // set new startHeight and add to total area
                    startHeight = currentHeight;
                    waterArea += segmentArea;
                    segmentArea = 0;
                }
            }
            waterArea += segmentArea;
        }
        return waterArea;
    }
}


text:
const http = require('http')
const postData = JSON.stringify({ foo: 'bar' })

const options = {
    hostname: 'mockbin.com',
    port: 80,
    path: '/request?foo=bar&foo=baz',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
    }
}

const req = http.request(options, (res) => {
    res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`)
    })
    res.on('end', () => {
        console.log('No more data in response.')
    })
})

req.on('error', (e) => {
    console.log(`Problem with request: ${e.message}`)
})

req.write(postData)
req.end()


text:
package org.dilzio.ripx;

import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventReleaser;
import com.lmax.disruptor.RingBuffer;
import org.dilzio.appparam.ApplicationParams;
import org.junit.Test;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * User: Matt C.
 * Date: 3/12/14
 */
public class RipXIntegrationTest {

    private static final int MAXITERS = 1000;
    private boolean _finished = false;

    @Test
    public void TestConstruction() throws InterruptedException {

        ApplicationParams appParams = getApplicationParams();
        appParams.setParam(RipXProperties.NUM_LISTENERS, "2");
        appParams.setParam(RipXProperties.WORKER_COUNT, "5");
        appParams.setParam(RipXProperties.THREAD_POOL_SIZE, "10");
        RipXWorkerFactory<TestRipXWorker, TestRipXEvent> workerFactory = getWorkerFactory();
        RipXProducerFactory producerFactory = getProducerFactory();
        TestRipXEventFactory eventFactory = new TestRipXEventFactory();
        RipX<TestRipXEvent, TestRipXWorker> underTest = new RipX<>(appParams, eventFactory, workerFactory, producerFactory);
        underTest.start();

        while (!_finished) {
            Thread.sleep(1000);
        }

    }

    private RipXProducerFactory getProducerFactory() {
        return new TestProducerFactory();
    }

    private RipXWorkerFactory<TestRipXWorker, TestRipXEvent> getWorkerFactory() {
        return new TestWorkerFactory();
    }

    private ApplicationParams getApplicationParams() {
        return new ApplicationParams<RipXProperties>();
    }

    ///Test Implementation Classes (typically these would be in external files)/////
    public static class TestRipXEventFactory implements EventFactory<TestRipXEvent> {
        @Override
        public TestRipXEvent newInstance() {
            return new TestRipXEvent();
        }
    }

    ;

    private static class TestRipXEvent {
        private int _value1;
        private int _value2;

        public int getValue2() {
            return _value2;
        }

        public void setValue2(int value2) {
            _value2 = value2;
        }

        public int getValue1() {
            return _value1;
        }

        public void setValue1(int value1) {
            _value1 = value1;
        }
    }

    private class TestRipXWorker extends AbstractRipXWorker<TestRipXEvent> {
        private final int _id;

        public TestRipXWorker(final RingBuffer<TestRipXEvent> ringBuffer, final int i) {
            super(ringBuffer, new CountDownLatch(0),  "testworker");
            _id = i;
        }

        @Override
        public void setEventReleaser(EventReleaser eventReleaser) {

        }

        @Override
        public void onStart() {

        }

        @Override
        public void onShutdown() {

        }

        @Override
        public void onEvent(TestRipXEvent event) throws Exception {
            //System.out.println("Worker " + _id + " value1: " + event.getValue1());
            //System.out.println("Worker " + _id + " value2: " + event.getValue2());

            if (event.getValue1() > MAXITERS) {
                _finished = true;
            }
        }
    }

    private class TestProducerFactory implements RipXProducerFactory<TestRipXEvent> {
        @Override
        public Collection<? extends RipXProducer> getProducerCollection(RingBuffer<TestRipXEvent> ringBuffer, int numConfiguredListeners) {
            List<TestRipXProducer> producerList = new LinkedList<>();

            for (int i = 0; i < numConfiguredListeners; i++) {
                producerList.add(new TestRipXProducer(ringBuffer));
            }

            return producerList;
        }
    }

    private class TestWorkerFactory implements RipXWorkerFactory<TestRipXWorker, TestRipXEvent> {
        @Override
        public TestRipXWorker[] getWorkerArray(final int numWorkers, final RingBuffer<TestRipXEvent> ringBuffer) {

            TestRipXWorker[] workerArray = new TestRipXWorker[numWorkers];
            for (int i = 0; i < numWorkers; i++) {
                workerArray[i] = new TestRipXWorker(ringBuffer, i);
            }
            return workerArray;
        }

        @Override
        public void injectStartupBarrier(CountDownLatch startupLatch) {

        }
    }

    private class TestRipXProducer implements RipXProducer {
        private final RingBuffer<TestRipXEvent> _ringBuffer;

        public TestRipXProducer(final RingBuffer<TestRipXEvent> ringBuffer) {
            _ringBuffer = ringBuffer;
        }

        @Override
        public void stop() {

        }

        @Override
        public void run() {
            int val1counter = 0;
            int val2counter = 10;

            while (!_finished) {
                long sequence = Long.MIN_VALUE;
                try {
                    sequence = _ringBuffer.next();
                    TestRipXEvent event = _ringBuffer.get(sequence);
                    event.setValue1(val1counter);
                    event.setValue2(val2counter);
                    val1counter++;
                    val2counter++;
                } finally {
                    // always publish event if ringbuffer sequence was incremented with _ringBuffer.next()
                    if (sequence != Long.MIN_VALUE) {
                        _ringBuffer.publish(sequence);
                    }
                }
            }
        }
    }
}


text:
import Ember from 'ember';
import DS from 'ember-data';
import ModelDefinition from './model-definition';
import FixtureBuilderFactory from './builder/fixture-builder-factory';

const assign = Ember.assign || Ember.merge;
let modelDefinitions = {};

/**
 Given a fixture name like 'person' or 'dude' determine what model this name
 refers to. In this case it's 'person' for each one.

 @param {String} name  a fixture name could be model name like 'person'
 or a named person in model definition like 'dude'
 @returns {String} model  name associated with fixture name or undefined if not found
 */
let lookupModelForFixtureName = function(name) {
  let definition = lookupDefinitionForFixtureName(name);
  if (definition) {
    return definition.modelName;
  }
};

/**

 @param {String} name a fixture name could be model name like 'person'
 or a named person in model definition like 'dude'
 @returns {ModelDefinition} ModelDefinition associated with model or undefined if not found
 */
let lookupDefinitionForFixtureName = function(name) {
  for (let model in modelDefinitions) {
    let definition = modelDefinitions[model];
    if (definition.matchesName(name)) {
      return definition;
    }
  }
};

let extractArgumentsShort = function(...args) {
  let opts = {};
  if (Ember.typeOf(args[args.length - 1]) === 'object') {
    opts = args.pop();
  }
  // whatever is left are traits
  let traits = Ember.A(args).compact();
  return { opts: opts, traits: traits };
};

/**
 extract arguments for build and make function
 @param {String} name  fixture name
 @param {String} trait  optional trait names ( one or more )
 @param {Object} opts  optional fixture options that will override default fixture values
 @returns {Object} json fixture
 */
let extractArguments = function(...args) {
  let name = args.shift();
  if (!name) {
    throw new Error('Build needs a factory name to build');
  }
  return assign({ name: name }, extractArgumentsShort.apply(this, args));
};

class FactoryGuy {
  /**
   * Setting for FactoryGuy. For now, just logging settings
   *
   * logLevel: 0 is off, 1 is on
   *
   * @param opts
   */
  settings({ logLevel = 0 } = {}) {
    this.logLevel = logLevel;
  }

  setStore(aStore) {
    Ember.assert("FactoryGuy#setStore needs a valid store instance.You passed in [" + aStore + "]", aStore instanceof DS.Store);
    this.store = aStore;
    const fixtureBuilderFactory = new FixtureBuilderFactory(this.store);
    this.fixtureBuilder = fixtureBuilderFactory.fixtureBuilder();
  }

  updateHTTPMethod() {
    return this.fixtureBuilder.updateHTTPMethod || 'PUT';
  }

  /**
   ```javascript

   Person = DS.Model.extend({
     type: DS.attr('string'),
     name: DS.attr('string')
   })

   FactoryGuy.define('person', {
     sequences: {
       personName: function(num) {
         return 'person #' + num;
       },
       personType: function(num) {
         return 'person type #' + num;
       }
     },
     default: {
       type: 'normal',
       name: FactoryGuy.generate('personName')
     },
     dude: {
       type: FactoryGuy.generate('personType')
     },
   });

   ```

   For the Person model, you can define named fixtures like 'dude' or
   just use 'person' and get default values.

   And to get those fixtures you would call them this way:

   FactoryGuy.build('dude') or FactoryGuy.build('person')

   @param {String} model the model to define
   @param {Object} config your model definition
   */
  define(model, config) {
    modelDefinitions[model] = new ModelDefinition(model, config);
  }

  /*
   @param model name of named fixture type like: 'admin' or model name like 'user'
   @returns {ModelDefinition} if there is one matching that name
   */
  findModelDefinition(model) {
    return modelDefinitions[model];
  }

  /**
   Used in model definitions to declare use of a sequence. For example:

   ```

   FactoryGuy.define('person', {
     sequences: {
       personName: function(num) {
         return 'person #' + num;
       }
     },
     default: {
       name: FactoryGuy.generate('personName')
     }
   });

   ```

   @param   {String|Function} value previously declared sequence name or
   an inline function to use as the sequence
   @returns {Function} wrapper function that is called by the model
   definition containing the sequence
   */
  generate(nameOrFunction) {
    let sortaRandomName = Math.floor((1 + Math.random()) * 65536).toString(16) + Date.now();
    return function() {
      // this function will be called by ModelDefinition, which has it's own generate method
      if (Ember.typeOf(nameOrFunction) === 'function') {
        return this.generate(sortaRandomName, nameOrFunction);
      } else {
        return this.generate(nameOrFunction);
      }
    };
  }

  /**
   Used in model definitions to define a belongsTo association attribute.
   For example:

   ```
   FactoryGuy.define('project', {
       default: {
         title: 'Project'
       },

       // setup named project with built in associated user
       project_with_admin: {
         user: FactoryGuy.belongsTo('admin')
       }

       // or use as a trait
       traits: {
         with_admin: {
           user: FactoryGuy.belongsTo('admin')
         }
       }
     })
   ```

   @param   {String} fixtureName fixture name
   @param   {Object} opts options
   @returns {Function} wrapper function that will build the association json
   */
  belongsTo(fixtureName, opts) {
    return ()=> {
      return this.buildRaw(fixtureName, opts);
    };
  }

  /**
   Used in model definitions to define a hasMany association attribute.
   For example:

   ```
   FactoryGuy.define('user', {
     default: {
       name: 'Bob'
     },

     // define the named user type that will have projects
     user_with_projects: { FactoryGuy.hasMany('project', 2) }

     // or use as a trait
     traits: {
       with_projects: {
         projects: FactoryGuy.hasMany('project', 2)
       }
     }
   })

   ```

   @param   {String} fixtureName fixture name
   @param   {Number} number of hasMany association items to build
   @param   {Object} opts options
   @returns {Function} wrapper function that will build the association json
   */
  hasMany(...args) {
    return ()=> {
      return this.buildRawList.apply(this, args);
    };
  }

  /**
   Build fixtures for model or specific fixture name.

   For example:

   ```

   FactoryGuy.build('user') for User model
   FactoryGuy.build('bob') for a 'bob' User
   FactoryGuy.build('bob', 'dude') for a 'bob' User with dude traits
   FactoryGuy.build('bob', 'dude', 'funny') for a 'bob' User with dude and funny traits
   FactoryGuy.build('bob', 'dude', {name: 'wombat'}) for a 'bob' User with dude trait and custom attribute name of 'wombat'

   ```

   @param {String} name  fixture name
   @param {String} trait  optional trait names ( one or more )
   @param {Object} opts  optional fixture options that will override default fixture values
   @returns {Object} json fixture
   */
  build() {
    let args = extractArguments.apply(this, arguments);
    let fixture = this.buildRaw.apply(this, arguments);
    let modelName = lookupModelForFixtureName(args.name);

    return this.fixtureBuilder.convertForBuild(modelName, fixture);
  }

  buildRaw() {
    let args = extractArguments.apply(this, arguments);

    let definition = lookupDefinitionForFixtureName(args.name);
    if (!definition) {
      throw new Error('Can\'t find that factory named [' + args.name + ']');
    }

    return definition.build(args.name, args.opts, args.traits);
  }

  /**
   Build list of fixtures for model or specific fixture name. For example:

   ```

   FactoryGuy.buildList('user') // for 0 User models
   FactoryGuy.buildList('user', 2) // for 2 User models
   FactoryGuy.build('bob', 2) // for 2 User model with bob attributes
   FactoryGuy.build('bob', 'with_car', ['with_car',{name: "Dude"}])
   // 2 User model with bob attributes, where the first also has 'with_car' trait
   // the last has 'with_car' trait and name of "Dude"

   ```

   @param {String} name  fixture name
   @param {Number} number  number of fixtures to create
   @param {String} trait  optional traits (one or more)
   @param {Object} opts  optional fixture options that will override default fixture values
   @returns {Array} list of fixtures
   */
  buildList(...args) {
    Ember.assert("buildList needs at least a name ( of model or named factory definition )", args.length > 0);

    let list = this.buildRawList.apply(this, arguments);

    let name = args.shift();
    let modelName = lookupModelForFixtureName(name);

    return this.fixtureBuilder.convertForBuild(modelName, list);
  }

  buildRawList(...args) {
    let name = args.shift();
    let definition = lookupDefinitionForFixtureName(name);
    if (!definition) {
      throw new Error("Can't find that factory named [" + name + "]");
    }
    let number = args[0] || 0;
    if (typeof number === 'number') {
      args.shift();
      let parts = extractArgumentsShort.apply(this, args);
      return definition.buildList(name, number, parts.traits, parts.opts);
    }
    else {
      return args.map(function(innerArgs) {
        if (Ember.typeOf(innerArgs) !== 'array') {
          innerArgs = [innerArgs];
        }
        let parts = extractArgumentsShort.apply(this, innerArgs);
        return definition.build(name, parts.opts, parts.traits);
      });
    }
  }

  /**
   Make new fixture and save to store.

   @param {String} name  fixture name
   @param {String} trait  optional trait names ( one or more )
   @param {Object} options  optional fixture options that will override default fixture values
   @returns {DS.Model} record
   */
  make() {
    let args = extractArguments.apply(this, arguments);

    Ember.assert(
      `FactoryGuy does not have the application's store.
       Use manualSetup(this.container) in model/component test
       before using make/makeList`, this.store
    );

    let modelName = lookupModelForFixtureName(args.name);
    let fixture = this.buildRaw.apply(this, arguments);
    let data = this.fixtureBuilder.convertForMake(modelName, fixture);

    const model = Ember.run(()=> this.store.push(data));

    let definition = lookupDefinitionForFixtureName(args.name);
    if (definition.hasAfterMake()) {
      definition.applyAfterMake(model, args.opts);
    }
    return model;
  }

  /**
   Make a list of model instances

   ```
   FactoryGuy.makeList('bob') // makes 0 bob's

   FactoryGuy.makeList('bob', 2) // makes 2 bob's

   FactoryGuy.makeList('bob', 2, 'with_car' , {name: "Dude"})
   // makes 2 bob's that have 'with_car' trait and name of "Dude"

   FactoryGuy.makeList('bob', 'with_car', ['with_car',{name: "Dude"}])
   // 2 User model with bob attributes, where the first also has 'with_car' trait
   // the last has 'with_car' trait and name of "Dude"
   ```

   @param {String} name name of fixture
   @param {Number} number number to create
   @param {String} trait  optional trait names ( one or more )
   @param {Object} options  optional fixture options that will override default fixture values
   @returns {Array} list of json fixtures or records depending on the adapter type
   */
  makeList(...args) {
    Ember.assert(
      `FactoryGuy does not have the application's store.
       Use manualSetup(this.container) in model/component test
       before using make/makeList`, this.store
    );

    Ember.assert("makeList needs at least a name ( of model or named factory definition )", args.length >= 1);

    let name = args.shift();
    let definition = lookupDefinitionForFixtureName(name);
    Ember.assert("Can't find that factory named [" + name + "]", !!definition);

    let number = args[0] || 0;
    if (typeof number === 'number') {
      args.shift();
      let arr = [];
      for (let i = 0; i < number; i++) {
        arr.push(this.make.apply(this, [name, ...args]));
      }
      return arr;
    }

    return args.map((innerArgs)=> {
      if (Ember.typeOf(innerArgs) !== 'array') {
        innerArgs = [innerArgs];
      }
      return this.make(...[name, ...innerArgs]);
    });
  }

  /**
   Clear model instances from store cache.
   Reset the id sequence for the models back to zero.
   */
  clearStore() {
    this.resetDefinitions();
    this.clearModels();
  }

  /**
   Reset the id sequence for the models back to zero.
   */
  resetDefinitions() {
    for (let model in modelDefinitions) {
      let definition = modelDefinitions[model];
      definition.reset();
    }
  }

  /**
   Clear model instances from store cache.
   */
  clearModels() {
    this.store.unloadAll();
  }

  /**
   Push fixture to model's FIXTURES array.
   Used when store's adapter is a DS.FixtureAdapter.

   @param {DS.Model} modelClass
   @param {Object} fixture the fixture to add
   @returns {Object} json fixture data
   */
  pushFixture(modelClass, fixture) {
    let index;
    if (!modelClass.FIXTURES) {
      modelClass.FIXTURES = [];
    }

    index = this.indexOfFixture(modelClass.FIXTURES, fixture);

    if (index > -1) {
      modelClass.FIXTURES.splice(index, 1);
    }

    modelClass.FIXTURES.push(fixture);

    return fixture;
  }

  /**
   Used in compliment with pushFixture in order to
   ensure we don't push duplicate fixtures

   @private
   @param {Array} fixtures
   @param {String|Integer} id of fixture to find
   @returns {Object} fixture
   */
  indexOfFixture(fixtures, fixture) {
    let index = -1,
        id    = fixture.id + '';
    Ember.A(fixtures).find(function(r, i) {
      if ('' + Ember.get(r, 'id') === id) {
        index = i;
        return true;
      } else {
        return false;
      }
    });
    return index;
  }

  /**
   Clears all model definitions
   */
  clearDefinitions(opts) {
    if (!opts) {
      this.modelDefinitions = {};
    }
  }

  /**
   Build url's for the mockjax calls. Proxy to the adapters buildURL method.

   @param {String} typeName model type name like 'user' for User model
   @param {String} id
   @return {String} url
   */
  buildURL(modelName, id = null, requestType) {
    const adapter = this.store.adapterFor(modelName);
    return adapter.buildURL(modelName, id, null, requestType);
  }

  /**
   Change reload behavior to only used cached models for find/findAll.
   You still have to handle query calls, since they always ajax for data.

   @params {Array} except list of models you don't want to mark as cached
   */
  cacheOnlyMode({ except=[] }={}) {
    let store = this.store;
    let findAdapter = store.adapterFor.bind(store);

    store.adapterFor = function(name) {
      let adapter = findAdapter(name);
      let shouldCache = ()=> {
        if (Ember.isPresent(except)) {
          return (Ember.A(except).includes(name));
        }
        return false;
      };
      adapter.shouldBackgroundReloadAll = shouldCache;
      adapter.shouldBackgroundReloadRecord = shouldCache;
      adapter.shouldReloadRecord = shouldCache;
      adapter.shouldReloadAll = shouldCache;
      return adapter;
    };
  }
}

let factoryGuy = new FactoryGuy();

let make = factoryGuy.make.bind(factoryGuy);
let makeList = factoryGuy.makeList.bind(factoryGuy);
let build = factoryGuy.build.bind(factoryGuy);
let buildList = factoryGuy.buildList.bind(factoryGuy);
let clearStore = factoryGuy.clearStore.bind(factoryGuy);

export {make, makeList, build, buildList, clearStore};
export default factoryGuy;


text:
LAUNCHER=
# If debugging is enabled propagate that through to sub-shells
if [[ "$-" == *x* ]]; then
  LAUNCHER="bash -x"
fi
BIN=$(cd "$( dirname "$0" )"; pwd)

USAGE="Usage: alluxio-mount.sh [Mount|SudoMount] [MACHINE]
\nIf omitted, MACHINE is default to be 'local'. MACHINE is one of:\n
  local\t\t\tMount local machine\n
  workers\t\tMount all the workers on worker nodes"

function init_env() {
  local libexec_dir=${ALLUXIO_LIBEXEC_DIR:-"${BIN}"/../libexec}
  . ${libexec_dir}/alluxio-config.sh
  MEM_SIZE=$(${BIN}/alluxio getConf --unit B alluxio.worker.memory.size)
  TIER_ALIAS=$(${BIN}/alluxio getConf alluxio.worker.tieredstore.level0.alias)
  TIER_PATH=$(${BIN}/alluxio getConf alluxio.worker.tieredstore.level0.dirs.path)
}

function mount_ramfs_linux() {
  local total_mem=$(($(cat /proc/meminfo | awk 'NR==1{print $2}') * 1024))
  if [[ ${total_mem} -lt ${MEM_SIZE} ]]; then
    echo "ERROR: Memory(${total_mem}) is less than requested ramdisk size(${MEM_SIZE}). Please
    reduce alluxio.worker.memory.size in alluxio-site.properties" >&2
    exit 1
  fi

  echo "Formatting RamFS: ${TIER_PATH} (${MEM_SIZE})"
  if mount | grep ${TIER_PATH} > /dev/null; then
    if [[ "$1" == "SudoMount" ]]; then
      sudo umount -l -f ${TIER_PATH}
    else
      umount -l -f ${TIER_PATH}
    fi
    if [[ $? -ne 0 ]]; then
      echo "ERROR: umount RamFS ${TIER_PATH} failed" >&2
      exit 1
    fi
  else
    if [[ "$1" == "SudoMount" ]]; then
      sudo mkdir -p ${TIER_PATH}
    else
      mkdir -p ${TIER_PATH}
    fi
    if [[ $? -ne 0 ]]; then
      echo "ERROR: mkdir ${TIER_PATH} failed" >&2
      exit 1
    fi
  fi

  if [[ "$1" == "SudoMount" ]]; then
    sudo mount -t ramfs -o size=${MEM_SIZE} ramfs ${TIER_PATH}
  else
    mount -t ramfs -o size=${MEM_SIZE} ramfs ${TIER_PATH}
  fi
  if [[ $? -ne 0 ]]; then
    echo "ERROR: mount RamFS ${TIER_PATH} failed" >&2
    exit 1
  fi

  if [[ "$1" == "SudoMount" ]]; then
    sudo chmod a+w ${TIER_PATH}
  else
    chmod a+w ${TIER_PATH}
  fi
  if [[ $? -ne 0 ]]; then
    echo "ERROR: chmod RamFS ${TIER_PATH} failed" >&2
    exit 1
  fi
}

function mount_ramfs_mac() {
  # Convert the memory size to number of sectors. Each sector is 512 Byte.
  local num_sectors=$(${BIN}/alluxio runClass alluxio.util.HFSUtils ${MEM_SIZE} 512)

  # Format the RAM FS
  # We may have a pre-existing RAM FS which we need to throw away
  echo "Formatting RamFS: ${TIER_PATH} ${num_sectors} sectors (${MEM_SIZE})."
  local device=$(df -l | grep ${TIER_PATH} | cut -d " " -f 1)
  if [[ -n "${device}" ]]; then
    hdiutil detach -force ${device}
  fi
  # Remove the "/Volumes/" part so we can get the name of the volume.
  diskutil erasevolume HFS+ ${TIER_PATH/#\/Volumes\//} $(hdiutil attach -nomount ram://${num_sectors})
}

function mount_ramfs_local() {
  init_env

  if [[ ${TIER_ALIAS} != "MEM" ]]; then
    # the top tier is not MEM, skip
    exit 1
  fi

  if [[ $(uname -a) == Darwin* ]]; then
    # Assuming Mac OS X
    mount_ramfs_mac
  else
    # Assuming Linux
    mount_ramfs_linux $1
  fi
}

function main {
  case "$1" in
    Mount|SudoMount)
      case "$2" in
        ""|local)
          mount_ramfs_local $1
          ;;
        workers)
          ${LAUNCHER} ${BIN}/alluxio-workers.sh ${BIN}/alluxio-mount.sh $1
          ;;
        *)
          echo -e ${USAGE} >&2
          exit 1
      esac
      ;;
    *)
      echo -e ${USAGE} >&2
      exit 1
  esac
}

main "$@"


text:
<?php

namespace Test\TopicBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Comment
 * @ORM\Entity(repositoryClass="Test\TopicBundle\Entity\Repository\CommentRepository")
 * @ORM\Table(name="comment")
 * @ORM\HasLifecycleCallbacks
 */
class Comment
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\ManyToOne(targetEntity="User", inversedBy="comments")
     */
    protected $user;

    /**
     * @var string
     *
     * @ORM\Column(name="comment", type="text", nullable=false)
     */
    protected $comment;

    /**
     * @var \Topic
     *
     * @ORM\ManyToOne(targetEntity="Topic", inversedBy="comments")
     * @ORM\JoinColumn(name="topic_id", referencedColumnName="id", nullable=false)
     */
    protected $topic;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime", nullable=false)
     */
    protected $created;

    public function __construct()
    {
        $this->setCreated(new \DateTime());
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set user
     *
     * @param string $user
     * @return Comment
     */
    public function setUser($user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return string
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Set comment
     *
     * @param string $comment
     * @return Comment
     */
    public function setComment($comment)
    {
        $this->comment = $comment;

        return $this;
    }

    /**
     * Get comment
     *
     * @return string
     */
    public function getComment()
    {
        return $this->comment;
    }

    /**
     * Set topic
     *
     * @param \Test\TopicBundle\Entity\Topic $topic
     * @return Comment
     */
    public function setTopic(\Test\TopicBundle\Entity\Topic $topic = null)
    {
        $this->topic = $topic;

        return $this;
    }

    /**
     * Get topic
     *
     * @return \Test\TopicBundle\Entity\Topic
     */
    public function getTopic()
    {
        return $this->topic;
    }

        /**
     * Set created
     *
     * @param \DateTime $created
     * @return Topic
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }
}


text:
 // 选择对象
 var chk_All = document.getElementById("chk_All")
     , chk_Items = document.getElementsByName("chk_Item")
     , hid_Items = document.getElementsByName("hid_Item");

 /*全选checkbox注册click事件*/
 chk_All.onclick = function (event) {
     for (var i = 0, len = chk_Items.length; i < len; i++) {
         chk_Items[i].checked = this.checked ? true : false;
     }
 };

 /*数据行中所有checkbox注册click事件处理程序*/
 chk_Items.onclick = function (event) {
     if (!this.checked) {
         chk_All.checked = false;
     } else {
         chk_All.checked = haveCheckedAll() ? true : false;
     }
 };

 /*数据行中是否所有的checkbox都被勾选*/
 function haveCheckedAll() {
     for (var i = 0, len = chk_Items.length; i < len; i++) {
         if (!chk_Items[i].checked) {
             return false;
         }
     }
     return true;
 };


text:
Weather-Education-Workshop-Innovation-Team (WEWIT)
==================================================

We aim to create content for an environmental sciences course. We will create a complete presentation where we will define the basic concepts of the urban heat island, climate change and how we can monitor climate within the cities. The approach is merely educational and will be presented to our university faculty in order to create awareness and introduce this topic in the environmental studies curriculum.

The course runs from the introduction of the terms urban heat island, climate change, the creation of microclimates up to the establishment of the designs for building the elements that has part in a sensor network for monitoring or supervisising variables like temperature and relative humidity. With this we aim to determine how are these variables affecting energy consumption, public health and human comfort in urban areas.

We answer questions related to the Urban Heat Island phenomena, how to determine the problem and how to revert it's effects. Prevention is not possible at this point so reducing consumption of fuels and the need for air conditioners will help revert the temperature increase in a more effective way. We plan to present this to the Architecture Faculty to promote new environmental courses related to this problems. Also some engineering courses related to the creation of urban sensor networks to gather data that will support new initiatives in reducing the already increasing temperatures within the cities.

Project Members:

Raul Fernando Solis Bethancurt - Electronics and Communications Engineer
Rafael Asprilla - M.Sc. in Engineering of Communication Systems

Faculty members at University of Panama

Objectives:
- Create awareness of the urban heat island effect, where it comes from, implications and technological tools to model    and control it's effects.
- Define concepts of the urban heat island, climate change and sensor networks.
- Discuss the implications of the increase in temperature due to human activities within the cities.
- Learn how to design and create an operative sensor network and the applications that will gather the information        needed to model and analyze the situation within the cities.

Course Synopsis

    Part 1: Climate and Environment
            Defines basic concepts of climate, environment, urban heat island and climate change.
    Part 2: Heat Dynamics
            Heat waves, how they work?
            Defining the required concepts to understand how heat waves move through the cities.
    Part 3: Heat Effects
            How heat affects humans, side effects of heat waves.
    Part 4: Tools to reduce heat effects
            Review of all tools, methods and policies that should be implemented in order to control and reduce the                 problem
    Part 5: Tell everybody about the problem
            How to inform the population about the issue, understand how the heat problem may affect them. Spread the               word
    Part 6: Short range sensor networks design and deployment
            Requirements, design and implementation of sensor networks for monitoring the urban heat island's                       temperature increase and create alarms that will alert of the situation.


text:
<?php
    class Royalty{
        private $id;
        private $petroleumProduct;
        private $plan;
        private $qteFuel;
        private $category;
        private $planLength;
        private $maxWeight;
        private $planWidth;
        private $surface;
        private $htPrice;
        private $ttcPrice;
        private $ffa;
        private $serviceId;
        private $coeffAcousticGroup;

        public function __construct($petroleumProduct, $plan,
                                    $qteFuel, $category, $planLength,
                                    $maxWeight, $planWidth, $surface,
                                    $htPrice, $ttcPrice, $ffa, $serviceId, $coeffAcousticGroup){
            $this->petroleumProduct = $petroleumProduct;
            $this->plan = $plan;
            $this->qteFuel = $qteFuel;
            $this->category = $category;
            $this->planLength = $planLength;
            $this->maxWeight = $maxWeight;
            $this->planWidth = $planWidth;
            $this->surface = $surface;
            $this->htPrice = $htPrice;
            $this->ttcPrice = $ttcPrice;
            $this->ffa = $ffa;
            $this->serviceId = $serviceId;
            $this->coeffAcousticGroup = $coeffAcousticGroup;
        }

        public function getId(){
            return $this->id;
        }
        public function setId($id){
            $this->id = $id;
        }

        public function getPetroleumProduct(){
            return $this->petroleumProduct;
        }

        public function getPlan(){
            return $this->plan;
        }

        public function getQteFuel(){
            return $this->qteFuel;
        }

        public function getCategory(){
            return $this->category ;
        }

        public function getPlanLength(){
            return $this->planLength;
        }

        public function getMaxWeight(){
            return $this->maxWeight;
        }

        public function getPlanWidth(){
            return $this->planWidth;
        }

        public function getSurface(){
            return $this->surface;
        }
        public function getHtPrice(){
            return $this->htPrice;
        }

        public function getTtcPrice(){
            return $this->ttcPrice;
        }

        public function getFfa(){
            return $this->ffa;
        }

        public function getServiceId(){
            return $this->serviceId;
        }

        public function getCoeffAcousticGroup(){
            return $this->coeffAcousticGroup;
        }

        public function setHtPrice($htPrice){
            $this->htPrice = $htPrice;
        }

        public function setTtcPrice($ttcPrice){
            $this->ttcPrice = $ttcPrice;
        }

        public function setServiceId($serviceId){
            $this->serviceId = $serviceId;
        }

        public function setCoeffAcousticGroup($coeffAcousticGroup){
            $this->coeffAcousticGroup = $coeffAcousticGroup;
        }
    }
?>