text:
/* Cluster IP hashmark target
 * (C) 2003-2004 by Harald Welte <laforge@netfilter.org>
 * based on ideas of Fabio Olive Leite <olive@unixforge.org>
 *
 * Development of this code funded by SuSE Linux AG, http://www.suse.com/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 */
#include <linux/module.h>
#include <linux/config.h>
#include <linux/proc_fs.h>
#include <linux/jhash.h>
#include <linux/bitops.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/icmp.h>
#include <linux/if_arp.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>

#include <net/checksum.h>

#include <linux/netfilter_arp.h>

#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/netfilter_ipv4/ipt_CLUSTERIP.h>
#include <net/netfilter/nf_conntrack_compat.h>

#define CLUSTERIP_VERSION "0.8"

#define DEBUG_CLUSTERIP

#ifdef DEBUG_CLUSTERIP
#define DEBUGP	printk
#else
#define DEBUGP
#endif

#define ASSERT_READ_LOCK(x)

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
MODULE_DESCRIPTION("iptables target for CLUSTERIP");

struct clusterip_config {
	struct list_head list;			/* list of all configs */
	atomic_t refcount;			/* reference count */
	atomic_t entries;			/* number of entries/rules
						 * referencing us */

	u_int32_t clusterip;			/* the IP address */
	u_int8_t clustermac[ETH_ALEN];		/* the MAC address */
	struct net_device *dev;			/* device */
	u_int16_t num_total_nodes;		/* total number of nodes */
	unsigned long local_nodes;		/* node number array */

#ifdef CONFIG_PROC_FS
	struct proc_dir_entry *pde;		/* proc dir entry */
#endif
	enum clusterip_hashmode hash_mode;	/* which hashing mode */
	u_int32_t hash_initval;			/* hash initialization */
};

static LIST_HEAD(clusterip_configs);

/* clusterip_lock protects the clusterip_configs list */
static DEFINE_RWLOCK(clusterip_lock);

#ifdef CONFIG_PROC_FS
static struct file_operations clusterip_proc_fops;
static struct proc_dir_entry *clusterip_procdir;
#endif

static inline void
clusterip_config_get(struct clusterip_config *c)
{
	atomic_inc(&c->refcount);
}

static inline void
clusterip_config_put(struct clusterip_config *c)
{
	if (atomic_dec_and_test(&c->refcount))
		kfree(c);
}

/* increase the count of entries(rules) using/referencing this config */
static inline void
clusterip_config_entry_get(struct clusterip_config *c)
{
	atomic_inc(&c->entries);
}

/* decrease the count of entries using/referencing this config.  If last
 * entry(rule) is removed, remove the config from lists, but don't free it
 * yet, since proc-files could still be holding references */
static inline void
clusterip_config_entry_put(struct clusterip_config *c)
{
	if (atomic_dec_and_test(&c->entries)) {
		write_lock_bh(&clusterip_lock);
		list_del(&c->list);
		write_unlock_bh(&clusterip_lock);

		dev_mc_delete(c->dev, c->clustermac, ETH_ALEN, 0);
		dev_put(c->dev);

		/* In case anyone still accesses the file, the open/close
		 * functions are also incrementing the refcount on their own,
		 * so it's safe to remove the entry even if it's in use. */
#ifdef CONFIG_PROC_FS
		remove_proc_entry(c->pde->name, c->pde->parent);
#endif
	}
}

static struct clusterip_config *
__clusterip_config_find(u_int32_t clusterip)
{
	struct list_head *pos;

	ASSERT_READ_LOCK(&clusterip_lock);
	list_for_each(pos, &clusterip_configs) {
		struct clusterip_config *c = list_entry(pos,
					struct clusterip_config, list);
		if (c->clusterip == clusterip) {
			return c;
		}
	}

	return NULL;
}

static inline struct clusterip_config *
clusterip_config_find_get(u_int32_t clusterip, int entry)
{
	struct clusterip_config *c;

	read_lock_bh(&clusterip_lock);
	c = __clusterip_config_find(clusterip);
	if (!c) {
		read_unlock_bh(&clusterip_lock);
		return NULL;
	}
	atomic_inc(&c->refcount);
	if (entry)
		atomic_inc(&c->entries);
	read_unlock_bh(&clusterip_lock);

	return c;
}

static void
clusterip_config_init_nodelist(struct clusterip_config *c,
			       const struct ipt_clusterip_tgt_info *i)
{
	int n;

	for (n = 0; n < i->num_local_nodes; n++) {
		set_bit(i->local_nodes[n] - 1, &c->local_nodes);
	}
}

static struct clusterip_config *
clusterip_config_init(struct ipt_clusterip_tgt_info *i, u_int32_t ip,
			struct net_device *dev)
{
	struct clusterip_config *c;
	char buffer[16];

	c = kmalloc(sizeof(*c), GFP_ATOMIC);
	if (!c)
		return NULL;

	memset(c, 0, sizeof(*c));
	c->dev = dev;
	c->clusterip = ip;
	memcpy(&c->clustermac, &i->clustermac, ETH_ALEN);
	c->num_total_nodes = i->num_total_nodes;
	clusterip_config_init_nodelist(c, i);
	c->hash_mode = i->hash_mode;
	c->hash_initval = i->hash_initval;
	atomic_set(&c->refcount, 1);
	atomic_set(&c->entries, 1);

#ifdef CONFIG_PROC_FS
	/* create proc dir entry */
	sprintf(buffer, "%u.%u.%u.%u", NIPQUAD(ip));
	c->pde = create_proc_entry(buffer, S_IWUSR|S_IRUSR, clusterip_procdir);
	if (!c->pde) {
		kfree(c);
		return NULL;
	}
	c->pde->proc_fops = &clusterip_proc_fops;
	c->pde->data = c;
#endif

	write_lock_bh(&clusterip_lock);
	list_add(&c->list, &clusterip_configs);
	write_unlock_bh(&clusterip_lock);

	return c;
}

static int
clusterip_add_node(struct clusterip_config *c, u_int16_t nodenum)
{

	if (nodenum == 0 ||
	    nodenum > c->num_total_nodes)
		return 1;

	/* check if we already have this number in our bitfield */
	if (test_and_set_bit(nodenum - 1, &c->local_nodes))
		return 1;

	return 0;
}

static int
clusterip_del_node(struct clusterip_config *c, u_int16_t nodenum)
{
	if (nodenum == 0 ||
	    nodenum > c->num_total_nodes)
		return 1;

	if (test_and_clear_bit(nodenum - 1, &c->local_nodes))
		return 0;

	return 1;
}

static inline u_int32_t
clusterip_hashfn(struct sk_buff *skb, struct clusterip_config *config)
{
	struct iphdr *iph = skb->nh.iph;
	unsigned long hashval;
	u_int16_t sport, dport;
	struct tcphdr *th;
	struct udphdr *uh;
	struct icmphdr *ih;

	switch (iph->protocol) {
	case IPPROTO_TCP:
		th = (void *)iph+iph->ihl*4;
		sport = ntohs(th->source);
		dport = ntohs(th->dest);
		break;
	case IPPROTO_UDP:
		uh = (void *)iph+iph->ihl*4;
		sport = ntohs(uh->source);
		dport = ntohs(uh->dest);
		break;
	case IPPROTO_ICMP:
		ih = (void *)iph+iph->ihl*4;
		sport = ntohs(ih->un.echo.id);
		dport = (ih->type<<8)|ih->code;
		break;
	default:
		if (net_ratelimit()) {
			printk(KERN_NOTICE "CLUSTERIP: unknown protocol `%u'\n",
				iph->protocol);
		}
		sport = dport = 0;
	}

	switch (config->hash_mode) {
	case CLUSTERIP_HASHMODE_SIP:
		hashval = jhash_1word(ntohl(iph->saddr),
				      config->hash_initval);
		break;
	case CLUSTERIP_HASHMODE_SIP_SPT:
		hashval = jhash_2words(ntohl(iph->saddr), sport,
				       config->hash_initval);
		break;
	case CLUSTERIP_HASHMODE_SIP_SPT_DPT:
		hashval = jhash_3words(ntohl(iph->saddr), sport, dport,
				       config->hash_initval);
		break;
	default:
		/* to make gcc happy */
		hashval = 0;
		/* This cannot happen, unless the check function wasn't called
		 * at rule load time */
		printk("CLUSTERIP: unknown mode `%u'\n", config->hash_mode);
		BUG();
		break;
	}

	/* node numbers are 1..n, not 0..n */
	return ((hashval % config->num_total_nodes)+1);
}

static inline int
clusterip_responsible(struct clusterip_config *config, u_int32_t hash)
{
	return test_bit(hash - 1, &config->local_nodes);
}

/***********************************************************************
 * IPTABLES TARGET
 ***********************************************************************/

static unsigned int
target(struct sk_buff **pskb,
       const struct net_device *in,
       const struct net_device *out,
       unsigned int hooknum,
       const void *targinfo,
       void *userinfo)
{
	const struct ipt_clusterip_tgt_info *cipinfo = targinfo;
	enum ip_conntrack_info ctinfo;
	u_int32_t *mark, hash;

	/* don't need to clusterip_config_get() here, since refcount
	 * is only decremented by destroy() - and ip_tables guarantees
	 * that the ->target() function isn't called after ->destroy() */

	mark = nf_ct_get_mark((*pskb), &ctinfo);
	if (mark == NULL) {
		printk(KERN_ERR "CLUSTERIP: no conntrack!\n");
			/* FIXME: need to drop invalid ones, since replies
			 * to outgoing connections of other nodes will be
			 * marked as INVALID */
		return NF_DROP;
	}

	/* special case: ICMP error handling. conntrack distinguishes between
	 * error messages (RELATED) and information requests (see below) */
	if ((*pskb)->nh.iph->protocol == IPPROTO_ICMP
	    && (ctinfo == IP_CT_RELATED
		|| ctinfo == IP_CT_RELATED+IP_CT_IS_REPLY))
		return IPT_CONTINUE;

	/* ip_conntrack_icmp guarantees us that we only have ICMP_ECHO,
	 * TIMESTAMP, INFO_REQUEST or ADDRESS type icmp packets from here
	 * on, which all have an ID field [relevant for hashing]. */

	hash = clusterip_hashfn(*pskb, cipinfo->config);

	switch (ctinfo) {
		case IP_CT_NEW:
			*mark = hash;
			break;
		case IP_CT_RELATED:
		case IP_CT_RELATED+IP_CT_IS_REPLY:
			/* FIXME: we don't handle expectations at the
			 * moment.  they can arrive on a different node than
			 * the master connection (e.g. FTP passive mode) */
		case IP_CT_ESTABLISHED:
		case IP_CT_ESTABLISHED+IP_CT_IS_REPLY:
			break;
		default:
			break;
	}

#ifdef DEBUG_CLUSTERP
	DUMP_TUPLE(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
#endif
	DEBUGP("hash=%u ct_hash=%u ", hash, *mark);
	if (!clusterip_responsible(cipinfo->config, hash)) {
		DEBUGP("not responsible\n");
		return NF_DROP;
	}
	DEBUGP("responsible\n");

	/* despite being received via linklayer multicast, this is
	 * actually a unicast IP packet. TCP doesn't like PACKET_MULTICAST */
	(*pskb)->pkt_type = PACKET_HOST;

	return IPT_CONTINUE;
}

static int
checkentry(const char *tablename,
	   const void *e_void,
           void *targinfo,
           unsigned int targinfosize,
           unsigned int hook_mask)
{
	struct ipt_clusterip_tgt_info *cipinfo = targinfo;
	const struct ipt_entry *e = e_void;

	struct clusterip_config *config;

	if (targinfosize != IPT_ALIGN(sizeof(struct ipt_clusterip_tgt_info))) {
		printk(KERN_WARNING "CLUSTERIP: targinfosize %u != %Zu\n",
		       targinfosize,
		       IPT_ALIGN(sizeof(struct ipt_clusterip_tgt_info)));
		return 0;
	}

	if (cipinfo->hash_mode != CLUSTERIP_HASHMODE_SIP &&
	    cipinfo->hash_mode != CLUSTERIP_HASHMODE_SIP_SPT &&
	    cipinfo->hash_mode != CLUSTERIP_HASHMODE_SIP_SPT_DPT) {
		printk(KERN_WARNING "CLUSTERIP: unknown mode `%u'\n",
			cipinfo->hash_mode);
		return 0;

	}
	if (e->ip.dmsk.s_addr != 0xffffffff
	    || e->ip.dst.s_addr == 0) {
		printk(KERN_ERR "CLUSTERIP: Please specify destination IP\n");
		return 0;
	}

	/* FIXME: further sanity checks */

	config = clusterip_config_find_get(e->ip.dst.s_addr, 1);
	if (config) {
		if (cipinfo->config != NULL) {
			/* Case A: This is an entry that gets reloaded, since
			 * it still has a cipinfo->config pointer. Simply
			 * increase the entry refcount and return */
			if (cipinfo->config != config) {
				printk(KERN_ERR "CLUSTERIP: Reloaded entry "
				       "has invalid config pointer!\n");
				return 0;
			}
			clusterip_config_entry_get(cipinfo->config);
		} else {
			/* Case B: This is a new rule referring to an existing
			 * clusterip config. */
			cipinfo->config = config;
			clusterip_config_entry_get(cipinfo->config);
		}
	} else {
		/* Case C: This is a completely new clusterip config */
		if (!(cipinfo->flags & CLUSTERIP_FLAG_NEW)) {
			printk(KERN_WARNING "CLUSTERIP: no config found for %u.%u.%u.%u, need 'new'\n", NIPQUAD(e->ip.dst.s_addr));
			return 0;
		} else {
			struct net_device *dev;

			if (e->ip.iniface[0] == '\0') {
				printk(KERN_WARNING "CLUSTERIP: Please specify an interface name\n");
				return 0;
			}

			dev = dev_get_by_name(e->ip.iniface);
			if (!dev) {
				printk(KERN_WARNING "CLUSTERIP: no such interface %s\n", e->ip.iniface);
				return 0;
			}

			config = clusterip_config_init(cipinfo,
							e->ip.dst.s_addr, dev);
			if (!config) {
				printk(KERN_WARNING "CLUSTERIP: cannot allocate config\n");
				dev_put(dev);
				return 0;
			}
			dev_mc_add(config->dev,config->clustermac, ETH_ALEN, 0);
		}
		cipinfo->config = config;
	}

	return 1;
}

/* drop reference count of cluster config when rule is deleted */
static void destroy(void *matchinfo, unsigned int matchinfosize)
{
	struct ipt_clusterip_tgt_info *cipinfo = matchinfo;

	/* if no more entries are referencing the config, remove it
	 * from the list and destroy the proc entry */
	clusterip_config_entry_put(cipinfo->config);

	clusterip_config_put(cipinfo->config);
}

static struct ipt_target clusterip_tgt = {
	.name = "CLUSTERIP",
	.target = &target,
	.checkentry = &checkentry,
	.destroy = &destroy,
	.me = THIS_MODULE
};

/***********************************************************************
 * ARP MANGLING CODE
 ***********************************************************************/

/* hardcoded for 48bit ethernet and 32bit ipv4 addresses */
struct arp_payload {
	u_int8_t src_hw[ETH_ALEN];
	u_int32_t src_ip;
	u_int8_t dst_hw[ETH_ALEN];
	u_int32_t dst_ip;
} __attribute__ ((packed));

#ifdef CLUSTERIP_DEBUG
static void arp_print(struct arp_payload *payload)
{
#define HBUFFERLEN 30
	char hbuffer[HBUFFERLEN];
	int j,k;
	const char hexbuf[]= "0123456789abcdef";

	for (k=0, j=0; k < HBUFFERLEN-3 && j < ETH_ALEN; j++) {
		hbuffer[k++]=hexbuf[(payload->src_hw[j]>>4)&15];
		hbuffer[k++]=hexbuf[payload->src_hw[j]&15];
		hbuffer[k++]=':';
	}
	hbuffer[--k]='\0';

	printk("src %u.%u.%u.%u@%s, dst %u.%u.%u.%u\n",
		NIPQUAD(payload->src_ip), hbuffer,
		NIPQUAD(payload->dst_ip));
}
#endif

static unsigned int
arp_mangle(unsigned int hook,
	   struct sk_buff **pskb,
	   const struct net_device *in,
	   const struct net_device *out,
	   int (*okfn)(struct sk_buff *))
{
	struct arphdr *arp = (*pskb)->nh.arph;
	struct arp_payload *payload;
	struct clusterip_config *c;

	/* we don't care about non-ethernet and non-ipv4 ARP */
	if (arp->ar_hrd != htons(ARPHRD_ETHER)
	    || arp->ar_pro != htons(ETH_P_IP)
	    || arp->ar_pln != 4 || arp->ar_hln != ETH_ALEN)
		return NF_ACCEPT;

	/* we only want to mangle arp requests and replies */
	if (arp->ar_op != htons(ARPOP_REPLY)
	    && arp->ar_op != htons(ARPOP_REQUEST))
		return NF_ACCEPT;

	payload = (void *)(arp+1);

	/* if there is no clusterip configuration for the arp reply's
	 * source ip, we don't want to mangle it */
	c = clusterip_config_find_get(payload->src_ip, 0);
	if (!c)
		return NF_ACCEPT;

	/* normally the linux kernel always replies to arp queries of
	 * addresses on different interfacs.  However, in the CLUSTERIP case
	 * this wouldn't work, since we didn't subscribe the mcast group on
	 * other interfaces */
	if (c->dev != out) {
		DEBUGP("CLUSTERIP: not mangling arp reply on different "
		       "interface: cip'%s'-skb'%s'\n", c->dev->name, out->name);
		clusterip_config_put(c);
		return NF_ACCEPT;
	}

	/* mangle reply hardware address */
	memcpy(payload->src_hw, c->clustermac, arp->ar_hln);

#ifdef CLUSTERIP_DEBUG
	DEBUGP(KERN_DEBUG "CLUSTERIP mangled arp reply: ");
	arp_print(payload);
#endif

	clusterip_config_put(c);

	return NF_ACCEPT;
}

static struct nf_hook_ops cip_arp_ops = {
	.hook = arp_mangle,
	.pf = NF_ARP,
	.hooknum = NF_ARP_OUT,
	.priority = -1
};

/***********************************************************************
 * PROC DIR HANDLING
 ***********************************************************************/

#ifdef CONFIG_PROC_FS

struct clusterip_seq_position {
	unsigned int pos;	/* position */
	unsigned int weight;	/* number of bits set == size */
	unsigned int bit;	/* current bit */
	unsigned long val;	/* current value */
};

static void *clusterip_seq_start(struct seq_file *s, loff_t *pos)
{
	struct proc_dir_entry *pde = s->private;
	struct clusterip_config *c = pde->data;
	unsigned int weight;
	u_int32_t local_nodes;
	struct clusterip_seq_position *idx;

	/* FIXME: possible race */
	local_nodes = c->local_nodes;
	weight = hweight32(local_nodes);
	if (*pos >= weight)
		return NULL;

	idx = kmalloc(sizeof(struct clusterip_seq_position), GFP_KERNEL);
	if (!idx)
		return ERR_PTR(-ENOMEM);

	idx->pos = *pos;
	idx->weight = weight;
	idx->bit = ffs(local_nodes);
	idx->val = local_nodes;
	clear_bit(idx->bit - 1, &idx->val);

	return idx;
}

static void *clusterip_seq_next(struct seq_file *s, void *v, loff_t *pos)
{
	struct clusterip_seq_position *idx = (struct clusterip_seq_position *)v;

	*pos = ++idx->pos;
	if (*pos >= idx->weight) {
		kfree(v);
		return NULL;
	}
	idx->bit = ffs(idx->val);
	clear_bit(idx->bit - 1, &idx->val);
	return idx;
}

static void clusterip_seq_stop(struct seq_file *s, void *v)
{
	kfree(v);
}

static int clusterip_seq_show(struct seq_file *s, void *v)
{
	struct clusterip_seq_position *idx = (struct clusterip_seq_position *)v;

	if (idx->pos != 0)
		seq_putc(s, ',');

	seq_printf(s, "%u", idx->bit);

	if (idx->pos == idx->weight - 1)
		seq_putc(s, '\n');

	return 0;
}

static struct seq_operations clusterip_seq_ops = {
	.start	= clusterip_seq_start,
	.next	= clusterip_seq_next,
	.stop	= clusterip_seq_stop,
	.show	= clusterip_seq_show,
};

static int clusterip_proc_open(struct inode *inode, struct file *file)
{
	int ret = seq_open(file, &clusterip_seq_ops);

	if (!ret) {
		struct seq_file *sf = file->private_data;
		struct proc_dir_entry *pde = PDE(inode);
		struct clusterip_config *c = pde->data;

		sf->private = pde;

		clusterip_config_get(c);
	}

	return ret;
}

static int clusterip_proc_release(struct inode *inode, struct file *file)
{
	struct proc_dir_entry *pde = PDE(inode);
	struct clusterip_config *c = pde->data;
	int ret;

	ret = seq_release(inode, file);

	if (!ret)
		clusterip_config_put(c);

	return ret;
}

static ssize_t clusterip_proc_write(struct file *file, const char __user *input,
				size_t size, loff_t *ofs)
{
#define PROC_WRITELEN	10
	char buffer[PROC_WRITELEN+1];
	struct proc_dir_entry *pde = PDE(file->f_dentry->d_inode);
	struct clusterip_config *c = pde->data;
	unsigned long nodenum;

	if (copy_from_user(buffer, input, PROC_WRITELEN))
		return -EFAULT;

	if (*buffer == '+') {
		nodenum = simple_strtoul(buffer+1, NULL, 10);
		if (clusterip_add_node(c, nodenum))
			return -ENOMEM;
	} else if (*buffer == '-') {
		nodenum = simple_strtoul(buffer+1, NULL,10);
		if (clusterip_del_node(c, nodenum))
			return -ENOENT;
	} else
		return -EIO;

	return size;
}

static struct file_operations clusterip_proc_fops = {
	.owner	 = THIS_MODULE,
	.open	 = clusterip_proc_open,
	.read	 = seq_read,
	.write	 = clusterip_proc_write,
	.llseek	 = seq_lseek,
	.release = clusterip_proc_release,
};

#endif /* CONFIG_PROC_FS */

static int init_or_cleanup(int fini)
{
	int ret;

	if (fini)
		goto cleanup;

	if (ipt_register_target(&clusterip_tgt)) {
		ret = -EINVAL;
		goto cleanup_none;
	}

	if (nf_register_hook(&cip_arp_ops) < 0) {
		ret = -EINVAL;
		goto cleanup_target;
	}

#ifdef CONFIG_PROC_FS
	clusterip_procdir = proc_mkdir("ipt_CLUSTERIP", proc_net);
	if (!clusterip_procdir) {
		printk(KERN_ERR "CLUSTERIP: Unable to proc dir entry\n");
		ret = -ENOMEM;
		goto cleanup_hook;
	}
#endif /* CONFIG_PROC_FS */

	printk(KERN_NOTICE "ClusterIP Version %s loaded successfully\n",
		CLUSTERIP_VERSION);

	return 0;

cleanup:
	printk(KERN_NOTICE "ClusterIP Version %s unloading\n",
		CLUSTERIP_VERSION);
#ifdef CONFIG_PROC_FS
	remove_proc_entry(clusterip_procdir->name, clusterip_procdir->parent);
#endif
cleanup_hook:
	nf_unregister_hook(&cip_arp_ops);
cleanup_target:
	ipt_unregister_target(&clusterip_tgt);
cleanup_none:
	return -EINVAL;
}

static int __init init(void)
{
	return init_or_cleanup(0);
}

static void __exit fini(void)
{
	init_or_cleanup(1);
}

module_init(init);
module_exit(fini);


text:
namespace faint{

Optional<FilePath> get_crash_file();
void write_exception_log(const FilePath&);

} // namespace

#endif

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace MetricsStatsDSandboxMvc
{
    public class Startup
    {
        private const bool HaveAppRunSampleRequests = true;

        public Startup(IConfiguration configuration) { Configuration = configuration; }

        public IConfiguration Configuration { get; }

        public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime)
        {
            app.UseTestStuff(lifetime, HaveAppRunSampleRequests);

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTestStuff();

            services.AddMvc().AddMetrics();
        }
    }
}


text:
<!DOCTYPE html>
<html>

  <head>
    <title>Amber contrib: Web</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script type='text/javascript' src='the.js'></script>
  </head>

  <body>
  <script type='text/javascript'>
      require(['app'], function (amber) {
          amber.initialize({
            //used for all new packages in IDE
            'transport.defaultAmdNamespace': "amber/web"
          });
          require(["amber-ide-starter-dialog"], function (dlg) { dlg.start(); });
      });
  </script>
  </body>

</html>


text:
<?php
require_once('Module.php');

class Assets extends Module {

	public $module = '';

	public function __construct()
	{
		parent::__construct();
	}

	public function items()
	{
		$dirs = $this->fuel->assets->dirs();
		$this->filters['group_id']['options'] = $dirs;

		parent::items();
	}

	public function create($dir = NULL, $inline = FALSE)
	{
		$id = NULL;

		if ( ! empty($dir)) $dir = uri_safe_decode($dir);

		if ($inline !== FALSE) $this->fuel->admin->set_inline(TRUE);

		$inline = $this->fuel->admin->is_inline();

		if ( ! empty($_POST))
		{
			if (( ! empty($_FILES['userfile']) AND $_FILES['userfile']['error'] != 4) OR ( ! empty($_FILES['userfile___0']) AND $_FILES['userfile___0']['error'] != 4))
			{

				// cleanup $dir name with any trailing slashes
				$dir = trim($this->input->post_get('asset_folder', TRUE), '/');

				$this->model->on_before_post();

				if ($this->input->post('asset_folder'))
				{
					if ( ! in_array($dir, array_keys($this->fuel->assets->dirs())))
					{
						show_404();
					}
				}

				$subfolder = ($this->config->item('assets_allow_subfolder_creation', 'fuel')) ? str_replace('..'.DIRECTORY_SEPARATOR, '', $this->input->get_post('subfolder', TRUE)) : ''; // remove any going down the folder structure for protections
				$upload_path = $this->config->item('assets_server_path').$this->fuel->assets->dir($dir).DIRECTORY_SEPARATOR.$subfolder; //assets_server_path is in assets config

				$posted['upload_path'] = $upload_path;
				$posted['overwrite'] = ($this->input->post_get('overwrite')) ? TRUE : FALSE;
				$posted['create_thumb'] = ($this->input->post_get('create_thumb')) ? TRUE : FALSE;
				$posted['resize_method'] = ($this->input->post_get('resize_method')) ? $this->input->post_get('resize_method', TRUE) : 'maintain_ratio';
				$posted['resize_and_crop'] = $this->input->post_get('resize_and_crop', TRUE);
				$posted['width'] = $this->input->post_get('width', TRUE);
				$posted['height'] = $this->input->post_get('height', TRUE);
				$posted['master_dim'] = $this->input->post_get('master_dim', TRUE);
				$posted['file_name'] = $this->input->post_get('userfile_file_name', TRUE);
				//$posted['unzip'] = ($this->input->post_get('unzip')) ? TRUE : FALSE;
				$posted['remove_subfolder'] = $this->input->post_get('remove_subfolder', TRUE);
				$posted['upscale'] = $this->input->post_get('upscale', TRUE);

				$redirect_to = uri_safe_decode($this->input->post_get('redirect_to'));
				$id = $posted['file_name'];

				// run before_create hook
				$this->_run_hook('before_create', $posted);

				// run before_save hook
				$this->_run_hook('before_save', $posted);

				if ($this->fuel->assets->upload($posted))
				{
					foreach($_FILES as $filename => $fileinfo)
					{
						$msg = lang('module_edited', $this->module_name, $fileinfo['name']);
						$this->fuel->logs->write($msg);
					}

					// explicitly set the flash values to save cookie space
					$flashdata['asset_folder'] = $this->input->post('asset_folder', TRUE);
					$flashdata['userfile_file_name'] = $this->input->post('userfile_file_name', TRUE);
					$flashdata['subfolder'] = $this->input->post('subfolder', TRUE);
					$flashdata['overwrite'] = $this->input->post('overwrite', TRUE);
					$flashdata['resize_method'] = $this->input->post('resize_method', TRUE);
					$flashdata['width'] = $this->input->post('width', TRUE);
					$flashdata['height'] = $this->input->post('height', TRUE);
					$flashdata['resize_method'] = $this->input->post('resize_method', TRUE);
					$flashdata['master_dim'] = $this->input->post('master_dim', TRUE);
					$flashdata['resize_method'] = $this->input->post('resize_method', TRUE);
					$flashdata['upscale'] = $this->input->post('upscale', TRUE);

					$uploaded_data = $this->fuel->assets->uploaded_data();
					$first_file = current($uploaded_data);

					$uploaded_file_name_arr = array();
					$uploaded_file_webpath_arr = array();

					foreach($uploaded_data as $ud)
					{
						$uploaded_path = assets_server_path().$dir;

						if (is_true_val($posted['remove_subfolder']))
						{
							$uploaded_path = $uploaded_path .'/'.$subfolder;
						}
						$uploaded_file_name_arr[] = trim(str_replace($uploaded_path, '', $ud['full_path']), '/');
						$uploaded_file_webpath_arr[] = trim(assets_server_to_web_path($ud['full_path'], TRUE), '/');
					}

					// set the uploaded file name to a concatenated string separated by commas
					$uploaded_file_name = implode(', ', $uploaded_file_name_arr);
					$flashdata['uploaded_file_name'] = $uploaded_file_name;
					$flashdata['uploaded_file_webpath'] = $uploaded_file_webpath_arr;

					$this->session->set_flashdata('uploaded_post', $flashdata);
					$this->fuel->admin->set_notification(lang('data_saved'), Fuel_admin::NOTIFICATION_SUCCESS);

					$this->model->on_after_post($posted);

					$inline = $this->fuel->admin->is_inline();

					$query_str = query_str(array(), TRUE);

					if ( ! empty($redirect_to))
					{
						$url = $redirect_to;
					}
					else if ($inline === TRUE)
					{
						$url = fuel_uri($this->module.'/inline_create/'.uri_safe_encode($dir).$query_str, FALSE);
					}
					else
					{
						$url = fuel_uri($this->module.'/create/'.uri_safe_encode($dir).$query_str, FALSE);
					}

					redirect($url);
				}
				else
				{
					add_errors($this->fuel->assets->errors());
				}
			}
			else
			{
				add_errors(lang('error_upload'));
			}
		}

		$form_vars = $this->input->get(NULL, TRUE);

		if ( ! empty($dir)) $form_vars['asset_folder'] = $dir;

		$form_vars['asset_folder'] = (!empty($form_vars['asset_folder'])) ? trim($form_vars['asset_folder'], '/') : '';
		$vars = $this->_form($form_vars, $inline);
		$vars['related_items'] = $this->model->related_items($vars);
		$list_view = ($inline) ? $this->module_uri.'/inline_items/' : $this->module_uri;
		$crumbs = array($list_view => $this->module_name, lang('assets_upload_action'));

		$this->fuel->admin->set_titlebar($crumbs);
		$this->fuel->admin->set_inline(($inline === TRUE));

		if ($inline === TRUE)
		{
			$this->fuel->admin->set_display_mode(Fuel_admin::DISPLAY_COMPACT_TITLEBAR);
		}
		else
		{
			$vars['actions'] = $this->load->module_view(FUEL_FOLDER, '_blocks/module_create_edit_actions', $vars, TRUE);
		}

		$this->fuel->admin->render($this->views['create_edit'], $vars, '', FUEL_FOLDER);

		return $id;
	}

	public function inline_create($field = NULL)
	{
		$this->create($field, TRUE);
	}

	public function select($dir = NULL)
	{
		if ( ! is_numeric($dir))
		{
			$dir = fuel_uri_string(1, NULL, TRUE);
			$dirs = $this->fuel->assets->dirs();

			foreach($dirs as $key => $d)
			{
				if ($d == $dir)
				{
					$dir = $key;
					break;
				}
			}
		}

		$value = '';

		if ($this->session->flashdata('uploaded_post'))
		{
			$uploaded_post = $this->session->flashdata('uploaded_post');

			if (isset($uploaded_post))
			{
				$subfolder = trim(preg_replace('#^'.preg_quote($dir).'(.*)#', '$1', $uploaded_post['asset_folder']), '/');

				if ( ! empty($subfolder))
				{
					$subfolder = $subfolder.'/';
				}

				$value = $subfolder.$uploaded_post['uploaded_file_name'];
			}
		}
		else
		{
			$value = $this->input->get_post('selected', TRUE);
		}

		$this->js_controller_params['method'] = 'select';
		$this->js_controller_params['folder'] = $dir;

		$this->load->helper('array');
		$this->load->library('form_builder');
		$this->model->add_filters(array('group_id' => $dir));

		$order = $this->input->get_post('order', TRUE);

		if ($order == 'last_updated')
		{
			$by = 'desc';
		}
		else
		{
			$order = 'name';
			$by = 'asc';
		}

		$options = options_list($this->model->list_items(NULL, 0, $order, $by), 'name', 'name');
		$redirect_to = uri_safe_encode(fuel_uri(fuel_uri_string(), TRUE)); // added back to make it refresh
		// $allowed_q = array(
		// 		'subfolder',
		// 		'userfile_file_name',
		// 		'overwrite',
		// 		'unzip',
		// 		'create_thumb',
		// 		'maintain_ration',
		// 		'width',
		// 		'height',
		// 		'master_dim',
		// 		'resize_and_crop',
		// 		'resize_method',
		// 		'hide_options',
		// 		'accept',
		// 		'multiple',
		// 		'remove_subfolder'
		// 		);
		$query_str = query_str(array(), FALSE, FALSE);
		$preview = ' OR Upload

';

		$field_values['asset_folder']['value'] = $dir;
		$fields['asset_select'] = array('value' => $value, 'label' => lang('assets_select_action'), 'type' => 'select', 'options' => $options, 'after_html' => $preview);

		if (!empty($_GET['width']))
		{
			$fields['width'] = array('value' => $this->input->get_post('width', TRUE), 'label' => lang('form_label_width'), 'size' => 5, 'row_class' => 'img_only');
		}

		if (!empty($_GET['height']))
		{
			$fields['height'] = array('value' => $this->input->get_post('height', TRUE), 'label' => lang('form_label_height'), 'size' => 5, 'row_class' => 'img_only');
		}

		if (!empty($_GET['alt']))
		{
			$fields['alt'] = array('value' => $this->input->get_post('alt', TRUE), 'label' => lang('form_label_alt'), 'row_class' => 'img_only');
		}

		if (!empty($_GET['align']))
		{
			$alignment_options = array(
				'' => '',
				'left' => 'left',
				'right' => 'right',
				'middle' => 'middle',
				'top' => 'top',
				'bottom' => 'bottom',

				);

			$fields['align'] = array('value' => $this->input->get_post('align', TRUE), 'label' => lang('form_label_align'), 'type' => 'select', 'options' => $alignment_options, 'row_class' => 'img_only');
		}

		if (!empty($_GET['class']))
		{
			$fields['class'] = array('value' => $this->input->get_post('class', TRUE), 'label' => lang('form_label_class'), 'size' => 6, 'row_class' => 'img_only');
		}

		$this->form_builder->css_class = 'asset_select';
		$this->form_builder->submit_value = NULL;
		$this->form_builder->use_form_tag = FALSE;
		$this->form_builder->set_fields($fields);
		$this->form_builder->display_errors = FALSE;
		$this->form_builder->set_field_values($field_values);

		$vars['form'] = $this->form_builder->render_divs();

		$this->fuel->admin->set_inline(TRUE);

		$crumbs = array('' => $this->module_name, lang('assets_select_action'));
		//$this->fuel->admin->set_panel_display('notification', FALSE);
		$this->fuel->admin->set_titlebar($crumbs);
		$this->fuel->admin->render('modal_select', $vars);
	}

	// no editing of images... just creating/overwriting existing
	public function edit($dir = NULL, $field = NULL, $redirect = TRUE)
	{
		redirect(fuel_uri('assets/create/'.$dir));
	}

	// seperated to make it easier in subclasses to use the form without rendering the page
	public function _form($field_values = NULL, $inline = FALSE)
	{
		$this->load->library('form_builder');
		$this->load->helper('convert');

		$model = $this->model;
		$this->js_controller_params['method'] = 'add_edit';

		$fields = $this->model->form_fields();

		$fields['redirect_to'] = array('type' => 'hidden', 'value' => uri_safe_encode($this->input->get_post('redirect_to')));

		$not_hidden = array();

		if ( ! empty($field_values['hide_options']) AND is_true_val($field_values['hide_options']))
		{
			$not_hidden = array('userfile');
		}
		else if ( ! empty($field_values['hide_image_options']) AND is_true_val($field_values['hide_image_options']))
		{
			$not_hidden = array('userfile', 'asset_folder', 'subfolder', 'userfile_file_name', 'overwrite', 'unzip');
		}

		if ( ! empty($field_values['accept']))
		{
			$fields['userfile']['accept'] = $field_values['accept'];
		}

		if (isset($field_values['multiple']))
		{
			if ((bool)$field_values['multiple'] === FALSE)
			{
				$fields['userfile']['class'] = '';
			}
			else
			{
				// if their are multiple files being uploaded, the new file name won't really work
				unset($fields['user_file_name']);
			}
		}

		// hide certain fields if params were passed
		if ( ! empty($not_hidden))
		{
			foreach($fields as $key => $field)
			{
				if ( ! in_array($key, $not_hidden))
				{
					$fields[$key]['type'] = 'hidden';
				}
			}
		}

		if ($this->session->flashdata('uploaded_post'))
		{
			$field_values = $this->session->flashdata('uploaded_post');
		}

		// load custom fields
		$this->form_builder->load_custom_fields(APPPATH.'config/custom_fields.php');
		$this->form_builder->submit_value = lang('btn_upload');
		$this->form_builder->use_form_tag = FALSE;
		$this->form_builder->set_fields($fields);
		$this->form_builder->display_errors = FALSE;
		$this->form_builder->set_field_values($field_values);

		/* NOT QUITE WORKING DUE TO CANCEL BUTTON */
		// if ($this->input->get_post('redirect_to'))
		// {
		// 	$this->form_builder->other_actions = $this->form->button('Back', 'back', 'style="margin: 10px 10px 0 0; float: left;" data-url="'.site_url($this->input->get_post('redirect_to')).'"');
		// }

		$vars['form'] = $this->form_builder->render();

		// other variables
		$vars['id'] = (!empty($field_values['asset_folder'])) ? uri_safe_encode($field_values['asset_folder']) : NULL;
		$vars['data'] = array();
		$vars['action'] =  'create';

		// $preview_key = preg_replace('#^(.*)\{(.+)\}(.*)$#', "\\2", $this->preview_path);
		// if (!empty($vars['data'][$preview_key])) $this->preview_path = preg_replace('#^(.*)\{(.+)\}(.*)$#e', "'\\1'.\$vars['data']['\\2'].'\\3'", $this->preview_path);

		// active or publish fields
		//$vars['publish'] = (!empty($saved['published']) && ($saved['published'] == 'yes')) ? 'Unpublish' : 'Publish';
		$vars['module'] = $this->module;
		$vars['actions'] = $this->load->view('_blocks/module_create_edit_actions', $vars, TRUE);
		$vars['notifications'] = $this->load->view('_blocks/notifications', $vars, TRUE);

		// setup query string
		$query_str = query_str();

		if ($inline === TRUE)
		{
			$vars['form_action'] = $this->module_uri.'/inline_create/'.$vars['id'].$query_str;
		}
		else
		{
			$vars['form_action'] = $this->module_uri.'/create/'.$vars['id'].$query_str;
		}

		return $vars;
	}

	public function view($id = null)
	{
		$url = $this->preview_path.'/'.$id;
		redirect($url);
	}
}


text:
from copy import copy

from graphql.language.ast import (
    ArgumentNode,
    DirectiveNode,
    DocumentNode,
    FieldNode,
    InlineFragmentNode,
    NameNode,
    OperationDefinitionNode,
    SelectionSetNode,
    StringValueNode,
)
from graphql.validation import validate

from ...ast_manipulation import (
    get_ast_field_name,
    get_human_friendly_ast_field_name,
    get_only_selection_from_ast,
)
from ...compiler.compiler_frontend import ast_to_ir
from ...compiler.helpers import get_only_element_from_collection
from ...exceptions import GraphQLInvalidMacroError
from ...query_formatting.common import validate_arguments
from ...schema import VERTEX_FIELD_PREFIXES, FoldDirective, OptionalDirective, is_vertex_field_name
from .ast_rewriting import remove_directives_from_ast
from .ast_traversal import get_directives_for_ast, get_type_at_macro_edge_target
from .descriptor import create_descriptor_from_ast_and_args
from .directives import (
    DIRECTIVES_ALLOWED_IN_MACRO_EDGE_DEFINITION,
    DIRECTIVES_REQUIRED_IN_MACRO_EDGE_DEFINITION,
    MacroEdgeDefinitionDirective,
    MacroEdgeTargetDirective,
    get_schema_for_macro_edge_definitions,
)
from .reversal import make_reverse_macro_edge_name

def _validate_query_definition(ast):
    """Raise errors if the query operation definition contains directives or variables."""
    if ast.directives:
        directive_names = [directive.name.value for directive in ast.directives]
        raise GraphQLInvalidMacroError(
            "Unexpectedly found directives at the top level of the GraphQL input. "
            "This is not supported. Directives: {}".format(directive_names)
        )

    if ast.variable_definitions:
        raise GraphQLInvalidMacroError(
            "Unexpectedly found variable definitions at the top level of the GraphQL input. "
            "This is not supported. Variable definitions: {}".format(ast.variable_definitions)
        )

def _validate_ast_with_builtin_graphql_validation(schema, ast):
    """Validate the ast against the schema with macro directives using GraphQL validate function."""
    schema_with_macro_edge_directives = get_schema_for_macro_edge_definitions(schema)

    validation_errors = validate(schema_with_macro_edge_directives, ast)
    if validation_errors:
        raise GraphQLInvalidMacroError("Macro edge failed validation: {}".format(validation_errors))

def _validate_that_macro_edge_definition_and_target_directives_appear_once(macro_directives):
    """Validate that macro definition and target directives appear once in the ast."""
    for directive_name in DIRECTIVES_REQUIRED_IN_MACRO_EDGE_DEFINITION:
        macro_data = macro_directives.get(directive_name, None)
        if not macro_data:
            raise GraphQLInvalidMacroError(
                'Required macro edge directive "@{}" was not found anywhere within the supplied '
                "macro edge definition GraphQL.".format(directive_name)
            )

        if len(macro_data) > 1:
            raise GraphQLInvalidMacroError(
                'Required macro edge directive "@{}" was unexpectedly present more than once in '
                "the supplied macro edge definition GraphQL. It was found {} times.".format(
                    directive_name, len(macro_data)
                )
            )

def _validate_non_required_macro_definition_directives(
    ast, inside_optional_scope=False, inside_fold_scope=False
):
    """Check that the macro is using non-required macro edge definition directives properly.

    Restrictions on use of directives:
    - @macro_edge, @output and @output_source are disallowed
    - @macro_edge_target is not allowed to be inside a @fold scope
    - @macro_edge_target is not allowed to begin with a coercion

    Args:
        ast: GraphQL AST describing a subtree of the macro
        inside_optional_scope: bool, whether the subtree is within an @optional scope
        inside_fold_scope: bool, whether the subtree is within a @fold scope
    """
    names_of_directives_at_ast = frozenset({directive.name.value for directive in ast.directives})

    subselection_inside_optional_scope = inside_optional_scope
    subselection_inside_fold_scope = inside_fold_scope

    for directive in ast.directives:
        name = directive.name.value
        if name not in DIRECTIVES_ALLOWED_IN_MACRO_EDGE_DEFINITION:
            raise GraphQLInvalidMacroError(
                "Unexpected directive name found: {} {}".format(name, directive)
            )

        if name == OptionalDirective.name:
            subselection_inside_optional_scope = True
        elif name == FoldDirective.name:
            subselection_inside_fold_scope = True
        elif name == MacroEdgeTargetDirective.name:
            if inside_optional_scope:
                raise GraphQLInvalidMacroError(
                    "The @macro_edge_target cannot be inside an @optional scope."
                )
            if OptionalDirective.name in names_of_directives_at_ast:
                raise GraphQLInvalidMacroError(
                    "The @macro_edge_target cannot be placed at a field marked @optional."
                )

            if inside_fold_scope:
                raise GraphQLInvalidMacroError(
                    "The @macro_edge_target cannot be inside a @fold scope."
                )
            if FoldDirective.name in names_of_directives_at_ast:
                raise GraphQLInvalidMacroError(
                    "The @macro_edge_target cannot be placed at a field marked @fold."
                )

            # Check that the target doesn't begin with a coercion. This also implicitly
            # checks that the macro is not on a union type, because union types always
            # start with a coercion.
            for selection in ast.selection_set.selections:
                if isinstance(selection, InlineFragmentNode):
                    raise GraphQLInvalidMacroError(
                        "The @macro_edge_target cannot begin directly"
                        "with a coercion. Please put the directive on"
                        "the coercion block itself."
                    )

    if isinstance(ast, (FieldNode, InlineFragmentNode, OperationDefinitionNode)):
        if ast.selection_set is not None:
            for selection in ast.selection_set.selections:
                _validate_non_required_macro_definition_directives(
                    selection,
                    inside_optional_scope=subselection_inside_optional_scope,
                    inside_fold_scope=subselection_inside_fold_scope,
                )
    else:
        raise AssertionError("Unexpected AST type received: {} {}".format(type(ast), ast))

def _validate_that_macro_edge_definition_is_only_top_level_field_directive(ast, macro_defn_ast):
    """Ensure that @macro_edge_definition is the only directive in the top level field."""
    directive_names = [directive.name.value for directive in ast.directives]
    unexpected_directives = [
        directive_name
        for directive_name in directive_names
        if directive_name != MacroEdgeDefinitionDirective.name
    ]
    if unexpected_directives:
        raise GraphQLInvalidMacroError(
            "Found unexpected directives at the top level of the macro definition GraphQL: "
            "{}".format(unexpected_directives)
        )

    if ast is not macro_defn_ast:
        raise GraphQLInvalidMacroError(
            'Expected to find the "@{}" directive at the top level of the macro definition '
            'GraphQL (on the "{}" field), but instead found it on the "{}" field. This is '
            "not allowed.".format(
                MacroEdgeDefinitionDirective.name,
                get_human_friendly_ast_field_name(ast),
                get_human_friendly_ast_field_name(macro_defn_ast),
            )
        )

def _find_subclass_with_field_name(schema, subclass_sets, parent_class_name, field_name):
    """Find a subclass that has a field with a given name, or return None if none exists."""
    subclasses = subclass_sets[parent_class_name]
    if parent_class_name not in subclasses:
        raise AssertionError(
            "Found a class that is not a subclass of itself, this means that the "
            "subclass_sets value is incorrectly constructed: {} {} {}".format(
                parent_class_name, subclasses, subclass_sets
            )
        )

    for subclass_name in subclasses:
        class_object = schema.get_type(subclass_name)
        if field_name in class_object.fields:
            # Found a match!
            return subclass_name

    # No match.
    return None

def _validate_macro_edge_name_for_class_name(schema, subclass_sets, class_name, macro_edge_name):
    """Ensure that the provided macro edge name is valid for the given class name."""
    # The macro edge must be a valid edge name.
    if not is_vertex_field_name(macro_edge_name):
        raise GraphQLInvalidMacroError(
            'The provided macro edge name "{}" is not valid, since it does not start with '
            "the expected prefixes for vertex fields: {}".format(
                macro_edge_name, list(VERTEX_FIELD_PREFIXES)
            )
        )

    # The macro edge must not have the same name as an existing edge on the class where it exists,
    # or any of its subclasses.
    conflicting_subclass_name = _find_subclass_with_field_name(
        schema, subclass_sets, class_name, macro_edge_name
    )
    if conflicting_subclass_name is not None:
        extra_error_text = ""
        if conflicting_subclass_name != class_name:
            extra_error_text = (
                "{} is a subclass of {}, which is where you attempted to "
                "define a macro edge".format(conflicting_subclass_name, class_name)
            )
        raise GraphQLInvalidMacroError(
            'The provided macro edge name "{edge_name}" has the same name as '
            'an existing field on the "{subclass_name}" GraphQL type or interface. '
            "{extra_error_text}"
            "This is not allowed, please choose a different name.".format(
                edge_name=macro_edge_name,
                subclass_name=conflicting_subclass_name,
                extra_error_text=extra_error_text,
            )
        )

def _validate_reversed_macro_edge(schema, subclass_sets, reverse_start_class_name, macro_edge_name):
    """Ensure that the provided macro does not conflict when its direction is reversed."""
    reversed_macro_edge_name = make_reverse_macro_edge_name(macro_edge_name)

    # The reversed macro edge must not have the same name as an existing edge on the target class
    # it points to, or any of its subclasses. If such an edge exists, then the macro edge is not
    # reversible since the reversed macro edge would conflict with the existing edge on that class.
    conflicting_subclass_name = _find_subclass_with_field_name(
        schema, subclass_sets, reverse_start_class_name, reversed_macro_edge_name
    )
    if conflicting_subclass_name is not None:
        extra_error_text = ""
        if conflicting_subclass_name != reverse_start_class_name:
            extra_error_text = (
                "{} is a subclass of {}, which is where your "
                "macro edge definition points to. ".format(
                    conflicting_subclass_name, reverse_start_class_name
                )
            )
        raise GraphQLInvalidMacroError(
            'The provided macro edge name "{edge_name}" is invalid: if the edge direction were '
            'reversed, it would conflict with an existing field on the "{subclass_name}" GraphQL '
            "type or interface. {extra_error_text}"
            "This is not allowed, please choose a different name.".format(
                edge_name=macro_edge_name,
                subclass_name=conflicting_subclass_name,
                extra_error_text=extra_error_text,
            )
        )

def _get_minimal_query_ast_from_macro_ast(macro_ast):
    """Get a query that should successfully compile to IR if the macro is valid."""
    ast_without_macro_directives = remove_directives_from_ast(
        macro_ast, DIRECTIVES_REQUIRED_IN_MACRO_EDGE_DEFINITION
    )

    # We will add this output directive to make the ast a valid query
    output_directive = DirectiveNode(
        name=NameNode(value="output"),
        arguments=[
            ArgumentNode(
                name=NameNode(value="out_name"), value=StringValueNode(value="dummy_output_name")
            )
        ],
    )

    # Shallow copy everything on the path to the first level selection list
    query_ast = copy(ast_without_macro_directives)
    root_level_selection = copy(get_only_selection_from_ast(query_ast, GraphQLInvalidMacroError))
    first_level_selections = list(root_level_selection.selection_set.selections)

    # Add an output to a new or existing __typename field
    existing_typename_field = None
    for idx, selection in enumerate(first_level_selections):
        if isinstance(selection, FieldNode):
            if selection.name.value == "__typename":
                # We have a copy of the list, but the elements are references to objects
                # in macro_ast that we don't want to mutate. So the following copy is necessary.
                existing_typename_field = copy(selection)
                existing_typename_field.directives = copy(existing_typename_field.directives)
                existing_typename_field.directives.append(output_directive)
                first_level_selections[idx] = existing_typename_field
    if existing_typename_field is None:
        first_level_selections.insert(
            0, FieldNode(name=NameNode(value="__typename"), directives=[output_directive])
        )

    # Propagate the changes back to the result_ast
    root_level_selection.selection_set = SelectionSetNode(selections=first_level_selections)
    query_ast.selection_set = SelectionSetNode(selections=[root_level_selection])
    return DocumentNode(definitions=[query_ast])

# ############
# Public API #
# ############

def get_and_validate_macro_edge_info(
    schema, subclass_sets, ast, macro_edge_args, type_equivalence_hints=None
):
    """Return a MacroEdgeDescriptor for the specified macro edge, after ensuring its validity.

    Args:
        schema: GraphQL schema object, created using the GraphQL library
        subclass_sets: Dict[str, Set[str]] mapping class names to the set of its subclass names.
                       A class in this context means the name of a GraphQLObjectType,
                       GraphQLUnionType or GraphQLInterface.
        ast: GraphQL library AST OperationDefinition object, describing the GraphQL that is defining
             the macro edge.
        macro_edge_args: dict mapping strings to any type, containing any arguments the macro edge
                         requires in order to function.
        type_equivalence_hints: optional dict of GraphQL interface or type -> GraphQL union.
                                Used as a workaround for GraphQL's lack of support for
                                inheritance across "types" (i.e. non-interfaces), as well as a
                                workaround for Gremlin's total lack of inheritance-awareness.
                                The key-value pairs in the dict specify that the "key" type
                                is equivalent to the "value" type, i.e. that the GraphQL type or
                                interface in the key is the most-derived common supertype
                                of every GraphQL type in the "value" GraphQL union.
                                Recursive expansion of type equivalence hints is not performed,
                                and only type-level correctness of this argument is enforced.
                                See README.md for more details on everything this parameter does.
                                *****
                                Be very careful with this option, as bad input here will
                                lead to incorrect output queries being generated.
                                *****

    Returns:
        MacroEdgeDescriptor containing the base type name where the macro edge is defined, the name
        of the macro edge, and the macro AST and arguments.
    """
    macro_directives = get_directives_for_ast(ast)

    _validate_query_definition(ast)
    _validate_ast_with_builtin_graphql_validation(schema, DocumentNode(definitions=[ast]))
    _validate_that_macro_edge_definition_and_target_directives_appear_once(macro_directives)
    _validate_non_required_macro_definition_directives(ast)

    # Guaranteed to only have one macro definition directive,
    # otherwise validation should have failed in the previous steps.
    macro_defn_ast, macro_defn_directive = get_only_element_from_collection(
        macro_directives[MacroEdgeDefinitionDirective.name]
    )

    # Ensure that the macro successfully compiles to IR.
    input_metadata = ast_to_ir(
        schema,
        _get_minimal_query_ast_from_macro_ast(ast),
        type_equivalence_hints=type_equivalence_hints,
    ).input_metadata
    validate_arguments(input_metadata, macro_edge_args)

    _validate_that_macro_edge_definition_is_only_top_level_field_directive(
        get_only_selection_from_ast(ast, GraphQLInvalidMacroError), macro_defn_ast
    )
    class_name = get_ast_field_name(macro_defn_ast)
    macro_edge_name = get_only_element_from_collection(macro_defn_directive.arguments).value.value

    _validate_macro_edge_name_for_class_name(schema, subclass_sets, class_name, macro_edge_name)

    target_class_name = get_type_at_macro_edge_target(schema, macro_defn_ast).name
    _validate_reversed_macro_edge(schema, subclass_sets, target_class_name, macro_edge_name)

    descriptor = create_descriptor_from_ast_and_args(
        class_name, target_class_name, macro_edge_name, macro_defn_ast, macro_edge_args
    )

    return descriptor


text:
#if OBJECT
using System;
using System.Threading.Tasks;
using P2PNET.TransportLayer;
using P2PNET.TransportLayer.EventArgs;
using P2PNET.ObjectLayer.EventArgs;
using System.Collections.Generic;

namespace P2PNET.ObjectLayer
{
    /// <summary>
    /// Class for sending and receiving objects between peers.
    /// Built on top of TransportManager.
    /// </summary>
    public class ObjectManager: IDisposable
    {
        /// <summary>
        /// Triggered when a new peer is detected or an existing peer becomes inactive
        /// </summary>
        public event EventHandler<PeerChangeEventArgs> PeerChange;

        /// <summary>
        /// Triggered when a message containing an object has been received
        /// </summary>
        public event EventHandler<ObjReceivedEventArgs> ObjReceived;

        /// <summary>
        /// A list of all peers that are known to this peer
        /// </summary>
        public List<Peer> KnownPeers
        {
            get
            {
                return peerManager.KnownPeers;
            }
        }

        private Serializer serializer;
        private TransportManager peerManager;

        /// <summary>
        /// Constructor that instantiates a object manager. To commence listening call the method <C>StartAsync</C>.
        /// </summary>
        /// <param name="mPortNum"> The port number which this peer will listen on and send messages with </param>
        /// <param name="mForwardAll"> When true, all messages received trigger a MsgReceived event. This includes UDB broadcasts that are reflected back to the local peer.</param>
        public ObjectManager(int mPortNum = 8080, bool mForwardAll = false, bool tcpOnly = false, ILogger mLogger = null)
        {
            peerManager = new TransportManager(mPortNum, mForwardAll, tcpOnly, mLogger);
            serializer = new Serializer();

            peerManager.MsgReceived += PeerManager_msgReceived;
            peerManager.PeerChange += PeerManager_PeerChange;
        }

        /// <summary>
        /// Peer will start actively listening on the specified port number.
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync()
        {
            await peerManager.StartAsync();
        }

        /// <summary>
        /// Sends an object to a peer via a reliable TCP connection
        /// </summary>
        /// <param name="ipAddress"> the IPv4 address to send the message to. In the format "xxxx.xxxx.xxxx.xxxx" </param>
        /// <param name="obj">The object to send to the other peer</param>
        /// <returns>true if message was sucessfully sent otherwise returns false</returns>
        public async Task<bool> SendAsyncTCP<T>(string ipAddress, T obj)
        {
            if(obj == null)
            {
                //no object to send
                return false;
            }
            byte[] msg = await PackObjectIntoMsg(obj);

            return await peerManager.SendAsyncTCP(ipAddress, msg);
        }

        /// <summary>
        /// Sends an object to a peer via an unreliable UDP connection
        /// Use <C>SendAsyncTCP</C> instead if packet loss cannot be tolerated.
        /// </summary>
        /// <param name="ipAddress"> the IPv4 address to send the message to. In the format "xxxx.xxxx.xxxx.xxxx" </param>
        /// <param name="obj">The object to send to the other peer</param>
        /// <returns>true if message was sucessfully sent otherwise returns false</returns>
        public async Task<bool> SendAsyncUDP<T>(string ipAddress, T obj)
        {
            byte[] msg = await PackObjectIntoMsg(obj);

            return await peerManager.SendAsyncUDP(ipAddress, msg);
        }

        /// <summary>
        /// Sends an unreliable UDP broadcast to the local router. Depending on your local router settings UDP broadcasts may be ignored.
        /// If the address of other peers is known use <C>SendToAllPeersAsyncUDP</C> instead.
        /// </summary>
        /// <param name="obj">The object that is broadcast to other peers</param>
        /// <returns></returns>
        public async Task SendBroadcastAsyncUDP<T>(T obj)
        {
            byte[] msg = await PackObjectIntoMsg(obj);

            await peerManager.SendBroadcastAsyncUDP(msg);
        }

        /// <summary>
        /// Sends a message via unreliable UDP to all known peers.
        /// Use <C>SendToAllPeersAsyncTCP</C> instead if packet loss can not be tolerated.
        /// </summary>
        /// <param name="obj">The object that is sent to all other peers</param>
        /// <returns></returns>
        public async Task SendToAllPeersAsyncUDP<T>(T obj)
        {
            byte[] msg = await PackObjectIntoMsg(obj);

            await peerManager.SendToAllPeersAsyncUDP(msg);
        }

        /// <summary>
        /// Sends a message via reliable TCP connections to all known peers.
        /// </summary>
        /// <param name="obj">The object that is sent to all other peers</param>
        /// <returns></returns>
        public async Task SendToAllPeersAsyncTCP<T>(T obj)
        {
            byte[] msg = await PackObjectIntoMsg(obj);

            await peerManager.SendToAllPeersAsyncTCP(msg);
        }

        //This is here for existing Peer to Peer systems that use asynchronous Connections.
        //This method is not needed otherwise because this class automatically keeps track
        //of peer connections
        /// <summary>
        /// This method is avaliable to make it easier to integrate existing asymetric peer to peer systems.
        /// </summary>
        /// <param name="ipAddress">the ip address to establish a connection with</param>
        /// <returns></returns>
        public async Task DirectConnectAsyncTCP(string ipAddress)
        {
            await peerManager.DirectConnectAsyncTCP(ipAddress);
        }

        private async Task<byte[]> PackObjectIntoMsg<T>(T obj)
        {
            //generate metadata
            Metadata metadata = await CreateMetadataObj(obj);

            //place object into a package
            ObjPackage<T> objPackage = new ObjPackage<T>( obj, metadata);

            //seralize package
            byte[] objMsg = serializer.SerializeObject(objPackage);

            return objMsg;
        }

        private async Task<Metadata> CreateMetadataObj<T>(T obj)
        {
            string sourceIp = await peerManager.GetIpAddress();
            string objType = obj.GetType().Name;
            Metadata metaData = new Metadata();
            metaData.SourceIp = sourceIp;
            metaData.ObjectType = objType;
            return metaData;
        }

        private void PeerManager_PeerChange(object sender, TransportLayer.EventArgs.PeerChangeEventArgs e)
        {
            PeerChange?.Invoke(this, e);
        }

        private void PeerManager_msgReceived(object sender, TransportLayer.EventArgs.MsgReceivedEventArgs e)
        {
            byte[] msg = e.Message;
            BObject obj = new BObject(msg, serializer);

            //generate metadata
            Metadata metadata = obj.GetMetadata();
            metadata.BindType = e.BindingType;
            ObjReceived?.Invoke(this, new ObjReceivedEventArgs(obj, metadata));
        }

        public void Dispose()
        {
            ((IDisposable)peerManager).Dispose();
        }
    }
}

#endif


text:
package com.freerdp.freerdpcore.application;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.util.Log;

import com.freerdp.freerdpcore.domain.BookmarkBase;
import com.freerdp.freerdpcore.presentation.ApplicationSettingsActivity;
import com.freerdp.freerdpcore.services.BookmarkDB;
import com.freerdp.freerdpcore.services.HistoryDB;
import com.freerdp.freerdpcore.services.LibFreeRDP;
import com.freerdp.freerdpcore.services.ManualBookmarkGateway;
import com.freerdp.freerdpcore.services.QuickConnectHistoryGateway;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class GlobalApp extends Application implements LibFreeRDP.EventListener {
    // event notification defines
    public static final String EVENT_TYPE = "EVENT_TYPE";
    public static final String EVENT_PARAM = "EVENT_PARAM";
    public static final String EVENT_STATUS = "EVENT_STATUS";
    public static final String EVENT_ERROR = "EVENT_ERROR";
    public static final String ACTION_EVENT_FREERDP = "com.freerdp.freerdp.event.freerdp";
    public static final int FREERDP_EVENT_CONNECTION_SUCCESS = 1;
    public static final int FREERDP_EVENT_CONNECTION_FAILURE = 2;
    public static final int FREERDP_EVENT_DISCONNECTED = 3;
    private static final String TAG = "GlobalApp";
    public static boolean ConnectedTo3G = false;
    private static Map<Long, SessionState> sessionMap;
    private static BookmarkDB bookmarkDB;
    private static ManualBookmarkGateway manualBookmarkGateway;

    private static HistoryDB historyDB;
    private static QuickConnectHistoryGateway quickConnectHistoryGateway;

    // timer for disconnecting sessions after the screen was turned off
    private static Timer disconnectTimer = null;

    public static ManualBookmarkGateway getManualBookmarkGateway() {
        return manualBookmarkGateway;
    }

    public static QuickConnectHistoryGateway getQuickConnectHistoryGateway() {
        return quickConnectHistoryGateway;
    }

    // Disconnect handling for Screen on/off events
    public void startDisconnectTimer() {
        final int timeoutMinutes = ApplicationSettingsActivity.getDisconnectTimeout(this);
        if (timeoutMinutes > 0) {
            // start disconnect timeout...
            disconnectTimer = new Timer();
            disconnectTimer.schedule(new DisconnectTask(), timeoutMinutes * 60 * 1000);
        }
    }

    static public void cancelDisconnectTimer() {
        // cancel any pending timer events
        if (disconnectTimer != null) {
            disconnectTimer.cancel();
            disconnectTimer.purge();
            disconnectTimer = null;
        }
    }

    // RDP session handling
    static public SessionState createSession(BookmarkBase bookmark, Context context) {
        SessionState session = new SessionState(LibFreeRDP.newInstance(context), bookmark);
        sessionMap.put(Long.valueOf(session.getInstance()), session);
        return session;
    }

    static public SessionState createSession(Uri openUri, Context context) {
        SessionState session = new SessionState(LibFreeRDP.newInstance(context), openUri);
        sessionMap.put(Long.valueOf(session.getInstance()), session);
        return session;
    }

    static public SessionState getSession(long instance) {
        return sessionMap.get(instance);
    }

    static public Collection<SessionState> getSessions() {
        // return a copy of the session items
        return new ArrayList<SessionState>(sessionMap.values());
    }

    static public void freeSession(long instance) {
        if (GlobalApp.sessionMap.containsKey(instance)) {
            GlobalApp.sessionMap.remove(instance);
            LibFreeRDP.freeInstance(instance);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();

        /* Initialize preferences. */
        ApplicationSettingsActivity.get(this);

        sessionMap = Collections.synchronizedMap(new HashMap<Long, SessionState>());

        LibFreeRDP.setEventListener(this);

        bookmarkDB = new BookmarkDB(this);

        manualBookmarkGateway = new ManualBookmarkGateway(bookmarkDB);

        historyDB = new HistoryDB(this);
        quickConnectHistoryGateway = new QuickConnectHistoryGateway(historyDB);

        ConnectedTo3G = NetworkStateReceiver.isConnectedTo3G(this);

        // init screen receiver here (this can't be declared in AndroidManifest - refer to:
        // http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(new ScreenReceiver(), filter);
    }

    // helper to send FreeRDP notifications
    private void sendRDPNotification(int type, long param) {
        // send broadcast
        Intent intent = new Intent(ACTION_EVENT_FREERDP);
        intent.putExtra(EVENT_TYPE, type);
        intent.putExtra(EVENT_PARAM, param);
        sendBroadcast(intent);
    }

    @Override
    public void OnPreConnect(long instance) {
        Log.v(TAG, "OnPreConnect");
    }

    // //////////////////////////////////////////////////////////////////////
    // Implementation of LibFreeRDP.EventListener
    public void OnConnectionSuccess(long instance) {
        Log.v(TAG, "OnConnectionSuccess");
        sendRDPNotification(FREERDP_EVENT_CONNECTION_SUCCESS, instance);
    }

    public void OnConnectionFailure(long instance) {
        Log.v(TAG, "OnConnectionFailure");

        // send notification to session activity
        sendRDPNotification(FREERDP_EVENT_CONNECTION_FAILURE, instance);
    }

    public void OnDisconnecting(long instance) {
        Log.v(TAG, "OnDisconnecting");
    }

    public void OnDisconnected(long instance) {
        Log.v(TAG, "OnDisconnected");
        sendRDPNotification(FREERDP_EVENT_DISCONNECTED, instance);
    }

    // TimerTask for disconnecting sessions after screen was turned off
    private static class DisconnectTask extends TimerTask {
        @Override
        public void run() {
            Log.v("DisconnectTask", "Doing action");

            // disconnect any running rdp session
            Collection<SessionState> sessions = GlobalApp.getSessions();
            for (SessionState session : sessions) {
                LibFreeRDP.disconnect(session.getInstance());
            }
        }
    }
}


text:
#include "src/core/lib/client_config/resolver_registry.h"

#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>

#define MAX_RESOLVERS 10

static grpc_resolver_factory *g_all_of_the_resolvers[MAX_RESOLVERS];
static int g_number_of_resolvers = 0;

static char *g_default_resolver_prefix;

void grpc_resolver_registry_init(const char *default_resolver_prefix) {
  g_number_of_resolvers = 0;
  g_default_resolver_prefix = gpr_strdup(default_resolver_prefix);
}

void grpc_resolver_registry_shutdown(void) {
  int i;
  for (i = 0; i < g_number_of_resolvers; i++) {
    grpc_resolver_factory_unref(g_all_of_the_resolvers[i]);
  }
  gpr_free(g_default_resolver_prefix);
}

void grpc_register_resolver_type(grpc_resolver_factory *factory) {
  int i;
  for (i = 0; i < g_number_of_resolvers; i++) {
    GPR_ASSERT(0 != strcmp(factory->vtable->scheme,
                           g_all_of_the_resolvers[i]->vtable->scheme));
  }
  GPR_ASSERT(g_number_of_resolvers != MAX_RESOLVERS);
  grpc_resolver_factory_ref(factory);
  g_all_of_the_resolvers[g_number_of_resolvers++] = factory;
}

static grpc_resolver_factory *lookup_factory(const char *name) {
  int i;

  for (i = 0; i < g_number_of_resolvers; i++) {
    if (0 == strcmp(name, g_all_of_the_resolvers[i]->vtable->scheme)) {
      return g_all_of_the_resolvers[i];
    }
  }

  return NULL;
}

grpc_resolver_factory *grpc_resolver_factory_lookup(const char *name) {
  grpc_resolver_factory *f = lookup_factory(name);
  if (f) grpc_resolver_factory_ref(f);
  return f;
}

static grpc_resolver_factory *lookup_factory_by_uri(grpc_uri *uri) {
  if (!uri) return NULL;
  return lookup_factory(uri->scheme);
}

static grpc_resolver_factory *resolve_factory(const char *target,
                                              grpc_uri **uri) {
  char *tmp;
  grpc_resolver_factory *factory = NULL;

  GPR_ASSERT(uri != NULL);
  *uri = grpc_uri_parse(target, 1);
  factory = lookup_factory_by_uri(*uri);
  if (factory == NULL) {
    if (g_default_resolver_prefix != NULL) {
      grpc_uri_destroy(*uri);
      gpr_asprintf(&tmp, "%s%s", g_default_resolver_prefix, target);
      *uri = grpc_uri_parse(tmp, 1);
      factory = lookup_factory_by_uri(*uri);
      if (factory == NULL) {
        grpc_uri_destroy(grpc_uri_parse(target, 0));
        grpc_uri_destroy(grpc_uri_parse(tmp, 0));
        gpr_log(GPR_ERROR, "don't know how to resolve '%s' or '%s'", target,
                tmp);
      }
      gpr_free(tmp);
    } else {
      grpc_uri_destroy(grpc_uri_parse(target, 0));
      gpr_log(GPR_ERROR, "don't know how to resolve '%s'", target);
    }
  }
  return factory;
}

grpc_resolver *grpc_resolver_create(
    const char *target, grpc_client_channel_factory *client_channel_factory) {
  grpc_uri *uri = NULL;
  grpc_resolver_factory *factory = resolve_factory(target, &uri);
  grpc_resolver *resolver;
  grpc_resolver_args args;
  memset(&args, 0, sizeof(args));
  args.uri = uri;
  args.client_channel_factory = client_channel_factory;
  resolver = grpc_resolver_factory_create_resolver(factory, &args);
  grpc_uri_destroy(uri);
  return resolver;
}

char *grpc_get_default_authority(const char *target) {
  grpc_uri *uri = NULL;
  grpc_resolver_factory *factory = resolve_factory(target, &uri);
  char *authority = grpc_resolver_factory_get_default_authority(factory, uri);
  grpc_uri_destroy(uri);
  return authority;
}


text:
(function() {
	var app = angular.module("projects", ['language-module']);

	app.directive("ioopProjects", function() {
		return {
			restrict: "E",
			templateUrl: "src/directives/ioop-projects.html",
			controller: ['$http', 'languageModule', function($http, lang) {
				var self = this;
				self.labels = lang;
				self.projects = [];

				var prjPrem = $http.get('/json/project.json');

				prjPrem.success(function(data) {
					self.projects = data;
				});

				prjPrem.error(function(data) {
					alert('fail');
				});
			}],
			controllerAs: "prj"
		};
	});

	app.directive("ioopProject", function() {
		return {
			restrict: "E",
			templateUrl: "src/directives/ioop-project.html"
		};
	});
})();


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="Mana (Build & Run)" type="NodeJSConfigurationType" application-parameters=". --url=https://local-dev.symphony.com:9090/" path-to-node="$PROJECT_DIR$/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron" working-dir="$PROJECT_DIR$">
    <envs>
      <env name="ELECTRON_DEV" value="true" />
      <env name="ELECTRON_DEBUGGING" value="true" />
    </envs>
    <method v="2">
      <option name="NpmBeforeRunTask" enabled="true">
        <package-json value="$PROJECT_DIR$/package.json" />
        <command value="run" />
        <scripts>
          <script value="compile" />
        </scripts>
        <node-interpreter value="project" />
        <envs />
      </option>
      <option name="NpmBeforeRunTask" enabled="true">
        <package-json value="$PROJECT_DIR$/package.json" />
        <command value="run" />
        <scripts>
          <script value="browserify" />
        </scripts>
        <node-interpreter value="project" />
        <envs />
      </option>
    </method>
  </configuration>
</component>


text:
function navAFoucs(elem){
    elem.focus(function(){
        this.blur();
    })
}
$(document).ready(function(){
    navAFoucs($('#nav a'));
})


text:
QCNode 1.4.x
======

The QuickConnect Framework for Node.js. Flow control, application controller logic, and so much more!

## Installation
```
npm install qcnode
```

## What is it for?

The QuickConnect framework for Node.js is designed to help the developer quickly write, debug, and run asynchronous or synchronous code. The framework encourages code re-use and modularity.

## How do I use it?

There are many ways!

### Simple Example
```javascript
QuickConnect = require('qcnode').QuickConnect
var qc = new QuickConnect

qc.command('list filtered files', function(){
	this.valcf( function(data, qc){
		if(qc === this){ //it does
			return this.STACK_CONTINUE
		} else {
			return "this is impossible"
		}
	})
	this.dcf( function(data, qc){
		fs.readdir(data.dirPath, function(err, files){
			if(err){
				//maybe handle it here, if I want
				qc.asyncStackError(err)
				return
			}
			qc.asyncStackContinue('files',files)
		})
		return qc.WAIT_FOR_DATA
	})
	this.dcf( function(data, qc){
		data.filteredFiles = data.files.filter(function(val){return val != data.filter})
	})
	this.vcf( function(data, qc){
		for(var fi in data.filteredFiles){
			console.log(fi)
		}
		return qc.STACK_EXIT
	})
})

...

var stack = qc.handleRequest('login', myData) // .handleRequest === .run

stack.on('error', function(err, data, index){
	//handle the error out here, where I know what is going on.
	console.log("unable to filter files right now: "+err.stack)
})

stack.on('end', function(data, index){
	console.log('yay!')
})

```

### Less Simple Example
```javascript
qc.isolate('request' function(){
	this.isolate( 'GET', function(){
		this.command('contest', function(){
			this.valcf(function(data){
				if(+new Date < limit){
					return "the contest has not begun"
				}
				return this.STACK_CONTINUE
			})
			this.dcf(function(data){
				data.response.writeHead(200)
				data.response.end(JSON.stringify({message:"you are a winner!"}))
				return this.STACK_CONTINUE
			})
		})
	})
	this.isolate( 'DELETE', function(){
		//more logic
	})
})

...

http.createServer(function(req, res){
	//this will dynamically select what command to run based on the url!

	url = require('url').parse(req.url, true)
	action = ['request',req.method]
	urlParts = url.pathname.split('/').filter(function(v){return v})//removes ''
	action = action.concat(urlParts)
	try {
		qc.run(action,{response:res},{
			error: function(err){
				res.write(500)
				res.end("error")
			},
			validateFail: function(failMsgs){
				res.write(422)
				res.end(JSON.stringify({errors:failsMsgs}))
			}
		})
	catch (err) {
		//stack is not defined
		res.write(404)
		res.end(cached404page)
	}
})
```
#### Josh, you just made more callbacks…
Um… No I didn't! Pay no attention to the man behind the callbacks! This code gets run top-to-bottom; the callbacks are just helpers.

Well, fine. These examples are actually written in a shorthand that was helpful while writting coffeescript. it looks like this in coffeescript:

```coffeescript
qc.isolate 'request', ->
	@isolate 'GET', ->
		@command 'contest', ->
			@valcf (data) ->
				if +new Date < limit
					"the contest has not begun"
				else
					@STACK_CONTINUE
			@dcf (data) ->
				data.response.writeHead 200
				data.response.end JSON.stringify message:"you are a winner!"
	@isolate 'DELETE', ->
		#more logic
```

It's pretty simple to write and read with that shorthand. Here is what is actually happening _inside QuickConnect:_

```javascript
var delim = qc.mapper.isolateDelimiter
qc.mapper.mapCommandToValCF(['request','GET','contest'].join(delim), myValCF)
qc.mapper.mapCommandToValCF(['request','GET','contest'].join(delim), myDCF)
//ect...
```

That is also very readable, but it takes a lot of characters.

### Do you like Chaining?
Since `isolate`,`command`, and the `cf` functions all return the same object that is `this` in the callbacks, you can chain! Here is an example from the qc tests:

```javascript
basic.command('basic stack to call')
    .valcf(function(data, qc){
        if (data.helol) {
            return qc.STACK_CONTINUE
        } else {
            return "this should not have been returned"
        }
    })
    .dcf(function(data, qc){
        assert(data.helol)
        return this.STACK_CONTINUE
    })
    .dcf(function(data, qc){
        setTimeout(function () {
            qc.asyncStackContinue()
        }, 5)
        return this.WAIT_FOR_DATA
    })
    .dcf(function(data, qc){
        setTimeout(function () {
            qc.asyncStackContinue('key','koy')
        }, 50)
        return this.WAIT_FOR_DATA
    })
    .dcf(function(data, qc){
        assert.equal(data.key,'koy')
        return this.STACK_CONTINUE
    })
    .vcf(function(data, qc){
        data.done = true
        return this.STACK_CONTINUE
    })
```
That's probably a more javascript-y way.
You just have to remember that `isolate`, `command`, and `cf` functions do not return the same object. This is not valid:

```javascript
//error!
basic.isolate(isol).command(mycom).valcf(myfunc).command(otherCom).ect(…)
```
Remember, if you can chain something, you can store it.

```javascript
iso = basic.isolate(isol)
comOne = iso.command(mycom)
comOne.valcf(myfunc).dcf(dfunc)
comTwo = iso.command(otherCom)
comTwo.ect(...)
```

## Could you change "X" to be "y"?
No, but **you** can with [mixins!](https://github.com/QuickConnect/QCNode/wiki/Mixin-Guide)

## So?

So this is awesome! You can use QC in the way that works for you. It's more than just flow control, it's designed to help you get things done faster, higher, and stronger.

## But how can I use it in ...?
Head on over to [our example page!](https://github.com/QuickConnect/QCNode/wiki/examples)

## QC History
QuickConnect started as a response to some of the problems encountered writing code for Enterprise Java servers. The framework pattern evolved for several years in a hybrid mobile environment (QCHybrid, iOS and Android) which provided tools for rapid prototyping of cross-platform apps.

From the async javascript environment of mobile web views, the jump to Node.js was natural, but required some heavy thinking and adaptation to match the node way of doing things. The first port was done by a developer for a mobile app company--this port was made open source after donation back to the main QC developer. The first version published for install via npm was a complete re-write of that first port; this resulted in a smaller, better QC that fuctions across many versions of node.

### Version numbers
QC is pretty mature and very functional, so it didn't make sense to publish a version <1.0.0

Here is how it works: When we change to version x.y.z

* x : your stuff will probably break
* y : your stuff will probably not break
* z : we fixed something, wrote a test, or something small

## Contribute
Because QC has a history older than Node.js, it has some things in it that are leftovers from other incarnations. 'handleRequest' is the oldest part; it comes from living on a server that handles client requests. It has been pointed out that a 'request', a 'command', and a 'stack' are all related, but come from different points in the history. We want to increase the 'y' part of the version by building better ways for people to use QC in their codeflow and workflow.

Fork the repo, submit a pull request and tell us your rational for the change; we would love to hear all ideas.

We feel the core logic of QC is pretty set in version 1.0.0, but if you have ideas for version 2.0.0, fork the repo or drop us a line!

# Licence
MIT

Copyright (c) 2013 Joshua Barney, Lee Barney

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
namespace {

struct BasicPacket {
  static constexpr uint32_t kMagic = 0x8badf00d;

  constexpr BasicPacket(uint32_t addr, uint64_t data)
      : magic(kMagic), address(addr), payload(data) {}

  uint32_t magic;
  uint32_t address;
  uint64_t payload;
};

}  // namespace

int main() {
  pw::bloat::BloatThisBinary();

  // Ensure we are paying the cost for log and assert.
  BasicPacket packet(0x1, 0x2);
  PW_CHECK_UINT_EQ(packet.magic, BasicPacket::kMagic, "Some CHECK logic");
  PW_LOG_INFO("Packet has address %u", static_cast<unsigned>(packet.address));
  PW_LOG_INFO("pw_StatusString %s", pw::OkStatus().str());

  std::array<std::byte, sizeof(BasicPacket)> packet_buffer;
  pw::sys_io::ReadBytes(packet_buffer);
  pw::sys_io::WriteBytes(packet_buffer);

  return static_cast<int>(packet.payload);
}


text:
Don't forget to change the ip address in views/layout.jade to the server's IP address.

##Further possibilities

1:Color selection, shadows,
1:a. Layers(multiple canvas objects)

2: Save drawings and pull saves from db

3: Flickr api to search images and open to have the user trace


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Deportes extends CI_Controller {

    function __construct() {
        parent::__construct();
    }

	public function index()
	{
            $cuerpo = $this->load->view('Deportes','',true);
            $this->load->view('plantilla',Array('cuerpo'=>$cuerpo));
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layNotification"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_marginTop="10dp"
    android:stretchColumns="1"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp">

</TableLayout>


text:
import * as React from 'react';

export default class FilterSelector extends React.Component<{title: string, open: boolean, onClick: Function}, any>
{
    render()
    {
        return (
            <button data-am-button="filter-chooser fill font-primary-bold"
                    className={"btn-toggle-productfilter" + (this.props.open ? " open":"")}
                    onClick={e => this.props.onClick()}>
                {this.props.title}
            </button>
        );
    }
}


text:
<?php

namespace Pragmatist\Regel\RuleSetProvider;

use Pragmatist\Regel\RuleSet\RuleSet;

interface RuleSetProvider
{
    /**
     * @param $identifier
     * @return RuleSet
     */
    public function ruleSetIdentifiedBy($identifier);
}


text:
module RSpec
  module Matchers
    module BuiltIn
      class Satisfy
        include MatchAliases

        def initialize(&block)
          @block = block
        end

        def matches?(actual, &block)
          @block = block if block
          @actual = actual
          @block.call(actual)
        end

        def failure_message_for_should
          "expected #{@actual} to satisfy block"
        end

        def failure_message_for_should_not
          "expected #{@actual} not to satisfy block"
        end

        def description
          "satisfy block"
        end

        # @private
        def supports_block_expectations?
          false
        end
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace DynamicTaskParallelism
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Tree walking example:");
            Console.WriteLine();
            var one = new BinaryTree<int>(1);
            var two = new BinaryTree<int>(2);
            var three = new BinaryTree<int>(3);
            var four = new BinaryTree<int>(4);
            var five = new BinaryTree<int>(5);
            var six = new BinaryTree<int>(6);
            var seven = new BinaryTree<int>(7);
            var eight = new BinaryTree<int>(8);
            var nine = new BinaryTree<int>(9);

            one.Left = two;
            two.Left = three;
            two.Right = four;
            four.Left = five;
            four.Right = six;
            one.Right = seven;
            seven.Right = eight;
            eight.Right = nine;

            Action<int> action = i => Console.WriteLine("Walked: {0}", i);

            Console.WriteLine("Walking in serial:");
            one.Walk(action);

            Console.WriteLine();
            Console.WriteLine("Walking in parallel:");
            one.ParallelWalk(action);

            Console.WriteLine();
            Console.WriteLine("Walking while not empty:");
            one.ParallelWalkWhileNotEmpty(action);

            Console.WriteLine();
            Console.WriteLine("Walking with parent/child tasks:");
            one.ParallelWalkWithParentChildTasks(action);
            Console.ReadKey();
            Console.Clear();

            Console.WriteLine("Array sorting example:");
            Console.WriteLine();
            var arraySize = 7500000;
            var maxValue = 1000000;
            var random = new Random(DateTime.Now.Millisecond);
            var sw = new Stopwatch();
            var values = new List<int>();
            for (var i = 0; i < arraySize; i++)
            {
                values.Add(random.Next(maxValue));
            }

            var valuesToSort = new int[arraySize];
            values.CopyTo(valuesToSort);

            Console.WriteLine("Sorting with Quicksort:");
            sw.Start();
            SortAlgorithms.Quicksort(valuesToSort);
            Console.WriteLine("Sort {0:N} items in {1}", arraySize, sw.Elapsed.ToString("g"));

            Console.WriteLine();
            Console.WriteLine("Sorting with Parallel Quicksort:");
            sw.Restart();
            SortAlgorithms.ParallelQuicksort(valuesToSort);
            Console.WriteLine("Sort {0:N} items in {1}", arraySize, sw.Elapsed.ToString("g"));
            sw.Stop();
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: sadiq
 * Date: 2/28/2017
 * Time: 12:54 PM
 */
?>

Site Comments

                            <img src="<?php echo base_url("assets/front/images/");?>/siteComments_thanksIcon.png" alt="#">

Thank You  for your feedback

                            <a class="agntAwrd_siteComentsThanks_btn" href="<?php echo base_url(); ?>">Main Menu


text:
* Renamed `RawData` -> `RawDatum`
* Added a new layer of task tracking `HarvestLog`
* Stripped date fields off of `RawData`
* `provider_doc_id` moved into its own model
* `RawDatum` will no longer be connected to `CeleryTask`

## Migrating
### Prerequisites
The `Source`, `SourceConfig`, `Harvester`, and `Transformer` models.

1. Rename `RawData` -> `RawDatum` (Done first for clarity)
2. Create the `SourceUniqueIdentifier` table
3. Populate `SourceUniqueIdentifier` with existing `RawDatum`.
  * `provider_doc_id` -> `SourceUniqueIdentifier.identifier`
  * `app_label` -> `SourceUniqueIdentifier.source_config_id`
4. Drop `provider_doc_id`, `source_id`, and `app_label`
5. The though-table connecting `RawDatum` to `CeleryTask` may be removed at this point.
6. Using `date_seen` and `date_created` begin to slowly re-harvest providers attempting to find these data again
7. Once all, or a sufficient amount, of data are linked to a `HarvestLog`, the date fields can be dropped.

## User Stories

## Tables
### RawDatum
Raw datum, exactly as it was given to SHARE.

| Column         | Type | Indexed | Nullable | FK  | Default | Description                                                        |
| :------------- | :--: | :-----: | :------: | :-: | :-----: | :----------------------------------------------------------------- |
| `suid_id`      | int  |    ✓    |          |  ✓  |         | SUID for this datum                                                |
| `datum`        | text |         |          |     |         | The raw datum itself (typically JSON or XML string)                |
| `sha256`       | text | unique  |          |     |         | SHA-256 hash of `data`                                             |
| `harvest_logs` | m2m  |         |          |     |         | List of HarvestLogs for harvester runs that found this exact datum |

### HarvestLog
Log entries to track the status of a specific harvester run.

| Column                  |   Type    | Indexed | Nullable | FK  |     Default     | Description                                                                                |
| :---------------------- | :-------: | :-----: | :------: | :-: | :-------------: | :------------------------------------------------------------------------------------------------------------ |
| `source_config_id`      |    int    |    ✓    |          |  ✓  |                 | IngestConfig for this harvester run                                                                           |
| `start_date`            | datetime  |    ✓    |          |     |                 | Beginning of the date range to harvest                                                                        |
| `end_date`              | datetime  |    ✓    |          |     |                 | End of the date range to harvest                                                                              |
| `status`                | enum(int) |    ✓    |          |     |     CREATED     | Status of the harvester run, one of {CREATED, STARTED, SPLIT, SUCCEEDED, FAILED, RESCHEDULED, SKIPPED}        |
| `error`                 |   text    |         |          |     |       ""        | A custom error message or traceback describing why this job failed                                            |
| `completions`           |    int    |         |          |     |        0        | The number of times `status` has been set to SUCCEEDED                                                        |
| `date_started`          | datetime  |         |          |     |                 | Datetime `status` was last set to STARTED                                                                     |
| `date_created`          | datetime  |         |          |     |       now       | Datetime this row was created                                                                                |
| `date_modified`         | datetime  |         |          |     | now (on update) | Datetime this row was last modified                                                                           |
| `share_version`         |   text    |         |          |     |     UNKNOWN     | The commitish at the time this job was last run                                                               |
| `harvester_version`     |   text    |    ✓    |          |     |   000.000.000   | Semantic version of the harvester, with each segment padded to 3 digits (e.g. '1.2.10' => '001.002.010')      |
| `source_config_version` |   text    |    ✓    |          |     |   000.000.000   | Semantic version of the `SourceConfig`, with each segment padded to 3 digits (e.g. '1.2.10' => '001.002.010') |

#### Other indices
* `source_config_id`, `harvester_version`, `start_date`, `end_date` (unique)

### HarvestLogRawDatum
Through-table that links a `RawDatum` to a `HarvestLog`. (Let Django generate this)

| Column           | Type | Indexed | Nullable | FK  | Default | Description |
| :--------------- | :--: | :-----: | :------: | :-: | :-----: | :---------- |
| `harvest_log_id` | int  |    ✓    |          |  ✓  |         |             |
| `rawdatum_id`    | int  |    ✓    |          |  ✓  |         |             |

#### Notes
* In the future, jobs may attempt to optimize themselves by searching for jobs that have already harvested a section of it required date range
* In the future, jobs may be merged together if they have overlapping date ranges to save on table space

## FAQ


text:
package main

import (
	"flag"
	"fmt"
	"net/rpc"
	"os"
	"os/signal"
	"runtime"
	"syscall"

	"github.com/Symantec/Dominator/lib/log/serverlogger"
	"github.com/Symantec/health-agent/httpd"
	"github.com/Symantec/tricorder/go/healthserver"
	"github.com/Symantec/tricorder/go/tricorder"
)

var (
	configDir = flag.String("configDir", "/etc/health-agent",
		"Name of the directory containing the health check configs")
	maxThreads = flag.Uint("maxThreads", 1,
		"Maximum number of parallel OS threads to use")
	pidfile = flag.String("pidfile", "/var/run/health-agent.pid",
		"Name of file to write my PID to")
	portNum = flag.Uint("portNum", 6910,
		"Port number to allocate and listen on for HTTP/RPC")
	probeInterval = flag.Uint("probeInterval", 10, "Probe interval in seconds")
)

func gracefulCleanup() {
	if *pidfile != "" {
		os.Remove(*pidfile)
	}
	os.Exit(1)
}

func writePidfile() {
	if *pidfile == "" {
		return
	}
	file, err := os.Create(*pidfile)
	if err != nil {
		return
	}
	defer file.Close()
	fmt.Fprintln(file, os.Getpid())
}

func doMain() error {
	flag.Parse()
	tricorder.RegisterFlags()
	runtime.GOMAXPROCS(int(*maxThreads))
	runtime.LockOSThread()
	logger := serverlogger.New("")
	proberList, err := setupProbers()
	if err != nil {
		return err
	}
	if err := setupHealthchecks(*configDir, proberList, logger); err != nil {
		logger.Printf("Error occurred while setting up Healthchecks")
		return err
	}
	httpd.AddHtmlWriter(proberList)
	httpd.AddHtmlWriter(logger)
	sighupChannel := make(chan os.Signal)
	signal.Notify(sighupChannel, syscall.SIGHUP)
	sigtermChannel := make(chan os.Signal)
	signal.Notify(sigtermChannel, syscall.SIGTERM, syscall.SIGINT)
	rpc.HandleHTTP()
	if err := httpd.StartServer(*portNum, logger); err != nil {
		return err
	}
	writePidfile()
	proberList.StartProbing(*probeInterval, logger)
	healthserver.SetReady()
	for {
		select {
		case <-sighupChannel:
			err = syscall.Exec(os.Args[0], os.Args, os.Environ())
			if err != nil {
				logger.Printf("Unable to Exec:%s\t%s\n", os.Args[0], err)
			}
		case <-sigtermChannel:
			logger.Println("Caught SIGTERM: exiting cleanly")
			logger.Flush()
			gracefulCleanup()
		}
	}
}

func main() {
	if err := doMain(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}