text:
package org.dcache.chimera;

import static org.dcache.nfs.v4.xdr.nfs4_prot.ACCESS4_EXTEND;
import static org.dcache.nfs.v4.xdr.nfs4_prot.ACCESS4_MODIFY;
import static org.dcache.nfs.v4.xdr.nfs4_prot.ACE4_INHERIT_ONLY_ACE;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import javax.security.auth.Subject;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.dcache.acl.ACE;
import org.dcache.acl.enums.AceFlags;
import org.dcache.acl.enums.AceType;
import org.dcache.acl.enums.Who;
import org.dcache.auth.Subjects;
import org.dcache.nfs.status.ExistException;
import org.dcache.nfs.status.NfsIoException;
import org.dcache.nfs.status.NoEntException;
import org.dcache.nfs.status.NotDirException;
import org.dcache.nfs.status.NotEmptyException;
import org.dcache.nfs.v4.NfsIdMapping;
import org.dcache.nfs.v4.acl.Acls;
import org.dcache.nfs.v4.xdr.aceflag4;
import org.dcache.nfs.v4.xdr.acemask4;
import org.dcache.nfs.v4.xdr.acetype4;
import org.dcache.nfs.v4.xdr.nfsace4;
import org.dcache.nfs.v4.xdr.uint32_t;
import org.dcache.nfs.v4.xdr.utf8str_mixed;
import org.dcache.nfs.vfs.AclCheckable;
import org.dcache.nfs.vfs.DirectoryEntry;
import org.dcache.nfs.vfs.FsStat;
import org.dcache.nfs.vfs.Inode;
import org.dcache.nfs.vfs.Stat;
import org.dcache.nfs.vfs.VirtualFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.collect.Lists;

public class HadoopHdfsVfs implements VirtualFileSystem, AclCheckable {

	private final static Logger LOG = LoggerFactory
			.getLogger(HadoopHdfsVfs.class);
	private Configuration hdfsConfig = null;
	private FileSystem hdfs = null;
	private LoadingCache<Inode, FSDataOutputStream> hdfsFSoutCache;

	private int maxCacheSize = 250;
	private int lastAccess = 30;
	private Path base;

	private final NfsIdMapping idMapping;
	private final HdfsJdbcFileSystemProvider jdbcFsProvider;

	public HadoopHdfsVfs(HdfsJdbcFileSystemProvider jdbcFsProvider,
			NfsIdMapping idMapping) throws IOException {
		this.jdbcFsProvider = jdbcFsProvider;
		this.idMapping = idMapping;
		init(null);
	}

	public HadoopHdfsVfs(HdfsJdbcFileSystemProvider jdbcFsProvider,
			NfsIdMapping idMapping, Path base) throws IOException {
		this.jdbcFsProvider = jdbcFsProvider;
		this.idMapping = idMapping;
		this.base = base;
		init(null);
	}

	public HadoopHdfsVfs(HdfsJdbcFileSystemProvider jdbcFsProvider,
			NfsIdMapping idMapping, Path base, Path configDir)
			throws IOException {
		this.jdbcFsProvider = jdbcFsProvider;
		this.idMapping = idMapping;
		this.base = base;
		init(configDir);
	}

	public HadoopHdfsVfs(HdfsJdbcFileSystemProvider jdbcFsProvider,
			NfsIdMapping idMapping, Path base, Path configDir,
			int maxCacheSize, int lastAccess) throws IOException {
		this.jdbcFsProvider = jdbcFsProvider;
		this.idMapping = idMapping;
		this.base = base;
		this.maxCacheSize = maxCacheSize;
		this.lastAccess = lastAccess;
		init(configDir);
	}

	protected void init(Path configDir) throws IOException {
		this.hdfsConfig = new Configuration();
		if (configDir != null) {
			this.hdfsConfig.addResource(new Path(configDir, "core-site.xml"));
			this.hdfsConfig.addResource(new Path(configDir, "hdfs-site.xml"));
			this.hdfsConfig.addResource(new Path(configDir, "yarn-site.xml"));
			this.hdfs = FileSystem.get(this.hdfsConfig);
		}
		this.hdfsFSoutCache = CacheBuilder.newBuilder()
				.maximumSize(this.maxCacheSize)
				.expireAfterAccess(this.lastAccess, TimeUnit.SECONDS)
				.removalListener(new InodeGarbageCollector())
				.build(new HdfsOutputStreamSupplier(this));
	}

	@Override
	public Inode getRootInode() throws IOException {
		return toInode(FsInode.getRoot(jdbcFsProvider));
	}

	@Override
	public Inode lookup(Inode parent, String path) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("lookup:{} in parant:{}", path, parent.toString());
		try {
			FsInode parentFsInode = toFsInode(parent);
			FsInode fsInode = parentFsInode.inodeOf(path);
			return toInode(fsInode);
		} catch (FileNotFoundHimeraFsException e) {
			throw new NoEntException("Path Do not exist.");
		}
	}

	@Override
	public Inode create(Inode parent, Stat.Type type, String path, int uid,
			int gid, int mode) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("create:{}", path);
		try {
			FsInode parentFsInode = toFsInode(parent);
			if (LOG.isDebugEnabled())
				LOG.debug("ParentFNode:{}", parentFsInode.toString());
			FsInode fsInode = jdbcFsProvider.createFile(parentFsInode, path,
					uid, gid, mode | typeToChimera(type), typeToChimera(type));
			return toInode(fsInode);
		} catch (FileExistsChimeraFsException e) {
			throw new ExistException("path already exists");
		}
	}

	@Override
	public Inode mkdir(Inode parent, String path, int uid, int gid, int mode)
			throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("mkdir:{}", path);
		try {
			FsInode parentFsInode = toFsInode(parent);
			FsInode fsInode = parentFsInode.mkdir(path, uid, gid, mode);
			return toInode(fsInode);
		} catch (FileExistsChimeraFsException e) {
			throw new ExistException("path already exists");
		}
	}

	@Override
	public Inode link(Inode parent, Inode link, String path, int uid, int gid)
			throws IOException {
		if (LOG.isInfoEnabled())
			LOG.info("link");
		FsInode parentFsInode = toFsInode(parent);
		FsInode linkInode = toFsInode(link);
		try {
			FsInode fsInode = jdbcFsProvider.createHLink(parentFsInode,
					linkInode, path);
			return toInode(fsInode);
		} catch (NotDirChimeraException e) {
			throw new NotDirException("parent not a directory");
		} catch (FileExistsChimeraFsException e) {
			throw new ExistException("path already exists");
		}
	}

	@Override
	public Inode symlink(Inode parent, String path, String link, int uid,
			int gid, int mode) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("symlink");
		try {
			FsInode parentFsInode = toFsInode(parent);
			FsInode fsInode = jdbcFsProvider.createLink(parentFsInode, path,
					uid, gid, mode, link.getBytes(StandardCharsets.UTF_8));
			return toInode(fsInode);
		} catch (FileExistsChimeraFsException e) {
			throw new ExistException("path already exists");
		}
	}

	@Override
	public int read(Inode inode, byte[] data, long offset, int count)
			throws IOException {
		Path path = inode2path(inode);
		FSDataInputStream fin = this.hdfs.open(new Path(this.base, path));
		int ret = fin.read(offset, data, 0, count);
		fin.close();
		if (LOG.isDebugEnabled()) {
			LOG.debug("Path, {}, readed {}, offset, {}, count, {}", path, ret,
					offset, count);
		}
		return ret;
	}

	@Override
	public boolean move(Inode src, String oldName, Inode dest, String newName)
			throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("move");
		FsInode from = toFsInode(src);
		FsInode to = toFsInode(dest);
		try {
			return jdbcFsProvider.move(from, oldName, to, newName);
		} catch (NotDirChimeraException e) {
			throw new NotDirException("not a directory");
		} catch (FileExistsChimeraFsException e) {
			throw new ExistException("destination exists");
		} catch (DirNotEmptyHimeraFsException e) {
			throw new NotEmptyException("directory exist and not empty");
		} catch (FileNotFoundHimeraFsException e) {
			throw new NoEntException("file not found");
		}
	}

	@Override
	public String readlink(Inode inode) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("readlink");
		FsInode fsInode = toFsInode(inode);
		int count = (int) fsInode.statCache().getSize();
		byte[] data = new byte[count];
		int n = jdbcFsProvider.read(fsInode, 0, data, 0, count);
		if (n < 0) {
			throw new NfsIoException("Can't read symlink");
		}
		return new String(data, 0, n, StandardCharsets.UTF_8);
	}

	@Override
	public void remove(Inode parent, String path) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("remove");
		FsInode parentFsInode = toFsInode(parent);
		try {
			jdbcFsProvider.remove(parentFsInode, path);
		} catch (FileNotFoundHimeraFsException e) {
			throw new NoEntException("path not found");
		} catch (DirNotEmptyHimeraFsException e) {
			throw new NotEmptyException("directory not empty");
		}
	}

	@Override
	public WriteResult write(Inode inode, byte[] data, long offset, int count,
			StabilityLevel stabilityLevel) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("write:length[{}] offset[{}] count[{}]", data.length,
					offset, count);
		FsInode fsInode = toFsInode(inode);
		int bytesWritten = fsInode.write(offset, data, 0, count);
		return new WriteResult(StabilityLevel.FILE_SYNC, bytesWritten);
	}

	@Override
	public void commit(Inode inode, long offset, int count) throws IOException {
		// nop (all IO is FILE_SYNC so no commits expected)
	}

	public void close(Inode inode) {
		if (this.hdfsFSoutCache.getIfPresent(inode) != null) {
			this.hdfsFSoutCache.invalidate(inode);
		}
	}

	public FSDataOutputStream getFSDataOutputStream(Inode inode)
			throws IOException {
		FSDataOutputStream fout = null;
		try {
			fout = this.hdfsFSoutCache.get(inode);
		} catch (ExecutionException e) {
			throw new IOException("Failed to open HDFS output stream", e);
		}
		return fout;
	}

	@Override
	public List<DirectoryEntry> list(Inode inode) throws IOException {
		FsInode parentFsInode = toFsInode(inode);
		if (LOG.isDebugEnabled())
			LOG.debug("list inode:{}", parentFsInode.toString());
		List<HimeraDirectoryEntry> list = DirectoryStreamHelper
				.listOf(parentFsInode);
		return Lists.transform(list, new ChimeraDirectoryEntryToVfs());
	}

	@Override
	public Inode parentOf(Inode inode) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("parentOf");
		FsInode parent = toFsInode(inode).getParent();
		if (parent == null) {
			throw new NoEntException("no parent");
		}
		return toInode(parent);
	}

	@Override
	public FsStat getFsStat() throws IOException {
		org.dcache.chimera.FsStat fsStat = jdbcFsProvider.getFsStat();
		return new FsStat(fsStat.getTotalSpace(), fsStat.getTotalFiles(),
				fsStat.getUsedSpace(), fsStat.getUsedFiles());
	}

	@Override
	public Stat getattr(Inode inode) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("getattr");
		FsInode fsInode = toFsInode(inode);
		try {
			return fromChimeraStat(fsInode.stat(), fsInode.id());
		} catch (FileNotFoundHimeraFsException e) {
			throw new NoEntException("Path Do not exist.");
		}
	}

	@Override
	public void setattr(Inode inode, Stat stat) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("setattr");
		FsInode fsInode = toFsInode(inode);
		fsInode.setStat(toChimeraStat(stat));
	}

	@Override
	public nfsace4[] getAcl(Inode inode) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("getAcl");
		FsInode fsInode = toFsInode(inode);
		nfsace4[] aces;
		List<ACE> dacl = jdbcFsProvider.getACL(fsInode);
		org.dcache.chimera.posix.Stat stat = fsInode.statCache();

		nfsace4[] unixAcl = Acls.of(stat.getMode(), fsInode.isDirectory());
		aces = new nfsace4[dacl.size() + unixAcl.length];
		int i = 0;
		for (ACE ace : dacl) {
			aces[i] = valueOf(ace, this.idMapping);
			i++;
		}
		System.arraycopy(unixAcl, 0, aces, i, unixAcl.length);
		return Acls.compact(aces);
	}

	@Override
	public void setAcl(Inode inode, nfsace4[] acl) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("setAcl");
		FsInode fsInode = toFsInode(inode);
		List<ACE> dacl = new ArrayList<>();
		for (nfsace4 ace : acl) {
			dacl.add(valueOf(ace, this.idMapping));
		}
		jdbcFsProvider.setACL(fsInode, dacl);
	}

	private static Stat fromChimeraStat(org.dcache.chimera.posix.Stat pStat,
			long fileid) {
		Stat stat = new Stat();
		stat.setATime(pStat.getATime());
		stat.setCTime(pStat.getCTime());
		stat.setMTime(pStat.getMTime());
		stat.setGid(pStat.getGid());
		stat.setUid(pStat.getUid());
		stat.setDev(pStat.getDev());
		stat.setIno(pStat.getIno());
		stat.setMode(pStat.getMode());
		stat.setNlink(pStat.getNlink());
		stat.setRdev(pStat.getRdev());
		stat.setSize(pStat.getSize());
		stat.setFileid(fileid);
		stat.setGeneration(pStat.getGeneration());
		return stat;
	}

	private static org.dcache.chimera.posix.Stat toChimeraStat(Stat stat) {

		org.dcache.chimera.posix.Stat pStat = new org.dcache.chimera.posix.Stat();
		pStat.setATime(stat.getATime());
		pStat.setCTime(stat.getCTime());
		pStat.setMTime(stat.getMTime());

		pStat.setGid(stat.getGid());
		pStat.setUid(stat.getUid());
		pStat.setDev(stat.getDev());
		pStat.setIno(stat.getIno());
		pStat.setMode(stat.getMode());
		pStat.setNlink(stat.getNlink());
		pStat.setRdev(stat.getRdev());
		pStat.setSize(stat.getSize());
		pStat.setGeneration(stat.getGeneration());
		return pStat;
	}

	@Override
	public int access(Inode inode, int mode) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("access");
		int accessmask = mode;
		if ((mode & (ACCESS4_MODIFY | ACCESS4_EXTEND)) != 0) {

			FsInode fsInode = toFsInode(inode);
			if (shouldRejectUpdates(fsInode)) {
				accessmask ^= (ACCESS4_MODIFY | ACCESS4_EXTEND);
			}
		}

		return accessmask;
	}

	private boolean shouldRejectUpdates(FsInode fsInode)
			throws ChimeraFsException {
		if (LOG.isDebugEnabled())
			LOG.debug("shouldRejectUpdates");
		return fsInode.type() == FsInodeType.INODE
				&& fsInode.getLevel() == 0
				&& !fsInode.isDirectory()
				&& (!jdbcFsProvider.getInodeLocations(fsInode,
						StorageGenericLocation.TAPE).isEmpty() || !jdbcFsProvider
						.getInodeLocations(fsInode, StorageGenericLocation.DISK)
						.isEmpty());
	}

	@Override
	public boolean hasIOLayout(Inode inode) throws IOException {
		if (LOG.isDebugEnabled())
			LOG.debug("hasIOLayout");
		FsInode fsInode = toFsInode(inode);
		return fsInode.type() == FsInodeType.INODE && fsInode.getLevel() == 0;
	}

	@Override
	public AclCheckable getAclCheckable() {
		if (LOG.isDebugEnabled())
			LOG.debug("AclCheckable");
		return this;
	}

	protected Path inode2path(Inode inode) throws IOException {
		String path = null;
		FsInode fsInode = toFsInode(inode);
		path = fsInode.getFs().inode2path(fsInode);
		return new Path(path);
	}

	protected FSDataOutputStream inode2FSDataOutputStream(Inode inode)
			throws IOException {
		FSDataOutputStream ret = null;
		try {
			Path path = inode2path(inode);
			if (LOG.isDebugEnabled())
				LOG.debug("Request path:{}", path);
			Path hdfsFile = new Path(this.base, path);
			if (LOG.isDebugEnabled())
				LOG.debug("Request file path :{}", hdfsFile);
			if (!this.hdfs.exists(hdfsFile.getParent())) {
				this.hdfs.mkdirs(hdfsFile.getParent());
			}
			ret = this.hdfs.create(hdfsFile, Boolean.TRUE);
		} catch (Exception e) {
			LOG.error("Failed to create FSDataOutputStream", e);
		}
		return ret;
	}

	protected FSDataInputStream inode2FSDataInputStream(Inode inode)
			throws IOException {
		Path path = inode2path(inode);
		return this.hdfs.open(new Path(this.base, path));
	}

	protected FsInode toFsInode(Inode inode) throws IOException {
		return this.jdbcFsProvider.inodeFromBytes(inode.getFileId());
	}

	protected Inode toInode(final FsInode inode) {
		try {
			return Inode.forFile(this.jdbcFsProvider.inodeToBytes(inode));
		} catch (ChimeraFsException e) {
			throw new RuntimeException("bug found", e);
		}
	}

	private int typeToChimera(Stat.Type type) {
		switch (type) {
		case SYMLINK:
			return UnixPermission.S_IFLNK;
		case DIRECTORY:
			return UnixPermission.S_IFDIR;
		case SOCK:
			return UnixPermission.S_IFSOCK;
		case FIFO:
			return UnixPermission.S_IFIFO;
		case BLOCK:
			return UnixPermission.S_IFBLK;
		case CHAR:
			return UnixPermission.S_IFCHR;
		case REGULAR:
		default:
			return UnixPermission.S_IFREG;
		}
	}

	private static nfsace4 valueOf(ACE ace, NfsIdMapping idMapping) {

		String principal;
		switch (ace.getWho()) {
		case USER:
			principal = idMapping.uidToPrincipal(ace.getWhoID());
			break;
		case GROUP:
			principal = idMapping.gidToPrincipal(ace.getWhoID());
			break;
		default:
			principal = ace.getWho().getAbbreviation();
		}

		nfsace4 nfsace = new nfsace4();
		nfsace.access_mask = new acemask4(new uint32_t(ace.getAccessMsk()));
		nfsace.flag = new aceflag4(new uint32_t(ace.getFlags()));
		nfsace.type = new acetype4(new uint32_t(ace.getType().getValue()));
		nfsace.who = new utf8str_mixed(principal);
		return nfsace;
	}

	private static ACE valueOf(nfsace4 ace, NfsIdMapping idMapping) {
		String principal = ace.who.toString();
		int type = ace.type.value.value;
		int flags = ace.flag.value.value;
		int mask = ace.access_mask.value.value;

		int id = -1;
		Who who = Who.fromAbbreviation(principal);
		if (who == null) {
			// not a special pricipal
			boolean isGroup = AceFlags.IDENTIFIER_GROUP.matches(flags);
			if (isGroup) {
				who = Who.GROUP;
				id = idMapping.principalToGid(principal);
			} else {
				who = Who.USER;
				id = idMapping.principalToUid(principal);
			}
		}
		return new ACE(AceType.valueOf(type), flags, mask, who, id,
				ACE.DEFAULT_ADDRESS_MSK);
	}

	@Override
	public Access checkAcl(Subject subject, Inode inode, int access)
			throws IOException {
		FsInode fsInode = toFsInode(inode);
		List<ACE> acl = jdbcFsProvider.getACL(fsInode);
		org.dcache.chimera.posix.Stat stat = jdbcFsProvider.stat(fsInode);
		return checkAcl(subject, acl, stat.getUid(), stat.getGid(), access);
	}

	private Access checkAcl(Subject subject, List<ACE> acl, int owner,
			int group, int access) {

		for (ACE ace : acl) {

			int flag = ace.getFlags();
			if ((flag & ACE4_INHERIT_ONLY_ACE) != 0) {
				continue;
			}

			if ((ace.getType() != AceType.ACCESS_ALLOWED_ACE_TYPE)
					&& (ace.getType() != AceType.ACCESS_DENIED_ACE_TYPE)) {
				continue;
			}

			int ace_mask = ace.getAccessMsk();
			if ((ace_mask & access) == 0) {
				continue;
			}

			Who who = ace.getWho();

			if ((who == Who.EVERYONE)
					|| (who == Who.OWNER & Subjects.hasUid(subject, owner))
					|| (who == Who.OWNER_GROUP & Subjects
							.hasGid(subject, group))
					|| (who == Who.GROUP & Subjects.hasGid(subject,
							ace.getWhoID()))
					|| (who == Who.USER & Subjects.hasUid(subject,
							ace.getWhoID()))) {

				if (ace.getType() == AceType.ACCESS_DENIED_ACE_TYPE) {
					return Access.DENY;
				} else {
					return Access.ALLOW;
				}
			}
		}

		return Access.UNDEFINED;
	}

	private class ChimeraDirectoryEntryToVfs implements
			Function<HimeraDirectoryEntry, DirectoryEntry> {
		@Override
		public DirectoryEntry apply(HimeraDirectoryEntry e) {
			if (LOG.isDebugEnabled())
				LOG.debug(
						"transform HimeraDirectoryEntry to DirectoryEntry:{}",
						e.getName());
			return new DirectoryEntry(e.getName(), toInode(e.getInode()),
					fromChimeraStat(e.getStat(), e.getInode().id()));
		}
	}

	private static class InodeGarbageCollector implements
			RemovalListener<Inode, FSDataOutputStream> {

		@Override
		public void onRemoval(
				RemovalNotification<Inode, FSDataOutputStream> notification) {
			try {
				FSDataOutputStream fout = notification.getValue();
				fout.flush();
				fout.close();
				if (LOG.isDebugEnabled())
					LOG.debug("FSDataOutputStream Closed.");
			} catch (IOException e) {
				LOG.error("Failed to close file channel of {} : {}",
						notification.getKey(), e.getMessage());
			}
		}
	}

	private static class HdfsOutputStreamSupplier extends
			CacheLoader<Inode, FSDataOutputStream> {

		private final HadoopHdfsVfs hdfsDriver;

		HdfsOutputStreamSupplier(HadoopHdfsVfs hdfsDriver) throws IOException {
			this.hdfsDriver = hdfsDriver;
		}

		@Override
		public FSDataOutputStream load(Inode inode) throws IOException {
			return this.hdfsDriver.inode2FSDataOutputStream(inode);
		}

	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecanactis flexans Nyl.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "Cumulus.h"
#include "Entity.h"
#include "RTMFP.h"
#include "Poco/Net/SocketAddress.h"

namespace Cumulus {

class Cookie;
class Target : public Entity {
public:
	Target(const Poco::Net::SocketAddress& address,Cookie* pCookie=NULL);
	virtual ~Target();

	const Poco::Net::SocketAddress	address;
	const bool						isPeer;
	const Poco::UInt8				peerId[ID_SIZE];
	const std::vector<Poco::UInt8>  initiatorNonce;
	const Poco::UInt8				sharedSecret[KEY_SIZE];

	const Poco::UInt8				publicKey[KEY_SIZE+4];
	DH*								pDH;
};

} // namespace Cumulus


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true" android:drawable="@drawable/editbox_background_focus" />
    <item android:drawable="@drawable/editbox_background_normal" />

</selector>


text: git push origin --delete branchname


text:
package com.google.api.gax.httpjson;

import com.google.api.client.http.EmptyContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.http.HttpMethods;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.GenericData;
import com.google.auth.Credentials;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auto.value.AutoValue;
import com.google.common.base.Strings;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import org.threeten.bp.Duration;
import org.threeten.bp.Instant;

/** A runnable object that creates and executes an HTTP request. */
class HttpRequestRunnable<RequestT, ResponseT> implements Runnable {
  private final RequestT request;
  private final ApiMethodDescriptor<RequestT, ResponseT> methodDescriptor;
  private final String endpoint;
  private final HttpJsonCallOptions httpJsonCallOptions;
  private final HttpTransport httpTransport;
  private final HttpJsonMetadata headers;
  private final ResultListener resultListener;

  private volatile boolean cancelled = false;

  HttpRequestRunnable(
      RequestT request,
      ApiMethodDescriptor<RequestT, ResponseT> methodDescriptor,
      String endpoint,
      HttpJsonCallOptions httpJsonCallOptions,
      HttpTransport httpTransport,
      HttpJsonMetadata headers,
      ResultListener resultListener) {
    this.request = request;
    this.methodDescriptor = methodDescriptor;
    this.endpoint = endpoint;
    this.httpJsonCallOptions = httpJsonCallOptions;
    this.httpTransport = httpTransport;
    this.headers = headers;
    this.resultListener = resultListener;
  }

  // Best effort cancellation without guarantees.
  // It will check if the task cancelled before each three sequential potentially time-consuming
  // operations:
  //   - request construction;
  //   - request execution (the most time consuming, taking);
  //   - response construction.
  void cancel() {
    cancelled = true;
  }

  @Override
  public void run() {
    HttpResponse httpResponse = null;
    RunnableResult.Builder result = RunnableResult.builder();
    HttpJsonMetadata.Builder trailers = HttpJsonMetadata.newBuilder();
    HttpRequest httpRequest = null;
    try {
      // Check if already cancelled before even creating a request
      if (cancelled) {
        return;
      }
      httpRequest = createHttpRequest();
      // Check if already cancelled before sending the request;
      if (cancelled) {
        return;
      }

      httpResponse = httpRequest.execute();

      // Check if already cancelled before sending the request;
      if (cancelled) {
        httpResponse.disconnect();
        return;
      }
      result.setResponseHeaders(
          HttpJsonMetadata.newBuilder().setHeaders(httpResponse.getHeaders()).build());
      result.setStatusCode(httpResponse.getStatusCode());
      result.setResponseContent(httpResponse.getContent());
      trailers.setStatusMessage(httpResponse.getStatusMessage());
    } catch (HttpResponseException e) {
      result.setStatusCode(e.getStatusCode());
      result.setResponseHeaders(HttpJsonMetadata.newBuilder().setHeaders(e.getHeaders()).build());
      result.setResponseContent(
          e.getContent() != null
              ? new ByteArrayInputStream(e.getContent().getBytes(StandardCharsets.UTF_8))
              : null);
      trailers.setStatusMessage(e.getStatusMessage());
      trailers.setException(e);
    } catch (Throwable e) {
      if (httpResponse != null) {
        trailers.setStatusMessage(httpResponse.getStatusMessage());
        result.setStatusCode(httpResponse.getStatusCode());
      } else {
        result.setStatusCode(400);
      }
      trailers.setException(e);
    } finally {
      if (!cancelled) {
        resultListener.setResult(result.setTrailers(trailers.build()).build());
      }
    }
  }

  HttpRequest createHttpRequest() throws IOException {
    GenericData tokenRequest = new GenericData();

    HttpRequestFormatter<RequestT> requestFormatter = methodDescriptor.getRequestFormatter();

    HttpRequestFactory requestFactory;
    Credentials credentials = httpJsonCallOptions.getCredentials();
    if (credentials != null) {
      requestFactory = httpTransport.createRequestFactory(new HttpCredentialsAdapter(credentials));
    } else {
      requestFactory = httpTransport.createRequestFactory();
    }

    JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
    // Create HTTP request body.
    String requestBody = requestFormatter.getRequestBody(request);
    HttpContent jsonHttpContent;
    if (!Strings.isNullOrEmpty(requestBody)) {
      jsonFactory.createJsonParser(requestBody).parse(tokenRequest);
      jsonHttpContent =
          new JsonHttpContent(jsonFactory, tokenRequest)
              .setMediaType((new HttpMediaType("application/json")));
    } else {
      // Force underlying HTTP lib to set Content-Length header to avoid 411s.
      // See EmptyContent.java.
      jsonHttpContent = new EmptyContent();
    }

    // Populate URL path and query parameters.
    String normalizedEndpoint = normalizeEndpoint(endpoint);
    GenericUrl url = new GenericUrl(normalizedEndpoint + requestFormatter.getPath(request));
    Map<String, List<String>> queryParams = requestFormatter.getQueryParamNames(request);
    for (Entry<String, List<String>> queryParam : queryParams.entrySet()) {
      if (queryParam.getValue() != null) {
        url.set(queryParam.getKey(), queryParam.getValue());
      }
    }

    HttpRequest httpRequest = buildRequest(requestFactory, url, jsonHttpContent);

    Instant deadline = httpJsonCallOptions.getDeadline();
    if (deadline != null) {
      long readTimeout = Duration.between(Instant.now(), deadline).toMillis();
      if (httpRequest.getReadTimeout() > 0
          && httpRequest.getReadTimeout() < readTimeout
          && readTimeout < Integer.MAX_VALUE) {
        httpRequest.setReadTimeout((int) readTimeout);
      }
    }

    for (Map.Entry<String, Object> entry : headers.getHeaders().entrySet()) {
      HttpHeadersUtils.setHeader(
          httpRequest.getHeaders(), entry.getKey(), (String) entry.getValue());
    }

    httpRequest.setParser(new JsonObjectParser(jsonFactory));

    return httpRequest;
  }

  private HttpRequest buildRequest(
      HttpRequestFactory requestFactory, GenericUrl url, HttpContent jsonHttpContent)
      throws IOException {
    // A workaround to support PATCH request. This assumes support of "X-HTTP-Method-Override"
    // header on the server side, which GCP services usually do.
    //
    // Long story short, the problems is as follows: gax-httpjson depends on NetHttpTransport class
    // from google-http-client, which depends on JDK standard java.net.HttpUrlConnection, which does
    // not support PATCH http method.
    //
    // It is a won't fix for JDK8: https://bugs.openjdk.java.net/browse/JDK-8207840.
    // A corresponding google-http-client issue:
    // https://github.com/googleapis/google-http-java-client/issues/167
    //
    // In JDK11 there is java.net.http.HttpRequest with PATCH method support but, gax-httpjson must
    // remain compatible with Java 8.
    //
    // Using "X-HTTP-Method-Override" header is probably the cleanest way to fix it. Other options
    // would be: hideous reflection hacks (not a safe option in a generic library, which
    // gax-httpjson is), writing own implementation of HttpUrlConnection (fragile and a lot of
    // work), depending on v2.ApacheHttpTransport (it has many extra dependencies, does not support
    // mtls etc).
    String actualHttpMethod = methodDescriptor.getHttpMethod();
    String originalHttpMethod = actualHttpMethod;
    if (HttpMethods.PATCH.equals(actualHttpMethod)) {
      actualHttpMethod = HttpMethods.POST;
    }
    HttpRequest httpRequest = requestFactory.buildRequest(actualHttpMethod, url, jsonHttpContent);
    if (originalHttpMethod != null && !originalHttpMethod.equals(actualHttpMethod)) {
      HttpHeadersUtils.setHeader(
          httpRequest.getHeaders(), "X-HTTP-Method-Override", originalHttpMethod);
    }
    return httpRequest;
  }

  // This will be frequently executed, so avoiding using regexps if not necessary.
  private String normalizeEndpoint(String rawEndpoint) {
    String normalized = rawEndpoint;
    // Set protocol as https by default if not set explicitly
    if (!normalized.contains("://")) {
      normalized = "https://" + normalized;
    }

    if (normalized.charAt(normalized.length() - 1) != '/') {
      normalized += '/';
    }

    return normalized;
  }

  @FunctionalInterface
  interface ResultListener {
    void setResult(RunnableResult result);
  }

  @AutoValue
  abstract static class RunnableResult {
    @Nullable
    abstract HttpJsonMetadata getResponseHeaders();

    abstract int getStatusCode();

    @Nullable
    abstract InputStream getResponseContent();

    abstract HttpJsonMetadata getTrailers();

    public static Builder builder() {
      return new AutoValue_HttpRequestRunnable_RunnableResult.Builder();
    }

    @AutoValue.Builder
    public abstract static class Builder {

      public abstract Builder setResponseHeaders(HttpJsonMetadata newResponseHeaders);

      public abstract Builder setStatusCode(int newStatusCode);

      public abstract Builder setResponseContent(InputStream newResponseContent);

      public abstract Builder setTrailers(HttpJsonMetadata newTrailers);

      public abstract RunnableResult build();
    }
  }
}


text:
export default function crashNested() {
  const a = 1;
  throw new Error('Nested test error');
}


text:
LOGGER(NetworkManager);

class PeerRequest
{
public:
    QVariant toVariant()
    {
        QVariantMap map;
        map.insert("type", "peer_request");
        map.insert("measurementDefinition", measurementDefinition);
        map.insert("taskId", taskId.toInt());
        map.insert("measurementUuid", measurementUuid);
        map.insert("measurement", measurement);
        map.insert("peer", peer);
        map.insert("port", port);
        map.insert("protocol", protocol);
        return map;
    }

    static PeerRequest fromVariant(const QVariant &variant)
    {
        QVariantMap map = variant.toMap();

        PeerRequest request;
        request.measurementDefinition = map.value("measurementDefinition");
        request.taskId = TaskId(map.value("taskId").toInt());
        request.measurementUuid = map.value("measurementUuid").toUuid();
        request.measurement = map.value("measurement").toString();
        request.peer = map.value("peer").toString();
        request.port = map.value("port").toUInt();
        request.protocol = (NetworkManager::SocketType)map.value("protocol").toInt();
        return request;
    }

    QVariant measurementDefinition;
    TaskId taskId;
    QUuid measurementUuid;
    QString measurement;
    QString peer;
    quint16 port;
    NetworkManager::SocketType protocol;
};

class NetworkManager::Private : public QObject
{
    Q_OBJECT

public:
    Private(NetworkManager *q)
    : q(q)
#if defined(Q_OS_ANDROID)
    , networkInfo("de/hsaugsburg/informatik/mplane/NetInfo")
#endif
    {
        connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
        connect(&keepaliveAddressLookup, SIGNAL(finished()), this, SLOT(lookupFinished()));

        keepaliveAddressLookup.setType(QDnsLookup::A);
    }

    NetworkManager *q;

    // Properties
    QMutex mutex;
    QHash<QString, QObject *> objectHash;
    QHash<QString, QAbstractSocket *> socketHash;

    QTimer timer;
    QPointer<QUdpSocket> socket;
    QPointer<Scheduler> scheduler;
    QPointer<Settings> settings;

    QSet<QUuid> handledMeasureUuids;

    quint16 localPort;

    RemoteHost keepaliveHost;
    QHostAddress keepaliveAddress;
    QDnsLookup keepaliveAddressLookup;

    QNetworkConfigurationManager ncm;
#if defined(Q_OS_ANDROID)
    QAndroidJniObject networkInfo;
#elif defined(Q_OS_IOS)
#else
    QNetworkInfo networkInfo;
#endif

    // Functions
    QAbstractSocket *createSocket(NetworkManager::SocketType socketType);

    void updateSocket();
    void updateTimer();
    void processDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port);

public slots:
    void socketDestroyed(QObject *obj);
    void responseChanged();
    void timeout();
    void onDatagramReady();
    void lookupFinished();
};

QAbstractSocket *NetworkManager::Private::createSocket(NetworkManager::SocketType socketType)
{
    QAbstractSocket *socket = NULL;

    switch (socketType)
    {
    case TcpSocket:
        socket = new ::TcpSocket;
        break;

    case UdpSocket:
        socket = new ::UdpSocket;
        break;

    case UtpSocket:
        //socket = new UtpSocket;
        break;

    default:
        break;
    }

    if (socket)
    {
        connect(socket, SIGNAL(destroyed(QObject *)), this, SLOT(socketDestroyed(QObject *)));
    }

    return socket;
}

void NetworkManager::Private::socketDestroyed(QObject *obj)
{
    QString hostname = objectHash.key(obj);

    if (hostname.isEmpty())
    {
        return;
    }

    objectHash.remove(hostname);
    socketHash.remove(hostname);
}

void NetworkManager::Private::updateSocket()
{
    if (!socket.isNull())
    {
        delete socket.data();
        socket.clear();
    }

    if (!keepaliveHost.isValid())
    {
        return;
    }

    localPort = keepaliveHost.port;

    socket = qobject_cast<QUdpSocket *>(q->createConnection(NetworkManager::UdpSocket));
    socket->setParent(this);
    connect(socket.data(), SIGNAL(readyRead()), this, SLOT(onDatagramReady()));

    if (!socket->bind(keepaliveHost.port))
    {
        LOG_ERROR(QString("Unable to bind port %1: %2").arg(keepaliveHost.port).arg(socket->errorString()));
    }
}

void NetworkManager::Private::updateTimer()
{
    TimingPtr timing = settings->config()->keepaliveTiming();

    if (!timing)
    {
        return;
    }

    QSharedPointer<PeriodicTiming> periodicTiming = timing.dynamicCast<PeriodicTiming>();
    Q_ASSERT(periodicTiming);

    int interval = periodicTiming->interval();

    if (interval < 1000)
    {
        LOG_ERROR("Keepalive interval < 1 sec will not be accepted.");
        return;
    }
    else
    {
        if (timer.interval() != interval)
        {
            LOG_DEBUG(QString("Keepalive set to %1 sec.").arg(interval / 1000));
        }
    }

    timer.setInterval(interval);
    timer.start();
}

class NetworkManagerMeasurementObserver : public MeasurementObserver
{
public:
    NetworkManager *networkManager;
    NetworkManager::SocketType socketType;
    quint16 localPort;

    QHostAddress host;
    quint16 port;

    QUuid measurementUuid;

    // MeasurementObserver interface
    void created(const MeasurementPtr &measurement)
    {
        QAbstractSocket *socket = networkManager->createConnection(socketType);

        QUdpSocket *udpSocket = qobject_cast<QUdpSocket *>(socket);

        if (!udpSocket->bind(localPort))
        {
            LOG_ERROR("Cannot bind socket");
            return;
        }

        // ACK the connection
        udpSocket->writeDatagram(QByteArray(), host, port);
        measurement->setPeerSocket(udpSocket);
        measurement->setMeasurementUuid(measurementUuid);
    }
};

void NetworkManager::Private::processDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)
{
    QString hostAndPort = QString("%1:%2").arg(host.toString()).arg(port);

    if (datagram.isEmpty())
    {
        LOG_DEBUG(QString("Received empty datagram from %1").arg(hostAndPort));
        return;
    }

    LOG_DEBUG(QString("Received datagram from %1: %2").arg(hostAndPort).arg(QString::fromUtf8(datagram)));
    //    if (settings->config()->keepaliveAddress() == hostAndPort) {
    // Master server
    QJsonParseError error;
    QJsonDocument document = QJsonDocument::fromJson(datagram, &error);

    if (error.error == QJsonParseError::NoError)
    {
        QJsonObject root = document.object();

        QString replyError = root.value("error").toString();

        if (!replyError.isEmpty())
        {
            LOG_ERROR(QString("Error from server: %1").arg(root.value("error").toString()));
            return;
        }

        PeerRequest request = PeerRequest::fromVariant(document.toVariant());

        if (handledMeasureUuids.contains(request.measurementUuid))
        {
            LOG_DEBUG("Measurement uuid is already handled, skipping second try");
            return;
        }

        handledMeasureUuids.insert(request.measurementUuid);

        MeasurementObserver *observer = NULL;

        if (request.protocol == NetworkManager::UdpSocket)
        {
            NetworkManagerMeasurementObserver *tempObs = new NetworkManagerMeasurementObserver;
            tempObs->networkManager = q;
            tempObs->socketType = request.protocol;
            tempObs->localPort = 5106; // TODO: Don't hardcode this here
            tempObs->host = host; //request.peer;
            tempObs->port = port;
            tempObs->measurementUuid = request.measurementUuid;

            observer = tempObs;
        }

        // TODO: We can't assign the Peer socket to Measurement since this is created in a separate thread
        //        and we can't access.

        TimingPtr timing(new ImmediateTiming);
        ScheduleDefinition testDefinition(ScheduleId(0), request.taskId, request.measurement, timing,
                                      request.measurementDefinition, Precondition());

        // Bypass scheduler and run directly on the executor
        scheduler->executor()->execute(testDefinition, observer);
    }
    else
    {
        LOG_ERROR(QString("Invalid JSon: %1").arg(error.errorString()));
    }

    //    } else {
    // TODO: Process incoming data
    //    }
}

void NetworkManager::Private::responseChanged()
{
    // Update the keepalive host address
    keepaliveHost = NetworkHelper::remoteHost(settings->config()->keepaliveAddress());

    updateSocket();
    //updateTimer(); TODO: deactivated for now

    // Lookup the host
    keepaliveAddressLookup.setName(keepaliveHost.host);
    keepaliveAddressLookup.lookup();
}

void NetworkManager::Private::timeout()
{
    if (keepaliveAddress.isNull())
    {
        LOG_WARNING("Invalid keepalive address (normal at first app start)");
        return;
    }

    QString sessionId = settings->apiKey();

    if (sessionId.isEmpty())
    {
        LOG_WARNING("Empty session id");
        return;
    }

    QStringList srcIp;
    srcIp.append(NetworkHelper::localIpAddress().toString());

    QVariantMap map;
    map.insert("type", "keepalive");
    map.insert("session_id", sessionId);
    map.insert("src_ip", srcIp);
    map.insert("src_port", localPort);

    QByteArray data = QJsonDocument::fromVariant(map).toJson();
    socket->writeDatagram(data, keepaliveAddress, keepaliveHost.port);

    LOG_DEBUG("Alive packet sent");
}

void NetworkManager::Private::onDatagramReady()
{
    while (socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());

        QHostAddress host;
        quint16 port;
        socket->readDatagram(datagram.data(), datagram.size(), &host, &port);

        // Process the datagram
        processDatagram(datagram, host, port);
    }
}

void NetworkManager::Private::lookupFinished()
{
    return; // TODO disabled for now
    // Check for errors
    if (keepaliveAddressLookup.error() != QDnsLookup::NoError)
    {
        LOG_ERROR(QString("Unable to look up host %1: %2").arg(keepaliveAddressLookup.name()).arg(keepaliveAddressLookup.errorString()));
        return;
    }

    foreach(const QDnsHostAddressRecord& record, keepaliveAddressLookup.hostAddressRecords())
    {
        // TODO: Take multiple host records
        QHostAddress value = record.value();
        if (!value.isNull())
        {
            keepaliveAddress = value;
            timeout();
            break;
        }
    }
}

NetworkManager::NetworkManager(QObject *parent)
: QObject(parent)
, d(new Private(this))
{
}

NetworkManager::~NetworkManager()
{
    delete d;
}

bool NetworkManager::init(Scheduler *scheduler, Settings *settings)
{
    connect(settings->config(), SIGNAL(responseChanged()), d, SLOT(responseChanged()));

    d->scheduler = scheduler;
    d->settings = settings;
    d->responseChanged();

    emit d->ncm.updateConfigurations();

    return true;
}

void NetworkManager::setRunning(bool running)
{
    if (isRunning() == running)
    {
        return;
    }

    if (!running)
    {
        d->timer.stop();
    }
    else
    {
        d->updateTimer();
    }
}

bool NetworkManager::isRunning() const
{
    return d->timer.isActive();
}

bool NetworkManager::onMobileConnection() const
{
#if defined(Q_OS_ANDROID)
     return d->networkInfo.callMethod<jboolean>("isOnMobileConnection");
#else
    QNetworkInfo::NetworkMode mode = connectionMode();

    if (mode != QNetworkInfo::WlanMode && mode != QNetworkInfo::EthernetMode)
    {
        LOG_DEBUG(QString("Connection type: %1").arg(mode));
        return true;
    }

    return false;
#endif
}

QNetworkInfo::NetworkMode NetworkManager::connectionMode() const
{
    QNetworkInfo::NetworkMode mode;

#if defined(Q_OS_ANDROID)
    mode = static_cast<QNetworkInfo::NetworkMode>(d->networkInfo.callMethod<jint>("connectionMode"));
#elif defined(Q_OS_IOS)
    mode = QNetworkInfo::WlanMode;
#else
    mode = d->networkInfo.currentNetworkMode();
    // QNetworkInfo does not check for the linux "Predictable Network Interface Names".
    // The following code fixes this.
    if (mode == QNetworkInfo::UnknownMode)
    {
        QList<QNetworkConfiguration> confList = d->ncm.allConfigurations(QNetworkConfiguration::Active);

        foreach (const QNetworkConfiguration &conf, confList)
        {
            QString name = conf.name();

            if (name.contains("enp"))
            {
                return QNetworkInfo::EthernetMode;
            }

            if (name.contains("wlp"))
            {
                return QNetworkInfo::WlanMode;
            }
        }
    }
#endif

    return mode;
}

QAbstractSocket *NetworkManager::connection(const QString &hostname, NetworkManager::SocketType socketType) const
{
    Q_UNUSED(socketType);
    return d->socketHash.value(hostname);
}

QAbstractSocket *NetworkManager::createConnection(NetworkManager::SocketType socketType)
{
    QAbstractSocket *socket = d->createSocket(socketType);

    if (!socket)
    {
        LOG_ERROR("Unknown socket type requested");
        return NULL;
    }

    //d->socketHash.insert(hostname, socket);
    //d->objectHash.insert(hostname, socket);

    return socket;
}

QAbstractSocket *NetworkManager::establishConnection(const QString &hostname,
                                                     const TaskId &taskId,
                                                     const QString &measurement,
                                                     MeasurementDefinitionPtr measurementDefinition,
                                                     NetworkManager::SocketType socketType)
{
    QAbstractSocket *socket = d->createSocket(socketType);

    if (!socket)
    {
        LOG_ERROR("Unknown socket type requested");
        return NULL;
    }

    RemoteHost remote = NetworkHelper::remoteHost(hostname);
    RemoteHost aliveRemote = d->keepaliveHost;

    if (false && d->keepaliveAddress.isNull()) // TODO deactivated for now
    {
        LOG_ERROR(QString("Invalid keepalivealive address: '%1' can't talk to alive server").arg(
                      d->keepaliveAddress.toString()));
        delete socket;
        return NULL;
    }

    measurementDefinition->measurementUuid = QUuid::createUuid();

    PeerRequest request;
    request.measurement = measurement;
    request.taskId = taskId;
    request.measurementDefinition = measurementDefinition->toVariant();
    request.measurementUuid = measurementDefinition->measurementUuid;
    request.peer = remote.host;
    request.port = aliveRemote.port;
    request.protocol = socketType;

    // If for some reason our packet gets routed back to us, don't handle it
    d->handledMeasureUuids.insert(measurementDefinition->measurementUuid);

    QUdpSocket *testSocket = d->socket.data();

    if (socketType != TcpSocket)
    {
        if (!socket->bind(remote.port))
        {
            LOG_ERROR(QString("Unable to bind source port to %1").arg(remote.port));
            delete socket;
            return NULL;
        }

        QUdpSocket *udpSocket = qobject_cast<QUdpSocket *>(socket);
        udpSocket->writeDatagram(QByteArray(), QHostAddress(remote.host), remote.port);

        testSocket = udpSocket;
    }

    QByteArray data = QJsonDocument::fromVariant(request.toVariant()).toJson();

    // Step one: Send test offer to peer directly
    testSocket->writeDatagram(data, QHostAddress(remote.host), d->localPort);

    // Step two: Send test offer to peer via alive-server
    //testSocket->writeDatagram(data, d->keepaliveAddress, aliveRemote.port); // TODO deactivated for now

    LOG_TRACE("Sent test offer to peer and alive-server");

    if (socketType != UdpSocket)
    {
        // Final step: Connect to remote host
        //if (socket->waitForReadyRead(5000))
        //    return socket;

        const int tries = 20;

        for (int i = 0; i < tries; ++i)
        {
            socket->connectToHost(remote.host, remote.port);

            if (socket->waitForConnected(5000 / tries))
            {
                return socket;
            }
        }

        LOG_ERROR(QString("Unable to connect tcp socket in %3 tries to %1: %2").arg(hostname).arg(socket->errorString()).arg(
                      tries));
    }
    else
    {
        if (!testSocket->waitForReadyRead(5000))
        {
            LOG_ERROR("Remote did not answer for 5 sec, aborting connection.");
        }
        else
        {
            // TODO: Read the first (empty) datagram
            QHostAddress packetHost;
            testSocket->readDatagram(0, 0, &packetHost);

            if (packetHost != QHostAddress(remote.host))
            {
                LOG_ERROR("Received connection packet from wrong host!");
            }
            else
            {
                return socket;
            }
        }
    }

    delete socket;
    return NULL;
}

QTcpServer *NetworkManager::createServerSocket()
{
    // TODO: Connect to traffic counter
    QTcpServer *server = new QTcpServer;
    return server;
}

bool NetworkManager::allInterfacesDown() const
{
    QNetworkInterface::InterfaceFlags flags;

    foreach (const QNetworkInterface &iface, QNetworkInterface::allInterfaces())
    {
        flags = iface.flags();

        if (flags & QNetworkInterface::IsLoopBack)
        {
            continue;
        }

        if (flags & (QNetworkInterface::IsUp | QNetworkInterface::IsRunning))
        {
            return false;
        }
    }

    return true;
}

#include "networkmanager.moc"


text:
<?php

namespace EnliteSeo\Exception;

class OverflowException extends RuntimeException
{

}


text:
package com.support.android.designlibdemo;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;

public class ExampleNotification {
        /**
         * A numeric value that identifies the notification that we'll be sending.
         * This value needs to be unique within this app, but it doesn't need to be
         * unique system-wide.
         */
        public static final int NOTIFICATION_ID = 1;
        private static final String NOMBRE_APP = "Red De Mascotas";
        private String texto;
        private Resources resources;
        private NotificationManager notificationManager;
        private Activity activity;

        public ExampleNotification(Resources resources, NotificationManager notificationManager, Activity activity, String texto){
            this.resources = resources;
            this.notificationManager = notificationManager; //TODO: (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            this.activity = activity;
            this.texto = texto;
        }

        /**
         * Send a sample notification using the NotificationCompat API.
         */
        public void sendNotification() {

            // BEGIN_INCLUDE(build_action)
            /** Create an intent that will be fired when the user clicks the notification.
             * The intent needs to be packaged into a {@link android.app.PendingIntent} so that the
             * notification service can fire it on our behalf.
             */

//            Intent intent = new Intent(getApplicationContext(), NotificationActivity.class);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://developer.android.com/reference/android/app/Notification.html"));
            PendingIntent pendingIntent = PendingIntent.getActivity(this.activity, 0, intent, 0);
            // END_INCLUDE(build_action)

            // BEGIN_INCLUDE (build_notification)
            /**
             * Use NotificationCompat.Builder to set up our notification.
             */
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this.activity);

            /** Set the icon that will appear in the notification bar. This icon also appears
             * in the lower right hand corner of the notification itself.
             */
            builder.setSmallIcon(R.drawable.footprint3);

            // Set the intent that will fire when the user taps the notification.
            builder.setContentIntent(pendingIntent);

            // Set the notification to auto-cancel. This means that the notification will disappear
            // after the user taps it, rather than remaining until it's explicitly dismissed.
            builder.setAutoCancel(true);

            /**
             *Build the notification's appearance.
             * Set the large icon, which appears on the left of the notification. In this
             * sample we'll set the large icon to be the same as our app icon. The app icon is a
             * reasonable default if you don't have anything more compelling to use as an icon.
             */
            builder.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.footprint1));

            /**
             * Set the text of the notification. This sample sets the three most commononly used
             * text areas:
             * 1. The content title, which appears in large type at the top of the notification
             * 2. The content text, which appears in smaller text below the title
             * 3. The subtext, which appears under the text on newer devices. Devices running
             *    versions of Android prior to 4.2 will ignore this field, so don't use it for
             *    anything vital!
             */
            builder.setContentTitle(NOMBRE_APP);
            builder.setContentText("Hay nuevas publicaciones similares a tu búsqueda");
            builder.setSubText("");

            // END_INCLUDE (build_notification)

            // BEGIN_INCLUDE(send_notification)
            /**
             * Send the notification. This will immediately display the notification icon in the
             * notification bar.
             */
            this.notificationManager.notify(NOTIFICATION_ID, builder.build());
            // END_INCLUDE(send_notification)
        }
    }


text:
action :osx_install do
  system("R -q -e \"options(repos='#{new_resource.mirror}'); if(!('#{new_resource.name}' %in% rownames(installed.packages()))){ install.packages('#{new_resource.name}')}\"")
end

# This action will update a package on OS X.
action :osx_update do
  system("R -q -e \"options(repos='#{new_resource.mirror}'); update.packages(ask='FALSE')\"")
end

# This action install a package on Windows
action :win_install do
	system("\"C:\\Program Files\\R\\R-3.0.2\\bin\\R.exe\" -q -e \"options(repos='#{new_resource.mirror}'); if(!('#{new_resource.name}' %in% rownames(installed.packages()))){ install.packages('#{new_resource.name}')}\"")
end

# This action will update a package on Windows.
action :win_update do
	system("\"C:\\Program Files\\R\\R-3.0.2\\bin\\R.exe\" -q -e \"options(repos='#{new_resource.mirror}'); update.packages(ask='FALSE')\"")
end


text:
package org.jboss.gravia.runtime.spi;

import static org.jboss.gravia.runtime.spi.RuntimeLogger.LOGGER;

import java.net.URL;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.jboss.gravia.Constants;
import org.jboss.gravia.resource.Attachable;
import org.jboss.gravia.resource.AttachmentKey;
import org.jboss.gravia.resource.DictionaryResourceBuilder;
import org.jboss.gravia.resource.Resource;
import org.jboss.gravia.resource.ResourceBuilder;
import org.jboss.gravia.resource.ResourceIdentity;
import org.jboss.gravia.resource.Version;
import org.jboss.gravia.resource.spi.AttachableSupport;
import org.jboss.gravia.runtime.Module;
import org.jboss.gravia.runtime.ModuleContext;
import org.jboss.gravia.runtime.Runtime;
import org.jboss.gravia.runtime.ServiceReference;
import org.jboss.gravia.utils.CaseInsensitiveDictionary;
import org.jboss.gravia.utils.IllegalArgumentAssertion;
import org.jboss.gravia.utils.UnmodifiableDictionary;
import org.osgi.framework.Bundle;

/**
 * The abstract base implementaiton for all {@link Module}s.
 *
 * @author thomas.diesler@jboss.com
 * @since 27-Sep-2013
 */
public abstract class AbstractModule implements Module, Attachable {

    public static AttachmentKey<ModuleEntriesProvider> MODULE_ENTRIES_PROVIDER_KEY = AttachmentKey.create(ModuleEntriesProvider.class);

    private final AbstractRuntime runtime;
    private final ClassLoader classLoader;
    private final Resource resource;
    private final Dictionary<String, String> headers;
    private final Attachable attachments = new AttachableSupport();
    private final ConcurrentHashMap<ServiceReference<?>, AtomicInteger> usedServices = new ConcurrentHashMap<ServiceReference<?>, AtomicInteger>();

    protected AbstractModule(AbstractRuntime runtime, ClassLoader classLoader, Resource resource, Dictionary<String, String> headers) {
        IllegalArgumentAssertion.assertNotNull(runtime, "runtime");
        IllegalArgumentAssertion.assertNotNull(classLoader, "classLoader");
        this.runtime = runtime;
        this.classLoader = classLoader;

        // One of the two must be given to determine the identity
        if (resource == null && headers == null)
            throw new IllegalArgumentException("Cannot create module identity");

        // Build the resource
        if (resource == null) {
            ResourceBuilder builder = new DictionaryResourceBuilder().load(headers);
            resource = builder.getResource();
        }
        this.resource = resource;

        // Build the headers
        ResourceIdentity resourceIdentity = resource.getIdentity();
        Hashtable<String, String> clonedHeaders = new Hashtable<String, String>();
        if (headers != null) {
            Enumeration<String> keys = headers.keys();
            while(keys.hasMoreElements()) {
                String key = keys.nextElement();
                String value = headers.get(key);
                clonedHeaders.put(key, value);
            }
        }
        if (clonedHeaders.get(Constants.GRAVIA_IDENTITY_CAPABILITY) == null) {
            String identityHeader = getIdentityHeader(resourceIdentity);
            clonedHeaders.put(Constants.GRAVIA_IDENTITY_CAPABILITY, identityHeader);
        }
        this.headers = new UnmodifiableDictionary<String, String>(new CaseInsensitiveDictionary<String>(clonedHeaders));

        // Verify the resource & headers identity
        ResourceIdentity headersIdentity = new DictionaryResourceBuilder().load(clonedHeaders).getResource().getIdentity();
        if (!resourceIdentity.equals(headersIdentity))
            throw new IllegalArgumentException("Resource and header identity does not match: " + resourceIdentity);
    }

    public static AbstractModule assertAbstractModule(Module module) {
        if (!(module instanceof AbstractModule))
            throw new IllegalArgumentException("Not an AbstractModule: " + module);
        return (AbstractModule) module;
    }

    private String getIdentityHeader(ResourceIdentity identity) {
        String symbolicName = identity.getSymbolicName();
        Version version = identity.getVersion();
        return symbolicName + ";version=" + version;
    }

    protected abstract void setState(State newState);

    protected AbstractRuntime getRuntime() {
        return runtime;
    }

    protected ClassLoader getClassLoader() {
        return classLoader;
    }

    @Override
    public ResourceIdentity getIdentity() {
        return resource.getIdentity();
    }

    @Override
    @SuppressWarnings("unchecked")
    public <A> A adapt(Class<A> type) {
        A result = null;
        if (type.isAssignableFrom(Bundle.class)) {
            result = (A) getBundleAdaptor(this);
        } else if (type.isAssignableFrom(Runtime.class)) {
            result = (A) runtime;
        } else if (type.isAssignableFrom(AbstractRuntime.class)) {
            result = (A) runtime;
        } else if (type.isAssignableFrom(ClassLoader.class)) {
            result = (A) classLoader;
        } else if (type.isAssignableFrom(Resource.class)) {
            result = (A) resource;
        } else if (type.isAssignableFrom(Module.class)) {
            result = (A) this;
        } else if (type.isAssignableFrom(ModuleContext.class)) {
            result = (A) getModuleContext();
        } else if (type.isAssignableFrom(ModuleEntriesProvider.class)) {
            result = (A) getAttachment(MODULE_ENTRIES_PROVIDER_KEY);
        }
        return result;
    }

    protected abstract Bundle getBundleAdaptor(Module module);

    @Override
    public <T> T putAttachment(AttachmentKey<T> key, T value) {
        return attachments.putAttachment(key, value);
    }

    @Override
    public <T> T getAttachment(AttachmentKey<T> key) {
        return attachments.getAttachment(key);
    }

    @Override
    public <T> boolean hasAttachment(AttachmentKey<T> key) {
        return attachments.hasAttachment(key);
    }

    @Override
    public <T> T removeAttachment(AttachmentKey<T> key) {
        return attachments.removeAttachment(key);
    }

    @Override
    public Class<?> loadClass(String className) throws ClassNotFoundException {
        assertNotUninstalled();
        return classLoader.loadClass(className);
    }

    @Override
    public Dictionary<String, String> getHeaders() {
        return headers;
    }

    @Override
    public URL getEntry(String path) {
        ModuleEntriesProvider entriesProvider = adapt(ModuleEntriesProvider.class);
        return entriesProvider != null ? entriesProvider.getEntry(path) : null;
    }

    @Override
    public List<String> getEntryPaths(String path) {
        ModuleEntriesProvider entriesProvider = adapt(ModuleEntriesProvider.class);
        return entriesProvider != null ? entriesProvider.getEntryPaths(path) : Collections.<String>emptyList();
    }

    @Override
    public List<URL> findEntries(String path, String filePattern, boolean recurse) {
        ModuleEntriesProvider entriesProvider = adapt(ModuleEntriesProvider.class);
        return entriesProvider != null ? entriesProvider.findEntries(path, filePattern, recurse) : Collections.<URL>emptyList();
    }

    public Set<ServiceReference<?>> getServicesInUseInternal() {
        return Collections.unmodifiableSet(usedServices.keySet());
    }

    public void addServiceInUse(ServiceReference<?> serviceState) {
        LOGGER.trace("Add service in use {} to: {}", serviceState, this);
        usedServices.putIfAbsent(serviceState, new AtomicInteger());
        AtomicInteger count = usedServices.get(serviceState);
        count.incrementAndGet();
    }

    public int removeServiceInUse(ServiceReference<?> serviceState) {
        LOGGER.trace("Remove service in use {} from: {}", serviceState, this);
        AtomicInteger count = usedServices.get(serviceState);
        if (count == null)
            return -1;

        int countVal = count.decrementAndGet();
        if (countVal == 0)
            usedServices.remove(serviceState);

        return countVal;
    }

    protected void assertNotUninstalled() {
        if (getState() == State.UNINSTALLED)
            throw new IllegalStateException("Module already uninstalled: " + this);
    }

    @Override
    public String toString() {
        return "Module[" + getIdentity() + "]";
    }
}


text:
using System;
using System.IO;

namespace Qotd
{
	public static class Program
	{
		public static void Main(string[] args)
		{
			if (args.Length <=0)
			{
				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine("You must specify a quotes file.");
				Console.ResetColor();
				return;
			}
			var quotes = File.ReadAllLines(args[0]);
			var randomQuote = quotes[new Random().Next(0, quotes.Length-1)];

			Console.WriteLine("[QOTD]: {0}", randomQuote);
		}
	}
}


text:
'use strict';

import React from 'react';
import ChatMessages from './ChatMessages'
import Composition from './Composition'

const ChatWindow = () => <div className="col-md-9">
      <ChatMessages></ChatMessages>
      <Composition></Composition>
    </div>;

export default ChatWindow;


text:
#include "mdc.h"

#include <QMutex>
#include <QThread>
#include "helpers/initialisationhelper.h"
#include "logger.h"

namespace Log4Qt
{

QString MDC::get(const QString &key)
{
    if (!instance()->mHash.hasLocalData())
        return QString();

    return instance()->mHash.localData()->value(key);
}

QHash<QString, QString> MDC::context()
{
    if (!instance()->mHash.hasLocalData())
        return QHash<QString, QString>();

    return *instance()->mHash.localData();
}

LOG4QT_IMPLEMENT_INSTANCE(MDC)

QHash<QString, QString> *MDC::localData()
{
    if (!instance()->mHash.hasLocalData())
        instance()->mHash.setLocalData(new QHash<QString, QString>);
    return instance()->mHash.localData();
}
} // namespace Log4Qt


text:
#ifndef TSQLQUERYORMAPPERITERATOR_H
#define TSQLQUERYORMAPPERITERATOR_H

#include <TSqlQueryORMapper>

template <class T>
class TSqlQueryORMapperIterator {
public:
    TSqlQueryORMapperIterator(TSqlQueryORMapper<T> &mapper) :
        m(&mapper), it(0) { }

    bool hasNext() const { return (it >= 0 && it < m->size()); }
    bool hasPrevious() const { return (it > 0 && it <= m->size()); }
    T next();
    T previous();
    void toBack()
    {
        m->last();
        it = m->size();
    }
    void toFront()
    {
        m->first();
        it = 0;
    }
    T value() const { return m->value(); }

private:
    TSqlQueryORMapperIterator(const TSqlQueryORMapperIterator<T> &);
    TSqlQueryORMapperIterator<T> &operator=(const TSqlQueryORMapperIterator<T> &);

    TSqlQueryORMapper<T> *m;
    int it;
};

/*!
  Returns the next object and advances the iterator by one position.
*/
template <class T>
inline T TSqlQueryORMapperIterator<T>::next()
{
    if (it++ != m->at()) {
        m->next();
    }
    return m->value();
}

/*!
  Returns the previous object and moves the iterator back by one
  position.
*/
template <class T>
inline T TSqlQueryORMapperIterator<T>::previous()
{
    if (--it != m->at()) {
        m->previous();
    }
    return m->value();
}

#endif  // TSQLQUERYORMAPPERITERATOR_H


text:
package me.newyith.fortress.util;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class BatchDataStore {
	private static BatchDataStore instance = null;
	public static BatchDataStore getInstance() {
		if (instance == null) {
			instance = new BatchDataStore();
		}
		return instance;
	}
	public static void setInstance(BatchDataStore newInstance) {
		instance = newInstance;
	}

	//-----------------------------------------------------------------------

	private static class Model {
		private final Map<UUID, BatchData> dataByUuid;

		@JsonCreator
		public Model(@JsonProperty("dataByUuid") Map<UUID, BatchData> dataByUuid) {
			this.dataByUuid = dataByUuid;

			//rebuild transient fields
		}
	}
	private Model model = null;

	@JsonCreator
	public BatchDataStore(@JsonProperty("model") Model model) {
		this.model = model;
	}

	public BatchDataStore() {
		model = new Model(new HashMap<>());
	}

	//-----------------------------------------------------------------------

	public static BatchData get(UUID uuid) {
		return getInstance().model.dataByUuid.get(uuid);
	}

	public static void put(UUID uuid, BatchData batchData) {
		getInstance().model.dataByUuid.put(uuid, batchData);
	}

	public static void remove(UUID uuid) {
		getInstance().model.dataByUuid.remove(uuid);
	}
}


text:
MVN_FLAGS="-Dmaven.compiler.source=15 -Dmaven.compiler.target=15 -DskipTests"
ALL_JARS=""

# install the build servers' jazzer-api into the maven repository
pushd "/tmp"
	${MVN} install:install-file -Dfile=${JAZZER_API_PATH} \
		-DgroupId="com.code-intelligence" \
		-DartifactId="jazzer-api" \
		-Dversion="0.12.0" \
		-Dpackaging=jar
popd

pushd "${SRC}/org.aspectj"
	${MVN} package ${MVN_FLAGS}
	${MVN} install ${MVN_FLAGS}
	CURRENT_VERSION=$(${MVN} org.apache.maven.plugins:maven-help-plugin:3.2.0:evaluate \
  -Dexpression=project.version -q -DforceStdout)
popd

pushd ${SRC}
	${MVN} package -DaspectjVersion="${CURRENT_VERSION}" ${MVN_FLAGS}
	install -v target/aspectj-fuzzer-${CURRENT_VERSION}.jar ${OUT}/aspectj-fuzzer-${CURRENT_VERSION}.jar
	ALL_JARS="${ALL_JARS} aspectj-fuzzer-${CURRENT_VERSION}.jar"
popd

# The classpath at build-time includes the project jars in $OUT as well as the
# Jazzer API.
BUILD_CLASSPATH=$(echo $ALL_JARS | xargs printf -- "$OUT/%s:"):$JAZZER_API_PATH

# All .jar and .class files lie in the same directory as the fuzzer at runtime.
RUNTIME_CLASSPATH=$(echo $ALL_JARS | xargs printf -- "\$this_dir/%s:"):\$this_dir

MVN_FUZZERS_PREFIX="src/main/java"

for fuzzer in $(find ${SRC} -name '*Fuzzer.java'); do
  stripped_path=$(echo ${fuzzer} | sed 's|^.*src/main/java/\(.*\).java$|\1|');
  # the .java was stripped by sed
  if (echo ${stripped_path} | grep ".java$"); then
	continue;
  fi

  fuzzer_basename=$(basename -s .java $fuzzer)
  fuzzer_classname=$(echo ${stripped_path} | sed 's|/|.|g');

  # Create an execution wrapper that executes Jazzer with the correct arguments.
  echo "#!/bin/bash
# LLVMFuzzerTestOneInput for fuzzer detection.
this_dir=\$(dirname \"\$0\")
if [[ \"\$@\" =~ (^| )-runs=[0-9]+($| ) ]]; then
  mem_settings='-Xmx1900m:-Xss900k'
else
  mem_settings='-Xmx2048m:-Xss1024k'
fi
LD_LIBRARY_PATH=\"$JVM_LD_LIBRARY_PATH\":\$this_dir \
\$this_dir/jazzer_driver --agent_path=\$this_dir/jazzer_agent_deploy.jar \
--cp=${RUNTIME_CLASSPATH} \
--target_class=${fuzzer_classname} \
--jvm_args=\"\$mem_settings\" \
\$@" > $OUT/${fuzzer_basename}
  chmod u+x $OUT/${fuzzer_basename}
done


text:
package org.jboss.resteasy.jsapi.testing.form;

import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;

/**
 * 12 03 2012
 *
 * @author Weinan Li
 */
public class MyForm2 {
    @FormParam("stuff")
    private String stuff;

    @FormParam("number")
    private int number;

    @HeaderParam("myHeader")
    private String header;

    public String getStuff() {
        return stuff;
    }

    public void setStuff(String stuff) {
        this.stuff = stuff;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
}


text:
static NSString * const kMUPAPIBaseURLString = @"https://jawbone.com/";

@implementation MUPAPIClient

+ (MUPAPIClient*)sharedClient {
    static MUPAPIClient *_shareClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _shareClient = [[MUPAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kMUPAPIBaseURLString]];
    });

    return _shareClient;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];

    if (!self) {
        return nil;
    }

    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];

    [self setDefaultHeader:@"Accept" value:@"application/json"];

    return self;
}

//- (void)requestUPWithPath:(NSString *)path
//               parameters:(NSDictionary *)parameters
//                 response:(void (^)(NSArray *socialFeeds))success
//                  failure:(void (^)(NSError *error))failure {
//
//    [super getPath:path
//        parameters:parameters
//           success:^(AFHTTPRequestOperation *operation, id responseObject) {
//
//               NSArray *feeds = [[responseObject valueForKey:@"data"] valueForKey:@"feed"];
//               NSMutableArray *socialFeeds = [[NSMutableArray alloc] initWithCapacity:feeds.count];
//
//               NSLog(@"ResponseObject:%@", feeds);
//
//               dispatch_queue_t feedsCreationQueue = dispatch_queue_create("com.mup.feedcreation", NULL);
//
//               dispatch_async(feedsCreationQueue, ^{
//
//                   for (NSDictionary *feed in feeds) {
//                       SocialFeed *socialFeed = [[SocialFeed alloc] initWithFeedAttributes:feed];
//                       [socialFeeds addObject:socialFeed];
//                   }
//                   success(socialFeeds);
//
//               });
//
//           }
//           failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//               failure(error);
//           }];
//}

@end


text:
/**
 *
 */
package br.unifor.pin.agendamento.managers;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import br.unifor.pin.agendamento.business.UsuarioBO;
import br.unifor.pin.agendamento.entity.Usuarios;
import br.unifor.pin.agendamento.filter.SessionContext;
import br.unifor.pin.agendamento.to.SegurancaTO;
import br.unifor.pin.agendamento.utils.Encripta;
import br.unifor.pin.agendamento.utils.MessagesUtils;
import br.unifor.pin.agendamento.utils.Navigation;

/**
 * @author patrick.cunha
 * @since 26/06/2015
 */
@RequestScoped
@Component(value = "login")
@ManagedBean(name = "login")
public class LoginManager {

	@Autowired
	private UsuarioBO usuarioBO;
	@Autowired
	private SegurancaTO seguranca;
	@Autowired
	private SessionContext sessao;

	@Autowired
	private SolicitacaoManager solicitacaoManagedBean;

	@Autowired
	private AgendamentoManager agendamentoManagedBean;

	private Usuarios usuario = new Usuarios();
	private boolean existsEmail;

	public String loggar() {
		sessao.limparSessao();
		Usuarios usuario = this.usuarioBO.loggar(this.usuario.getMatricula(),
				Encripta.encripta(this.usuario.getSenha()));
		this.usuario = new Usuarios();
		if (usuario != null) {
			seguranca.setUsuario(usuario);
			existsEmail = true;
			solicitacaoManagedBean.carregarListas();
			solicitacaoManagedBean.retornaCoordenador();
			agendamentoManagedBean.carregarListas();
			MessagesUtils.info("Bem vindo "+usuario.getNome());
			return Navigation.SUCESSO;
		} else {
			existsEmail = false;
			MessagesUtils.error("O e-mail ou a senha inseridos estão incorretos.");
			return Navigation.FRACASSO;
		}
	}

	public String cadastrar(){
		return Navigation.CADASTRA;
	}

	/**
	 * @return the usuario
	 */
	public Usuarios getUsuario() {
		return usuario;
	}

	/**
	 * @param usuario
	 *            the usuario to set
	 */
	public void setUsuario(Usuarios usuario) {
		this.usuario = usuario;
	}

	/**
	 * @return the existsEmail
	 */
	public boolean isExistsEmail() {
		return existsEmail;
	}

	/**
	 * @param existsEmail
	 *            the existsEmail to set
	 */
	public void setExistsEmail(boolean existsEmail) {
		this.existsEmail = existsEmail;
	}

	public SolicitacaoManager getSolicitacaoManagedBean() {
		return solicitacaoManagedBean;
	}

	public void setSolicitacaoManagedBean(SolicitacaoManager solicitacaoManagedBean) {
		this.solicitacaoManagedBean = solicitacaoManagedBean;
	}

}


text:
using Microsoft.Extensions.DependencyInjection;

namespace Cofoundry.Domain.CQS.Internal;

/// <summary>
/// Factory to create ICommandHandler instances
/// </summary>
public class CommandHandlerFactory : ICommandHandlerFactory
{
    private readonly IServiceProvider _serviceProvider;

    public CommandHandlerFactory(
        IServiceProvider serviceProvider
        )
    {
        _serviceProvider = serviceProvider;
    }

    /// <summary>
    /// Creates a new IAsyncCommandHandler instance with the specified type signature.
    /// </summary>
    public ICommandHandler<T> CreateAsyncHandler<T>() where T : ICommand
    {
        return _serviceProvider.GetRequiredService<ICommandHandler<T>>();
    }
}


text:
#pragma once
#include <aws/elasticache/ElastiCache_EXPORTS.h>
#include <aws/elasticache/ElastiCacheRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace ElastiCache
{
namespace Model
{

  /**
   *
Represents the input of a DescribeCacheClusters
   * operation.

See Also:
   AWS
   * API Reference

   */
  class AWS_ELASTICACHE_API DescribeCacheClustersRequest : public ElastiCacheRequest
  {
  public:
    DescribeCacheClustersRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DescribeCacheClusters"; }

    Aws::String SerializePayload() const override;

  protected:
    void DumpBodyToUrl(Aws::Http::URI& uri ) const override;

  public:

    /**
     *
The user-supplied cluster identifier. If this parameter is specified, only
     * information about that specific cluster is returned. This parameter isn't case
     * sensitive.

     */
    inline const Aws::String& GetCacheClusterId() const{ return m_cacheClusterId; }

    /**
     *
The user-supplied cluster identifier. If this parameter is specified, only
     * information about that specific cluster is returned. This parameter isn't case
     * sensitive.

     */
    inline void SetCacheClusterId(const Aws::String& value) { m_cacheClusterIdHasBeenSet = true; m_cacheClusterId = value; }

    /**
     *
The user-supplied cluster identifier. If this parameter is specified, only
     * information about that specific cluster is returned. This parameter isn't case
     * sensitive.

     */
    inline void SetCacheClusterId(Aws::String&& value) { m_cacheClusterIdHasBeenSet = true; m_cacheClusterId = std::move(value); }

    /**
     *
The user-supplied cluster identifier. If this parameter is specified, only
     * information about that specific cluster is returned. This parameter isn't case
     * sensitive.

     */
    inline void SetCacheClusterId(const char* value) { m_cacheClusterIdHasBeenSet = true; m_cacheClusterId.assign(value); }

    /**
     *
The user-supplied cluster identifier. If this parameter is specified, only
     * information about that specific cluster is returned. This parameter isn't case
     * sensitive.

     */
    inline DescribeCacheClustersRequest& WithCacheClusterId(const Aws::String& value) { SetCacheClusterId(value); return *this;}

    /**
     *
The user-supplied cluster identifier. If this parameter is specified, only
     * information about that specific cluster is returned. This parameter isn't case
     * sensitive.

     */
    inline DescribeCacheClustersRequest& WithCacheClusterId(Aws::String&& value) { SetCacheClusterId(std::move(value)); return *this;}

    /**
     *
The user-supplied cluster identifier. If this parameter is specified, only
     * information about that specific cluster is returned. This parameter isn't case
     * sensitive.

     */
    inline DescribeCacheClustersRequest& WithCacheClusterId(const char* value) { SetCacheClusterId(value); return *this;}

    /**
     *
The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a marker is included in
     * the response so that the remaining results can be retrieved.

Default:
     * 100

Constraints: minimum 20; maximum 100.

     */
    inline int GetMaxRecords() const{ return m_maxRecords; }

    /**
     *
The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a marker is included in
     * the response so that the remaining results can be retrieved.

Default:
     * 100

Constraints: minimum 20; maximum 100.

     */
    inline void SetMaxRecords(int value) { m_maxRecordsHasBeenSet = true; m_maxRecords = value; }

    /**
     *
The maximum number of records to include in the response. If more records
     * exist than the specified MaxRecords value, a marker is included in
     * the response so that the remaining results can be retrieved.

Default:
     * 100

Constraints: minimum 20; maximum 100.

     */
    inline DescribeCacheClustersRequest& WithMaxRecords(int value) { SetMaxRecords(value); return *this;}

    /**
     *
An optional marker returned from a prior request. Use this marker for
     * pagination of results from this operation. If this parameter is specified, the
     * response includes only records beyond the marker, up to the value specified by
     * MaxRecords.

     */
    inline const Aws::String& GetMarker() const{ return m_marker; }

    /**
     *
An optional marker returned from a prior request. Use this marker for
     * pagination of results from this operation. If this parameter is specified, the
     * response includes only records beyond the marker, up to the value specified by
     * MaxRecords.

     */
    inline void SetMarker(const Aws::String& value) { m_markerHasBeenSet = true; m_marker = value; }

    /**
     *
An optional marker returned from a prior request. Use this marker for
     * pagination of results from this operation. If this parameter is specified, the
     * response includes only records beyond the marker, up to the value specified by
     * MaxRecords.

     */
    inline void SetMarker(Aws::String&& value) { m_markerHasBeenSet = true; m_marker = std::move(value); }

    /**
     *
An optional marker returned from a prior request. Use this marker for
     * pagination of results from this operation. If this parameter is specified, the
     * response includes only records beyond the marker, up to the value specified by
     * MaxRecords.

     */
    inline void SetMarker(const char* value) { m_markerHasBeenSet = true; m_marker.assign(value); }

    /**
     *
An optional marker returned from a prior request. Use this marker for
     * pagination of results from this operation. If this parameter is specified, the
     * response includes only records beyond the marker, up to the value specified by
     * MaxRecords.

     */
    inline DescribeCacheClustersRequest& WithMarker(const Aws::String& value) { SetMarker(value); return *this;}

    /**
     *
An optional marker returned from a prior request. Use this marker for
     * pagination of results from this operation. If this parameter is specified, the
     * response includes only records beyond the marker, up to the value specified by
     * MaxRecords.

     */
    inline DescribeCacheClustersRequest& WithMarker(Aws::String&& value) { SetMarker(std::move(value)); return *this;}

    /**
     *
An optional marker returned from a prior request. Use this marker for
     * pagination of results from this operation. If this parameter is specified, the
     * response includes only records beyond the marker, up to the value specified by
     * MaxRecords.

     */
    inline DescribeCacheClustersRequest& WithMarker(const char* value) { SetMarker(value); return *this;}

    /**
     *
An optional flag that can be included in the
     * DescribeCacheCluster request to retrieve information about the
     * individual cache nodes.

     */
    inline bool GetShowCacheNodeInfo() const{ return m_showCacheNodeInfo; }

    /**
     *
An optional flag that can be included in the
     * DescribeCacheCluster request to retrieve information about the
     * individual cache nodes.

     */
    inline void SetShowCacheNodeInfo(bool value) { m_showCacheNodeInfoHasBeenSet = true; m_showCacheNodeInfo = value; }

    /**
     *
An optional flag that can be included in the
     * DescribeCacheCluster request to retrieve information about the
     * individual cache nodes.

     */
    inline DescribeCacheClustersRequest& WithShowCacheNodeInfo(bool value) { SetShowCacheNodeInfo(value); return *this;}

    /**
     *
An optional flag that can be included in the
     * DescribeCacheCluster request to show only nodes (API/CLI: clusters)
     * that are not members of a replication group. In practice, this mean Memcached
     * and single node Redis clusters.

     */
    inline bool GetShowCacheClustersNotInReplicationGroups() const{ return m_showCacheClustersNotInReplicationGroups; }

    /**
     *
An optional flag that can be included in the
     * DescribeCacheCluster request to show only nodes (API/CLI: clusters)
     * that are not members of a replication group. In practice, this mean Memcached
     * and single node Redis clusters.

     */
    inline void SetShowCacheClustersNotInReplicationGroups(bool value) { m_showCacheClustersNotInReplicationGroupsHasBeenSet = true; m_showCacheClustersNotInReplicationGroups = value; }

    /**
     *
An optional flag that can be included in the
     * DescribeCacheCluster request to show only nodes (API/CLI: clusters)
     * that are not members of a replication group. In practice, this mean Memcached
     * and single node Redis clusters.

     */
    inline DescribeCacheClustersRequest& WithShowCacheClustersNotInReplicationGroups(bool value) { SetShowCacheClustersNotInReplicationGroups(value); return *this;}

  private:

    Aws::String m_cacheClusterId;
    bool m_cacheClusterIdHasBeenSet;

    int m_maxRecords;
    bool m_maxRecordsHasBeenSet;

    Aws::String m_marker;
    bool m_markerHasBeenSet;

    bool m_showCacheNodeInfo;
    bool m_showCacheNodeInfoHasBeenSet;

    bool m_showCacheClustersNotInReplicationGroups;
    bool m_showCacheClustersNotInReplicationGroupsHasBeenSet;
  };

} // namespace Model
} // namespace ElastiCache
} // namespace Aws


text:
栏目管理中心

+ 新增

            <select ng-model='c.parent'>
                <option ng-repeat="parent in parents" value="{{parent._id}}">{{parent.name}}</option>
            </select>
            <input type="text" ng-model="c.name" placeholder="输入栏目名称" >
            <button class="pure-button pure-button-primary" ng-click="addClass($index)" style="font-size: 12px">添加</button>

                {{parent.childCount}}

                {{parent.name}}

{{item.name}}

删除

修改