text:
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.setpoint_managers import SetpointManagerOutdoorAirPretreat

log = logging.getLogger(__name__)

class TestSetpointManagerOutdoorAirPretreat(unittest.TestCase):

    def setUp(self):
        self.fd, self.path = tempfile.mkstemp()

    def tearDown(self):
        os.remove(self.path)

    def test_create_setpointmanageroutdoorairpretreat(self):

        pyidf.validation_level = ValidationLevel.error

        obj = SetpointManagerOutdoorAirPretreat()
        # alpha
        var_name = "Name"
        obj.name = var_name
        # alpha
        var_control_variable = "Temperature"
        obj.control_variable = var_control_variable
        # real
        var_minimum_setpoint_temperature = 3.3
        obj.minimum_setpoint_temperature = var_minimum_setpoint_temperature
        # real
        var_maximum_setpoint_temperature = 4.4
        obj.maximum_setpoint_temperature = var_maximum_setpoint_temperature
        # real
        var_minimum_setpoint_humidity_ratio = 1.0
        obj.minimum_setpoint_humidity_ratio = var_minimum_setpoint_humidity_ratio
        # real
        var_maximum_setpoint_humidity_ratio = 1.0
        obj.maximum_setpoint_humidity_ratio = var_maximum_setpoint_humidity_ratio
        # node
        var_reference_setpoint_node_name = "node|Reference Setpoint Node Name"
        obj.reference_setpoint_node_name = var_reference_setpoint_node_name
        # node
        var_mixed_air_stream_node_name = "node|Mixed Air Stream Node Name"
        obj.mixed_air_stream_node_name = var_mixed_air_stream_node_name
        # node
        var_outdoor_air_stream_node_name = "node|Outdoor Air Stream Node Name"
        obj.outdoor_air_stream_node_name = var_outdoor_air_stream_node_name
        # node
        var_return_air_stream_node_name = "node|Return Air Stream Node Name"
        obj.return_air_stream_node_name = var_return_air_stream_node_name
        # node
        var_setpoint_node_or_nodelist_name = "node|Setpoint Node or NodeList Name"
        obj.setpoint_node_or_nodelist_name = var_setpoint_node_or_nodelist_name

        idf = IDF()
        idf.add(obj)
        idf.save(self.path, check=False)

        with open(self.path, mode='r') as f:
            for line in f:
                log.debug(line.strip())

        idf2 = IDF(self.path)
        self.assertEqual(idf2.setpointmanageroutdoorairpretreats[0].name, var_name)
        self.assertEqual(idf2.setpointmanageroutdoorairpretreats[0].control_variable, var_control_variable)
        self.assertAlmostEqual(idf2.setpointmanageroutdoorairpretreats[0].minimum_setpoint_temperature, var_minimum_setpoint_temperature)
        self.assertAlmostEqual(idf2.setpointmanageroutdoorairpretreats[0].maximum_setpoint_temperature, var_maximum_setpoint_temperature)
        self.assertAlmostEqual(idf2.setpointmanageroutdoorairpretreats[0].minimum_setpoint_humidity_ratio, var_minimum_setpoint_humidity_ratio)
        self.assertAlmostEqual(idf2.setpointmanageroutdoorairpretreats[0].maximum_setpoint_humidity_ratio, var_maximum_setpoint_humidity_ratio)
        self.assertEqual(idf2.setpointmanageroutdoorairpretreats[0].reference_setpoint_node_name, var_reference_setpoint_node_name)
        self.assertEqual(idf2.setpointmanageroutdoorairpretreats[0].mixed_air_stream_node_name, var_mixed_air_stream_node_name)
        self.assertEqual(idf2.setpointmanageroutdoorairpretreats[0].outdoor_air_stream_node_name, var_outdoor_air_stream_node_name)
        self.assertEqual(idf2.setpointmanageroutdoorairpretreats[0].return_air_stream_node_name, var_return_air_stream_node_name)
        self.assertEqual(idf2.setpointmanageroutdoorairpretreats[0].setpoint_node_or_nodelist_name, var_setpoint_node_or_nodelist_name)


text:
package com.johnson.CommonWechatFrontAPi.model.compontent;

import java.io.Serializable;

/**
 * Created by johnson on 8/13/2017.
 */
public class Like implements Serializable {

    int id;
    String targetUuid;
    String userUuid;
    String createTime;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTargetUuid() {
        return targetUuid;
    }

    public void setTargetUuid(String targetUuid) {
        this.targetUuid = targetUuid;
    }

    public String getUserUuid() {
        return userUuid;
    }

    public void setUserUuid(String userUuid) {
        this.userUuid = userUuid;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "Like{" +
                "id=" + id +
                ", targetUuid='" + targetUuid + '\'' +
                ", userUuid='" + userUuid + '\'' +
                ", createTime='" + createTime + '\'' +
                '}';
    }
}

redpajama_set_name: RedPajamaGithub


text:
static NSString *const kSettingInfoCell = @"kSettingInfoCell";
static NSString *const kUserInfoHeaderCell = @"kUserInfoHeaderCell";
static NSString *const kUserInfoSwitchCell = @"kUserInfoSwitchCell";
static NSString *const kDLSettingClickCell = @"kDLSettingClickCell";

@interface DLUserCenterViewController () <UITableViewDelegate, UITableViewDataSource>

//用户信息列表
@property (nonatomic) UITableView *userInfoListView;

@property (nonatomic, assign) BOOL bSignIn;

@end

@implementation DLUserCenterViewController

-(instancetype)init {
    self = [super init];
    if (self) {
        DDLogInfo(@"UserCenterViewController init");
    }

    return self;
}

-(void)dealloc {
    DDLogInfo(@"UserCenterViewController dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tryUpdateSignIn:) name:[AppUtil notificationNameSignIn] object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tryUpdateSignIn:) name:[AppUtil notificationNameLogout] object:nil];

    self.automaticallyAdjustsScrollViewInsets = NO;

    [self tryUpdateSignIn:nil];

    [self.view addSubview:self.userInfoListView];

    [self.userInfoListView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.mas_topLayoutGuideBottom);
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
    }];

    self.userInfoListView.backgroundColor = [UIColor whiteColor];
    self.userInfoListView.dataSource = self;
    self.userInfoListView.delegate = self;

}

-(UITableView *)userInfoListView {
    if (!_userInfoListView) {
        _userInfoListView = [[UITableView alloc] initWithFrame:CGRectZero];
        _userInfoListView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [_userInfoListView registerClass:[DLSettingInfoCell class] forCellReuseIdentifier:kSettingInfoCell];
        [_userInfoListView registerClass:[DLUserInfoHeaderCell class] forCellReuseIdentifier:kUserInfoHeaderCell];
        [_userInfoListView registerClass:[DLUserInfoSwitchCell class] forCellReuseIdentifier:kUserInfoSwitchCell];
        [_userInfoListView registerClass:[DLSettingClickCell class] forCellReuseIdentifier:kDLSettingClickCell];

    }

    return _userInfoListView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {
        return 1;
    }
    if (section == 1) {
        return 1;
    }

    if (section == 2) {
        return 1;
    }

    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;

    if (section == 0) {
        return 100;
    }

    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;

    if (section == 0) {
        switch (row) {
            case 0:
            {
                DLUserInfoHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:kUserInfoHeaderCell forIndexPath:indexPath];
                [cell.iconImageView setImage:[UIImage imageNamed:@"default_avatar"]];

                if (_bSignIn) {
                    VodkaUserDefaults *userDefaults= [VodkaUserDefaults sharedUserDefaults];
                    NSString *name = [userDefaults name];

                    [cell.titleLab setText:name];
                } else {
                    [cell.titleLab setText:NSLocalizedString(@"Click portrait to sign in", comment: "")];
                }

                return cell;
            }
                break;

            default:
                break;
        }
    }

    if (section == 1) {

        switch (row) {
            case 0:
            {
                DLSettingInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:kSettingInfoCell forIndexPath:indexPath];
                [cell.titleLab setText:NSLocalizedString(@"Feedback", comment: "")];

                return cell;
            }
                break;

            default:
                break;
        }
    }

    if (section == 2) {

        switch (row) {
            case 0:
            {
                DLSettingInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:kSettingInfoCell forIndexPath:indexPath];
                [cell.titleLab setText:NSLocalizedString(@"Settings", comment: "")];

                return cell;
            }
                break;

            default:
                break;
        }
    }

    return [[UITableViewCell alloc] initWithFrame:CGRectZero];

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }

    return 20;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;

    if (section == 0) {
        switch (row) {
            case 0:
            {
                if (!_bSignIn) {
                    DLSignInViewController *loginViewController = [[DLSignInViewController alloc] init];
                    UINavigationController *navLoginController = [[UINavigationController alloc] initWithRootViewController:loginViewController];

                    [self presentViewController:navLoginController animated:YES completion:nil];
                }

            }
                break;

            default:
                break;
        }
    }

    if (section == 1) {

        switch (row) {
            case 0:
            {
                //反馈建议
                DLFeedbackViewController *feedbackViewController = [[DLFeedbackViewController alloc] init];
                feedbackViewController.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:feedbackViewController animated:YES];
            }
                break;
            case 1:
            {
                //推荐给好友
            }
                break;
            default:
                break;
        }
    }

    if (section == 2) {

        switch (row) {
            case 0:
            {
                DLSettingsViewController *settingsViewController = [[DLSettingsViewController alloc] init];
                settingsViewController.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:settingsViewController animated:YES];
            }
                break;

            default:
                break;
        }
    }

}

-(void)tryUpdateSignIn:(NSNotification *)notification{

    VodkaUserDefaults *userDefaults= [VodkaUserDefaults sharedUserDefaults];
    NSString *accessToken = [userDefaults accessToken];

    _bSignIn = accessToken?YES:NO;

    if (_bSignIn) {
        //导航栏
        self.navigationItem.title = NSLocalizedString(@"Me", comment: "");
    } else {
        //导航栏
        self.navigationItem.title = NSLocalizedString(@"Not signed in", comment: "");
    }

    [self.userInfoListView reloadData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
import weakref
from itertools import cycle
from typing import Any, Hashable, MutableMapping

from . import base

class AbstractMetaListStorage(base.AbstractStorage):
    def raw_key(self, key):
        return key

    @property
    def storages(self):
        return map(lambda x: self.context[x], self.config.storages)

class Fallback(AbstractMetaListStorage):
    async def get(self, key):
        key = self.raw_key(key)
        for storage in self.storages:
            v = await storage.get(key)
            if v is not None:
                return v

    async def set(self, key, value):
        pass

class Replicator(AbstractMetaListStorage):
    async def init(self):
        self._pool = cycle(self.storages)

    async def get(self, key):
        storage = next(self._pool)
        key = self.raw_key(key)
        return await storage.get(key)

    async def set(self, key, value):
        key = self.raw_key(key)
        for storage in self.storages:
            await storage.set(key, value)

class Cache(base.AbstractStorage):
    def raw_key(self, key):
        return key

    @property
    def storage(self):
        return self.context[self.config.storage]

    @property
    def source(self):
        return self.context[self.config.source]

    async def get(self, key):
        key = self.raw_key(key)
        v = await self.storage.get(key)
        if v is not None:
            return v
        v = await self.source.get(key)
        await self.storage.set(key, v)
        return v

    def set(self, key, value):
        key = self.raw_key(key)
        return self.storage.set(key, value)

class FutureStorage(base.AbstractStorage):
    _futures: MutableMapping

    def __init__(self, *args, **kwargs):
        self._futures = {}
        super().__init__(*args, **kwargs)

    def set_config(self, config):
        super().set_config(config)
        if self.config.get('weak', True):
            self._futures = weakref.WeakValueDictionary()

    def raw_key(self, key: Any) -> Hashable:
        return key

    async def set(self, key: Hashable, value: Any) -> None:
        raw_key = self.raw_key(key)
        if raw_key not in self._futures:
            pass
        elif not self._futures[raw_key].done():
            self._futures[raw_key].set_result(value)
            return None
        elif not self.config.get('exists_set'):
            return None
        future = self.loop.create_future()
        self._futures[raw_key] = future
        future.set_result(value)

    def get(self, key):
        key = self.raw_key(key)
        if key in self._futures:
            return self._futures[key]
        else:
            return self._futures.setdefault(key, self.loop.create_future())


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using static LiteDB.Constants;

namespace LiteDB.Engine
{
    internal class SysPageList : SystemCollection
    {
        private readonly HeaderPage _header;
        private readonly TransactionMonitor _monitor;
        private Dictionary<uint, string> _collections;

        public SysPageList(HeaderPage header, TransactionMonitor monitor) : base("$page_list")
        {
            _header = header;
            _monitor = monitor;
        }

        public override IEnumerable<BsonDocument> Input(BsonValue options)
        {
            var pageID = GetOption(options, "pageID");

            // get any transaction from current thread ID
            var transaction = _monitor.GetThreadTransaction();
            var snapshot = transaction.CreateSnapshot(LockMode.Read, "$", false);

            _collections = _header.GetCollections().ToDictionary(x => x.Value, x => x.Key);

            var result = pageID != null ?
                this.GetList((uint)pageID.AsInt32, null, transaction, snapshot) :
                this.GetAllList(transaction, snapshot);

            foreach (var page in result)
            {
                yield return page;
            }
        }

        private IEnumerable<BsonDocument> GetAllList(TransactionService transaction, Snapshot snapshot)
        {
            // get empty page list, from header
            foreach (var page in this.GetList(_header.FreeEmptyPageList, null, transaction, snapshot))
            {
                yield return page;
            }

            // get lists from data pages/index list
            foreach (var collection in _collections)
            {
                var snap = transaction.CreateSnapshot(LockMode.Read, collection.Value, false);

                for (var slot = 0; slot < PAGE_FREE_LIST_SLOTS; slot++)
                {
                    var result = this.GetList(snap.CollectionPage.FreeDataPageList[slot], null, transaction, snap);

                    foreach (var page in result)
                    {
                        yield return page;
                    }
                }

                var indexes = snap.CollectionPage.GetCollectionIndexes().ToArray();

                foreach (var index in indexes)
                {
                    var result = this.GetList(index.FreeIndexPageList, index.Name, transaction, snap);

                    foreach (var page in result)
                    {
                        yield return page;
                    }

                }
            }
        }

        private IEnumerable<BsonDocument> GetList(uint pageID, string indexName, TransactionService transaction, Snapshot snapshot)
        {
            if (pageID == uint.MaxValue) yield break;

            var page = snapshot.GetPage<BasePage>(pageID);

            while (page != null)
            {
                _collections.TryGetValue(page.ColID, out var collection);

                yield return new BsonDocument
                {
                    ["pageID"] = (int)page.PageID,
                    ["pageType"] = page.PageType.ToString(),
                    ["slot"] = (int)page.PageListSlot,
                    ["collection"] = collection,
                    ["index"] = indexName,
                    ["freeBytes"] = page.FreeBytes,
                    ["itemsCount"] = (int)page.ItemsCount
                };

                if (page.NextPageID == uint.MaxValue) break;

                transaction.Safepoint();

                page = snapshot.GetPage<BasePage>(page.NextPageID);
            }
        }
    }
}


text:
#include <grpc/support/avl.h>

#include <assert.h>
#include <stdlib.h>

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

gpr_avl gpr_avl_create(const gpr_avl_vtable *vtable) {
  gpr_avl out;
  out.vtable = vtable;
  out.root = NULL;
  return out;
}

static gpr_avl_node *ref_node(gpr_avl_node *node) {
  if (node) {
    gpr_ref(&node->refs);
  }
  return node;
}

static void unref_node(const gpr_avl_vtable *vtable, gpr_avl_node *node) {
  if (node == NULL) {
    return;
  }
  if (gpr_unref(&node->refs)) {
    vtable->destroy_key(node->key);
    vtable->destroy_value(node->value);
    unref_node(vtable, node->left);
    unref_node(vtable, node->right);
    gpr_free(node);
  }
}

static long node_height(gpr_avl_node *node) {
  return node == NULL ? 0 : node->height;
}

#ifndef NDEBUG
static long calculate_height(gpr_avl_node *node) {
  return node == NULL ? 0 : 1 + GPR_MAX(calculate_height(node->left),
                                        calculate_height(node->right));
}

static gpr_avl_node *assert_invariants(gpr_avl_node *n) {
  if (n == NULL) return NULL;
  assert_invariants(n->left);
  assert_invariants(n->right);
  assert(calculate_height(n) == n->height);
  assert(labs(node_height(n->left) - node_height(n->right)) <= 1);
  return n;
}
#else
static gpr_avl_node *assert_invariants(gpr_avl_node *n) { return n; }
#endif

gpr_avl_node *new_node(void *key, void *value, gpr_avl_node *left,
                       gpr_avl_node *right) {
  gpr_avl_node *node = gpr_malloc(sizeof(*node));
  gpr_ref_init(&node->refs, 1);
  node->key = key;
  node->value = value;
  node->left = assert_invariants(left);
  node->right = assert_invariants(right);
  node->height = 1 + GPR_MAX(node_height(left), node_height(right));
  return node;
}

static gpr_avl_node *get(const gpr_avl_vtable *vtable, gpr_avl_node *node,
                         void *key) {
  long cmp;

  if (node == NULL) {
    return NULL;
  }

  cmp = vtable->compare_keys(node->key, key);
  if (cmp == 0) {
    return node;
  } else if (cmp > 0) {
    return get(vtable, node->left, key);
  } else {
    return get(vtable, node->right, key);
  }
}

void *gpr_avl_get(gpr_avl avl, void *key) {
  gpr_avl_node *node = get(avl.vtable, avl.root, key);
  return node ? node->value : NULL;
}

int gpr_avl_maybe_get(gpr_avl avl, void *key, void **value) {
  gpr_avl_node *node = get(avl.vtable, avl.root, key);
  if (node != NULL) {
    *value = node->value;
    return 1;
  }
  return 0;
}

static gpr_avl_node *rotate_left(const gpr_avl_vtable *vtable, void *key,
                                 void *value, gpr_avl_node *left,
                                 gpr_avl_node *right) {
  gpr_avl_node *n =
      new_node(vtable->copy_key(right->key), vtable->copy_value(right->value),
               new_node(key, value, left, ref_node(right->left)),
               ref_node(right->right));
  unref_node(vtable, right);
  return n;
}

static gpr_avl_node *rotate_right(const gpr_avl_vtable *vtable, void *key,
                                  void *value, gpr_avl_node *left,
                                  gpr_avl_node *right) {
  gpr_avl_node *n = new_node(
      vtable->copy_key(left->key), vtable->copy_value(left->value),
      ref_node(left->left), new_node(key, value, ref_node(left->right), right));
  unref_node(vtable, left);
  return n;
}

static gpr_avl_node *rotate_left_right(const gpr_avl_vtable *vtable, void *key,
                                       void *value, gpr_avl_node *left,
                                       gpr_avl_node *right) {
  /* rotate_right(..., rotate_left(left), right) */
  gpr_avl_node *n = new_node(
      vtable->copy_key(left->right->key),
      vtable->copy_value(left->right->value),
      new_node(vtable->copy_key(left->key), vtable->copy_value(left->value),
               ref_node(left->left), ref_node(left->right->left)),
      new_node(key, value, ref_node(left->right->right), right));
  unref_node(vtable, left);
  return n;
}

static gpr_avl_node *rotate_right_left(const gpr_avl_vtable *vtable, void *key,
                                       void *value, gpr_avl_node *left,
                                       gpr_avl_node *right) {
  /* rotate_left(..., left, rotate_right(right)) */
  gpr_avl_node *n = new_node(
      vtable->copy_key(right->left->key),
      vtable->copy_value(right->left->value),
      new_node(key, value, left, ref_node(right->left->left)),
      new_node(vtable->copy_key(right->key), vtable->copy_value(right->value),
               ref_node(right->left->right), ref_node(right->right)));
  unref_node(vtable, right);
  return n;
}

static gpr_avl_node *rebalance(const gpr_avl_vtable *vtable, void *key,
                               void *value, gpr_avl_node *left,
                               gpr_avl_node *right) {
  switch (node_height(left) - node_height(right)) {
    case 2:
      if (node_height(left->left) - node_height(left->right) == -1) {
        return assert_invariants(
            rotate_left_right(vtable, key, value, left, right));
      } else {
        return assert_invariants(rotate_right(vtable, key, value, left, right));
      }
    case -2:
      if (node_height(right->left) - node_height(right->right) == 1) {
        return assert_invariants(
            rotate_right_left(vtable, key, value, left, right));
      } else {
        return assert_invariants(rotate_left(vtable, key, value, left, right));
      }
    default:
      return assert_invariants(new_node(key, value, left, right));
  }
}

static gpr_avl_node *add_key(const gpr_avl_vtable *vtable, gpr_avl_node *node,
                             void *key, void *value) {
  long cmp;
  if (node == NULL) {
    return new_node(key, value, NULL, NULL);
  }
  cmp = vtable->compare_keys(node->key, key);
  if (cmp == 0) {
    return new_node(key, value, ref_node(node->left), ref_node(node->right));
  } else if (cmp > 0) {
    return rebalance(
        vtable, vtable->copy_key(node->key), vtable->copy_value(node->value),
        add_key(vtable, node->left, key, value), ref_node(node->right));
  } else {
    return rebalance(vtable, vtable->copy_key(node->key),
                     vtable->copy_value(node->value), ref_node(node->left),
                     add_key(vtable, node->right, key, value));
  }
}

gpr_avl gpr_avl_add(gpr_avl avl, void *key, void *value) {
  gpr_avl_node *old_root = avl.root;
  avl.root = add_key(avl.vtable, avl.root, key, value);
  assert_invariants(avl.root);
  unref_node(avl.vtable, old_root);
  return avl;
}

static gpr_avl_node *in_order_head(gpr_avl_node *node) {
  while (node->left != NULL) {
    node = node->left;
  }
  return node;
}

static gpr_avl_node *in_order_tail(gpr_avl_node *node) {
  while (node->right != NULL) {
    node = node->right;
  }
  return node;
}

static gpr_avl_node *remove_key(const gpr_avl_vtable *vtable,
                                gpr_avl_node *node, void *key) {
  long cmp;
  if (node == NULL) {
    return NULL;
  }
  cmp = vtable->compare_keys(node->key, key);
  if (cmp == 0) {
    if (node->left == NULL) {
      return ref_node(node->right);
    } else if (node->right == NULL) {
      return ref_node(node->left);
    } else if (node->left->height < node->right->height) {
      gpr_avl_node *h = in_order_head(node->right);
      return rebalance(vtable, vtable->copy_key(h->key),
                       vtable->copy_value(h->value), ref_node(node->left),
                       remove_key(vtable, node->right, h->key));
    } else {
      gpr_avl_node *h = in_order_tail(node->left);
      return rebalance(
          vtable, vtable->copy_key(h->key), vtable->copy_value(h->value),
          remove_key(vtable, node->left, h->key), ref_node(node->right));
    }
  } else if (cmp > 0) {
    return rebalance(
        vtable, vtable->copy_key(node->key), vtable->copy_value(node->value),
        remove_key(vtable, node->left, key), ref_node(node->right));
  } else {
    return rebalance(vtable, vtable->copy_key(node->key),
                     vtable->copy_value(node->value), ref_node(node->left),
                     remove_key(vtable, node->right, key));
  }
}

gpr_avl gpr_avl_remove(gpr_avl avl, void *key) {
  gpr_avl_node *old_root = avl.root;
  avl.root = remove_key(avl.vtable, avl.root, key);
  assert_invariants(avl.root);
  unref_node(avl.vtable, old_root);
  return avl;
}

gpr_avl gpr_avl_ref(gpr_avl avl) {
  ref_node(avl.root);
  return avl;
}

void gpr_avl_unref(gpr_avl avl) { unref_node(avl.vtable, avl.root); }

int gpr_avl_is_empty(gpr_avl avl) { return avl.root == NULL; }


text:
from __future__ import annotations

from contextvars import ContextVar
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ._structures import JobInfo
    from .schedulers.async_ import AsyncScheduler
    from .schedulers.sync import Scheduler

#: The currently running (local) scheduler
current_scheduler: ContextVar[Scheduler | None] = ContextVar(
    "current_scheduler", default=None
)
current_async_scheduler: ContextVar[AsyncScheduler | None] = ContextVar(
    "current_async_scheduler", default=None
)
#: Metadata about the current job
current_job: ContextVar[JobInfo] = ContextVar("job_info")


text:
package org.w3c.domts.level2.core;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.w3c.dom.*;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.w3c.domts.DOMTest.load;

/**
 * The "getOwnerElement()" will return the Element node this attribute is attached to or
 * null if this attribute is not in use.
 * Retreive the default attribute defaultAttr and check its owner element.  Verify if the name
 * the nodeName of the returned ownerElement is emp:employee.
 *
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#Attr-ownerElement
 * @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=259
 */
public class attrgetownerelement01 {

    @Test
    @Disabled
    public void testRun() throws Throwable {
        Document doc = load("staffNS", false);
        NodeList elementList = doc.getElementsByTagNameNS("http://www.nist.gov", "employee");
        Element element = (Element) elementList.item(1);
        NamedNodeMap attributes = element.getAttributes();
        Attr attr = (Attr) attributes.getNamedItemNS(null, "defaultAttr");
        Element ownerElement = attr.getOwnerElement();
        String ownerElementName = ownerElement.getNodeName();
        assertEquals("emp:employee", ownerElementName, "attrgetownerelement01");
    }

    /**
     * Gets URI that identifies the test
     *
     * @return uri identifier of test
     */
    public String getTargetURI() {
        return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/attrgetownerelement01";
    }

}


text:
<?php

namespace stlrnz\tests\json\converter;

use stlrnz\json\converter\Encoder;
use stlrnz\tests\json\converter\model\SimpleObject;

class EncoderArrayObjectTest extends \PHPUnit_Framework_TestCase
{
	/**
	 * encode ArrayObject (all attributes)
	 */
	public function testEncodeArrayObjectPublic()
	{
		$arr = $this->getTestArray();

		$ec = new Encoder();

		$s = $ec->encode($arr);

		$this->assertJsonStringEqualsJsonString('[1, 2, ["a", "b"], [[9, "z"],[{
														"pubArray": [],
														"pubString": "this is a test"
													}]]]', $s);
	}

	/**
	 * encode ArrayObject (all attributes)
	 */
	public function testEncodeArrayObjectAll()
	{
		$arr = $this->getTestArray();

		$ec = new Encoder();
		$ec->convertNonAccessibleProperties();

		$s = $ec->encode($arr);

		$this->assertJsonStringEqualsJsonString('[1, 2, ["a", "b"], [[9, "z"],[{
														"pubArray": [],
														"pubString": "this is a test",
														"priFloat": 12.3,
														"proInt": 5
													}]]]', $s);
	}

	/**
	 * @return \ArrayObject
	 */
	private function getTestArray()
	{
		$so = new SimpleObject();
		$so->setPriFloat(12.3);
		$so->setProInt(5);
		$so->setPubArray(array());
		$so->setPubString('this is a test');

		$arr = new \ArrayObject();
		$arr->append(1);
		$arr->append(2);
		$arr->append(array('a', 'b'));

		$arr30 = new \ArrayObject();
		$arr30->append(9);
		$arr30->append('z');

		$arr31 = new \ArrayObject();
		$arr31->append($so);

		$arr3 = new \ArrayObject();
		$arr3->append($arr30);
		$arr3->append($arr31);

		$arr->append($arr3);

		return $arr;
	}
}


text:
static NSManagedObjectModel* WYDefaultManagedObjectModel;

@implementation NSManagedObjectModel(WYStore)

+ (instancetype)wy_defaultModel {

    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        [self wy_setDefaultModel];
    });
    return WYDefaultManagedObjectModel;
}

+ (void)wy_setDefaultModel {

    NSString *bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey];
    [self wy_setDefaultModelWithName:bundleName];
}

+ (void)wy_setDefaultModelWithName:(NSString *)name {

    NSArray *namePart = [name componentsSeparatedByString:@"."];
    NSString *resource = [namePart firstObject];
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:resource withExtension:@"momd"];//namePart.count>1? [namePart lastObject] : @"momd"];
    WYDefaultManagedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
}

@end


text:
if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
    PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
    Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
    nitpick = createNitpick(Script.resolvePath("."));
}

nitpick.perform("Image Entity alpha", Script.resolvePath("."), "secondary", undefined, function(testType) {
    Script.include(nitpick.getUtilsRootPath() + "test_stage.js");
    var LIFETIME = 200;

    // Add the test Cases
    var initData = {
        flags: {
            hasKeyLight: true,
            hasAmbientLight: true
        },
        lifetime: LIFETIME,
        originFrame: nitpick.getOriginFrame()
    };
    var createdEntities = setupStage(initData);

    var posOri = getStagePosOriAt(0, 0, 0);
    var assetsRootPath = nitpick.getAssetsRootPath();

    function getPos(col, row) {
        var center = posOri.pos;
        return Vec3.sum(Vec3.sum(center, Vec3.multiply(Quat.getRight(MyAvatar.orientation), col)),
                                         Vec3.multiply(Quat.getUp(MyAvatar.orientation), row));
    }

    var IMAGES_START_INDEX = createdEntities.length;

    createdEntities.push(Entities.addEntity({
        type: "Image",
        imageURL: assetsRootPath + "textures/redArrow.jpg",
        position: getPos(-0.5, 1),
        dimensions: 1.0,
        keepAspectRatio: false,
        alpha: 1.0,
        lifetime: LIFETIME
    }));

    createdEntities.push(Entities.addEntity({
        type: "Image",
        imageURL: assetsRootPath + "textures/redArrow.jpg",
        position: getPos(0.5, 1),
        dimensions: 1.0,
        keepAspectRatio: false,
        alpha: 0.5,
        lifetime: LIFETIME
    }));

    nitpick.addStepSnapshot("Take snapshot");

    nitpick.addStep("Switch alphas of images", function () {
        for (var i = IMAGES_START_INDEX; i < createdEntities.length; i++) {
            var alpha = Entities.getEntityProperties(createdEntities[i]).alpha;
            Entities.editEntity(createdEntities[i], { alpha: -(alpha - 1.5)});
        }
    });

    nitpick.addStepSnapshot("Take snapshot");

    nitpick.addStep("Clean up after test", function () {
        for (var i = 0; i < createdEntities.length; i++) {
            Entities.deleteEntity(createdEntities[i]);
        }
    });

    var result = nitpick.runTest(testType);
});


text:
namespace web {

// A response provider that returns a  string for all requests. Used for testing
// purposes.
class StringResponseProvider : public web::DataResponseProvider {
 public:
  explicit StringResponseProvider(const std::string& response_body);

  // web::DataResponseProvider methods.
  bool CanHandleRequest(const Request& request) override;
  void GetResponseHeadersAndBody(
      const Request& request,
      scoped_refptr<net::HttpResponseHeaders>* headers,
      std::string* response_body) override;

 private:
  // The string that is returned in the response body.
  std::string response_body_;
  DISALLOW_COPY_AND_ASSIGN(StringResponseProvider);
};

}  // namespace web

#endif  // IOS_WEB_PUBLIC_TEST_RESPONSE_PROVIDERS_STRING_RESPONSE_PROVIDER_


text:
import logging
from datetime import datetime

from rx.disposables import Disposable, SingleAssignmentDisposable, \
    CompositeDisposable
from rx.concurrency.scheduler import Scheduler

log = logging.getLogger("Rx")

class IOLoopScheduler(Scheduler):
    """A scheduler that schedules work via the Tornado I/O main event loop.

    http://tornado.readthedocs.org/en/latest/ioloop.html"""

    def __init__(self, loop=None):
        from tornado import ioloop # Lazy import
        self.loop = loop or ioloop.IOLoop.current()

    def schedule(self, action, state=None):
        """Schedules an action to be executed."""

        scheduler = self
        disposable = SingleAssignmentDisposable()
        disposed = [False]

        def interval():
            if not disposed[0]:
                disposable.disposable = action(scheduler, state)

        self.loop.add_callback(interval)

        def dispose():
            # nonlocal
            disposed[0] = True

        return CompositeDisposable(disposable, Disposable(dispose))

    def schedule_relative(self, duetime, action, state=None):
        """Schedules an action to be executed after duetime.

        Keyword arguments:
        duetime -- {timedelta} Relative time after which to execute the action.
        action -- {Function} Action to be executed.

        Returns {Disposable} The disposable object used to cancel the scheduled
        action (best effort)."""

        scheduler = self
        seconds = scheduler.to_relative(duetime)/1000.0
        if not seconds:
            return scheduler.schedule(action, state)

        disposable = SingleAssignmentDisposable()
        def interval():
            disposable.disposable = action(scheduler, state)

        log.debug("timeout: %s", seconds)
        handle = self.loop.call_later(seconds, interval)

        def dispose():
            self.loop.remove_timeout(handle)

        return CompositeDisposable(disposable, Disposable(dispose))

    def schedule_absolute(self, duetime, action, state=None):
        """Schedules an action to be executed at duetime.

        Keyword arguments:
        duetime -- {datetime} Absolute time after which to execute the action.
        action -- {Function} Action to be executed.

        Returns {Disposable} The disposable object used to cancel the scheduled
        action (best effort)."""

        duetime = self.to_datetime(duetime)
        return self.schedule_relative(duetime - self.now(), action, state)

    def now(self):
        """Represents a notion of time for this scheduler. Tasks being scheduled
        on a scheduler will adhere to the time denoted by this property."""

        return self.to_datetime(self.loop.time())


text:
import csv
import sys
import os
import getopt
import glob
import filecmp
import re
from pycsw.core.util import http_request

def plural(num):
    """Determine plurality given an integer"""
    if num != 1:
        return 's'
    else:
        return ''

def get_validity(sexpected, sresult, soutfile, force_id_mask=False):
    """Decipher whether the output passes, fails, or initializes"""
    if not os.path.exists(sexpected):  # create expected file
        expectedfile = open(sexpected, 'w')
        expectedfile.write(normalize(sresult, force_id_mask))
        expectedfile.close()
        sstatus = 0
    else:  # compare result with expected
        if not os.path.exists('results'):
            os.mkdir('results')
        resultfile = open('results%s%s' % (os.sep, soutfile), 'wb')
        resultfile.write(normalize(sresult, force_id_mask))
        resultfile.close()
        if filecmp.cmp(sexpected, 'results%s%s' % (os.sep, soutfile)):  # pass
            os.remove('results%s%s' % (os.sep, soutfile))
            sstatus = 1
        else:  # fail
            import difflib
            diff = difflib.unified_diff(
                open(sexpected).readlines(),
                open('results%s%s' % (os.sep, soutfile)).readlines())
            print '\n'.join(list(diff))
            sstatus = -1
    return sstatus

def normalize(sresult, force_id_mask=False):
    """Replace time, updateSequence and version specific values with generic
    values"""

    # XML responses
    version = re.search('<!-- (.*) -->', sresult)
    updatesequence = re.search('updateSequence="(\S+)"', sresult)
    timestamp = re.search('timestamp="(.*)"', sresult)
    timestamp2 = re.search('timeStamp="(.*)"', sresult)
    timestamp3 = re.search('<oai:responseDate>(.*)</oai:responseDate>', sresult)
    timestamp4 = re.search('<oai:earliestDatestamp>(.*)</oai:earliestDatestamp>', sresult)
    zrhost = re.search('<zr:host>(.*)</zr:host>', sresult)
    zrport = re.search('<zr:port>(.*)</zr:port>', sresult)
    elapsed_time = re.search('elapsedTime="(.*)"', sresult)
    expires = re.search('expires="(.*?)"', sresult)
    atom_updated = re.findall('<atom:updated>(.*)</atom:updated>', sresult)

    if version:
        sresult = sresult.replace(version.group(0), '<!-- PYCSW_VERSION -->')
    if updatesequence:
        sresult = sresult.replace(updatesequence.group(0),
                                  'updateSequence="PYCSW_UPDATESEQUENCE"')
    if timestamp:
        sresult = sresult.replace(timestamp.group(0),
                                  'timestamp="PYCSW_TIMESTAMP"')
    if timestamp2:
        sresult = sresult.replace(timestamp2.group(0),
                                  'timeStamp="PYCSW_TIMESTAMP"')
    if timestamp3:
        sresult = sresult.replace(timestamp3.group(0),
                                  '<oai:responseDate>PYCSW_TIMESTAMP</oai:responseDate>')
    if timestamp4:
        sresult = sresult.replace(timestamp4.group(0),
                                  '<oai:earliestDatestamp>PYCSW_TIMESTAMP</oai:earliestDatestamp>')
    if zrport:
        sresult = sresult.replace(zrport.group(0),
                                  '<zr:port>PYCSW_PORT</zr:port>')
    if zrhost:
        sresult = sresult.replace(zrhost.group(0),
                                  '<zr:host>PYCSW_HOST</zr:host>')
    if elapsed_time:
        sresult = sresult.replace(elapsed_time.group(0),
                                  'elapsedTime="PYCSW_ELAPSED_TIME"')
    if expires:
        sresult = sresult.replace(expires.group(0),
                                  'expires="PYCSW_EXPIRES"')
    for au in atom_updated:
        sresult = sresult.replace(au, 'PYCSW_TIMESTAMP')

    # for csw:HarvestResponse documents, mask identifiers
    # which are dynamically generated for OWS endpoints
    if sresult.find('HarvestResponse') != -1:
        identifier = re.findall('<dc:identifier>(\S+)</dc:identifier>',
                                sresult)
        for i in identifier:
            sresult = sresult.replace(i, 'PYCSW_IDENTIFIER')

    # JSON responses
    timestamp = re.search('"timestamp": "(.*?)"', sresult)

    if timestamp:
        sresult = sresult.replace(timestamp.group(0),
                                  '"timestamp": "PYCSW_TIMESTAMP"')

    # harvesting-based GetRecords/GetRecordById responses
    if force_id_mask:
        dcid = re.findall('<dc:identifier>(urn:uuid.*)</dc:identifier>', sresult)
        isoid = re.findall('id="(urn:uuid.*)"', sresult)
        isoid2 = re.findall('<gco:CharacterString>(urn:uuid.*)</gco', sresult)

        for d in dcid:
            sresult = sresult.replace(d, 'PYCSW_IDENTIFIER')
        for i in isoid:
            sresult = sresult.replace(i, 'PYCSW_IDENTIFIER')
        for i2 in isoid2:
            sresult = sresult.replace(i2, 'PYCSW_IDENTIFIER')

    return sresult

def usage():
    """Provide usage instructions"""
    return '''
NAME
    run_tests.py - pycsw unit test testrunner

SYNOPSIS
    run_tests.py -u <url> [-l logfile] [-s suite1[,suite2]]

    Available options:

    -u    URL to test

    -l    log results to file

    -s    testsuites to run (comma-seperated list)

    -d    database (SQLite3 [default], PostgreSQL, MySQL)

    -r    run tests which harvest remote resources (default off)

EXAMPLES

    1.) default test example

        run_tests.py -u http://localhost:8000/

    2.) log results to logfile

        run_tests.py -u http://localhost:8000/ -l /path/to/results.log

    3.) run only specified testsuites

        run_tests.py -u http://localhost:8000/ -s default,apiso

    3.) run tests including remote harvest tests

        run_tests.py -u http://localhost:8000/ -s default,apiso -r

'''

# main

if len(sys.argv) < 2:
    print usage()
    sys.exit(1)

URL = sys.argv[1]

URL = None
LOGFILE = None
TESTSUITES = []

PASSED = 0
FAILED = 0
WARNING = 0
INITED = 0

LOGWRITER = None
DATABASE = 'SQLite3'
REMOTE = False

try:
    OPTS, ARGS = getopt.getopt(sys.argv[1:], 'u:l:s:d:rh')
except getopt.GetoptError as err:
    print '\nERROR: %s' % err
    print usage()
    sys.exit(2)

for o, a in OPTS:
    if o == '-u':
        URL = a
    if o == '-l':
        LOGFILE = a
    if o == '-d':
        DATABASE = a
    if o == '-r':
        REMOTE = True
    if o == '-s':
        TESTSUITES = a.split(',')
    if o == '-h':  # dump help and exit
        print usage()
        sys.exit(3)

print '\nRunning tests against %s' % URL

if LOGFILE is not None:  # write detailed output to CSV
    LOGWRITER = csv.writer(open(LOGFILE, 'wb'))
    LOGWRITER.writerow(['url', 'configuration', 'testname', 'result'])

if TESTSUITES:
    if 'harvesting' in TESTSUITES:
        REMOTE = True
    TESTSUITES_LIST = ['suites%s%s' % (os.sep, x) for x in TESTSUITES]
else:
    TESTSUITES_LIST = glob.glob('suites%s*' % os.sep)

for testsuite in TESTSUITES_LIST:
    if not os.path.exists(testsuite):
        raise RuntimeError('Testsuite %s not found' % testsuite)

    if testsuite == 'suites%sharvesting' % os.sep and not REMOTE:
        continue

    force_id_mask = False
    if testsuite in ['suites%smanager' % os.sep, 'suites%sharvesting' % os.sep]:
        force_id_mask = True

    # get configuration
    for cfg in glob.glob('%s%s*.cfg' % (testsuite, os.sep)):
        print '\nTesting configuration %s' % cfg

        for root, dirs, files in os.walk(testsuite):
            if files:
                for sfile in sorted(files):
                    if os.path.splitext(sfile)[1] not in ['.xml', '.txt']:
                        break

                    if sfile == 'requests.txt':  # GET requests
                        filename = '%s%s%s' % (root, os.sep, sfile)
                        gets = csv.reader(open(filename))
                        for row in gets:
                            testfile = '%s%s%s' % (root, os.sep, sfile)
                            request = ','.join(row[1:]).replace('PYCSW_SERVER',
                                                                URL)
                            outfile = '%s%s' % (root.replace(os.sep, '_'),
                                                '_%s.xml' % row[0])
                            expected = 'expected%s%s' % (os.sep, outfile)
                            print '\n test %s:%s' % (testfile, row[0])

                            try:
                                result = http_request('GET', request)
                            except Exception as err:
                                result = err.read()

                            status = get_validity(expected, result, outfile,
                                                  force_id_mask)

                            if status == 1:
                                print '  passed'
                                PASSED += 1
                            elif status == 0:
                                print '  initialized'
                                INITED += 1
                            elif status == -1 and DATABASE == 'PostgreSQL':
                                print '  warning: possible collation issue'
                                WARNING += 1
                            else:
                                print '  FAILED'
                                FAILED += 1

                            if LOGWRITER is not None:
                                LOGWRITER.writerow([URL, cfg,
                                                    testfile, status])

                    else:  # POST requests
                        testfile = '%s%s%s' % (root, os.sep, sfile)
                        if '%sdata' % os.sep in testfile:  # sample data
                            break
                        outfile = '%s%s' % (os.sep,
                                            testfile.replace(os.sep, '_'))
                        expected = 'expected%s%s' % (os.sep, outfile)
                        print '\n test %s' % testfile

                        # read test
                        f = open(testfile)
                        request = f.read()
                        f.close()

                        configkvp = 'config=tests%s%s' % (os.sep, cfg)
                        url2 = '%s?%s' % (URL, configkvp)

                        # invoke request
                        try:
                            result = http_request('POST', url2, request)
                        except Exception as err:
                            result = err.read()

                        status = get_validity(expected, result, outfile,
                                              force_id_mask)

                        if status == 1:
                            print '  passed'
                            PASSED += 1
                        elif status == 0:
                            print '  initialized'
                            INITED += 1
                        elif status == -1 and DATABASE == 'PostgreSQL':
                            print '  warning: possible sorting collation issue'
                            WARNING += 1
                        else:
                            print '  FAILED'
                            FAILED += 1

                        if LOGWRITER is not None:
                            LOGWRITER.writerow([URL, cfg, testfile, status])

print '\nResults (%d/%d - %.2f%%)' % \
    (PASSED, PASSED + FAILED, float(PASSED) / float(PASSED + FAILED) * 100)
print '   %d test%s passed' % (PASSED, plural(PASSED))
print '   %d test%s warnings' % (WARNING, plural(WARNING))
print '   %d test%s failed' % (FAILED, plural(FAILED))
print '   %d test%s initialized' % (INITED, plural(INITED))

sys.exit(FAILED)


text:
package gobile.boomesh.com.gobile;

/**
 * Add most test constants for this class.  Can utilize {@link Consts} as well through this class.
 * <p/>
 * Created by sumesh on 12/30/15.
 */
public class TestConsts extends Consts {
    private final static String TAG = TestConsts.class.getSimpleName();
    public final static String PREFS_NAME = TAG + ".UNIT_TESTING_SHARED_PREFS";
}


text:
define("p3/widget/SelectedTable", [
  'dojo/_base/declare', 'dijit/_WidgetBase', 'dojo/dom-construct', 'dojo/query',

  'dojo/NodeList-traverse'
], function (
  declare, WidgetBase, dom, query
) {
  return declare([WidgetBase], {
    colNames: [],     // names of columns
    colKeys: [],      // names of keys for each column
    label: null,      // labels items. example: {rowIndex: 1, colKey: 'name', format: function(rowObj) {}}
    _rows: [],        // data model for rows in table

    _tableHTML:
      '
' +
        '
' +
        '
' +
        '
' +
        '
' +
      '
',

    _emptyHtML:
      '
' +
        'None Selected	' +
      '
',

    _emptyEle: null,   // dom element for empty table

    constructor: function () {
      this._rows = [];
    },

    postCreate: function () {
      var self = this;
      self.inherited(arguments);

      // add list container
      var table = self.table = dom.toDom(this._tableHTML),
        thead = query('thead', table)[0],
        row =  dom.place('
', thead);

      // add header
      self.colNames.forEach(function (name) {
        dom.place('' + name + '	', row);
      });
      dom.place(' 	', row);

      dom.place(row, thead);
      dom.place(table, self.domNode, 'last');

      // "none selected"
      self._addEmptyNotice();
    },

    startup: function () {
      // startup
    },

    /**
     * add item to tablerow of input
     */
    addRow: function (rowObj) {

      var self = this;

      // remove "none selected"
      dom.destroy(self._emptyEle);

      // add to data model
      var rowID = self.table.rows.length;
      self._rows.push(Object.assign({ _rowID: rowID }, rowObj));

      //  add to dom
      var tr = dom.toDom('

');

      var entries = self.colKeys.map(function (key) {
        // add special formatting if needed
        if (self.label && self.label.rowIndex == rowID && self.label.colKey == key) {
          return '' +  self.label.format(rowObj) + '	';
        }

        return ''  + rowObj[key] + '	';
      });

      dom.place(dom.toDom(entries.join('')), tr);
      var rmBtn = dom.toDom('');
      dom.place('' + rmBtn.outerHTML + '	', tr);

      var tbody = query('tbody', self.table)[0];
      dom.place(tr, tbody);

      // reinit delete event
      self._addDeleteEvent(tr);
    },

    _rmRow: function (rowIndex) {
      // update data model
      this._rows.splice(rowIndex - 1, 1);
    },

    _addDeleteEvent: function (tr) {
      var self = this;

      query('.rm-btn', tr).on('click', function () {
        var row = query(this).parents('tr')[0];
        var rowIndex = row.rowIndex;

        self._rmRow(rowIndex);
        dom.destroy(row);

        // add none selected if needed
        if (!self._rows.length) {
          self._addEmptyNotice();
        }

        // add label if needed, and if not removing the last remaining row
        if (self.label && self.label.rowIndex == rowIndex && self._rows.length) {
          var tbody = query('tbody', self.table)[0];
          var i = rowIndex - 1;  // data model is zero-indexed
          var tr = query('tr', tbody)[i];
          var td = query('[data-key="' + self.label.colKey + '"]', tr)[0];
          td.innerHTML = self.label.format(self._rows[i]);
        }
      });
    },

    _addEmptyNotice: function () {
      var tbody = query('tbody', this.table)[0];
      this._emptyEle = dom.place(this._emptyHtML, tbody);
    },

    _getNameAttr: function () {
      // returns the name of the input set
      return this.name;
    },

    getRows: function () {
      return this._rows;
    },

    clear: function () {
      var tbody = query('tbody', this.table)[0];
      dom.empty(tbody);
      this._rows = [];

      this._addEmptyNotice();
    },

    onRmRow: function (id) {
      // if remove item call back is provided, call it
      if (this.onRemove) this.onRemove();
    }

  });
});


text:
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/dns/record_rdata.h"

#include <algorithm>
#include <memory>
#include <utility>

#include "base/big_endian.h"
#include "net/dns/dns_response.h"
#include "net/dns/dns_test_util.h"
#include "net/test/gtest_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

namespace net {
namespace {

using ::testing::ElementsAreArray;
using ::testing::IsNull;
using ::testing::NotNull;
using ::testing::SizeIs;

base::StringPiece MakeStringPiece(const uint8_t* data, unsigned size) {
  const char* data_cc = reinterpret_cast<const char*>(data);
  return base::StringPiece(data_cc, size);
}

base::StringPiece MakeStringPiece(const std::vector<uint8_t>& vec) {
  return MakeStringPiece(vec.data(), vec.size());
}

TEST(RecordRdataTest, ParseSrvRecord) {
  // These are just the rdata portions of the DNS records, rather than complete
  // records, but it works well enough for this test.

  const uint8_t
      record[] =
          {
              0x00, 0x01, 0x00, 0x02, 0x00, 0x50, 0x03, 'w',  'w',
              'w',  0x06, 'g',  'o',  'o',  'g',  'l',  'e',  0x03,
              'c',  'o',  'm',  0x00, 0x01, 0x01, 0x01, 0x02, 0x01,
              0x03, 0x04, 'w',  'w',  'w',  '2',  0xc0, 0x0a,  // Pointer to
                                                               // "google.com"
          };

  DnsRecordParser parser(record, sizeof(record), 0, /*num_records=*/0);
  const unsigned first_record_len = 22;
  base::StringPiece record1_strpiece = MakeStringPiece(
      record, first_record_len);
  base::StringPiece record2_strpiece = MakeStringPiece(
      record + first_record_len, sizeof(record) - first_record_len);

  std::unique_ptr<SrvRecordRdata> record1_obj =
      SrvRecordRdata::Create(record1_strpiece, parser);
  ASSERT_TRUE(record1_obj != nullptr);
  ASSERT_EQ(1, record1_obj->priority());
  ASSERT_EQ(2, record1_obj->weight());
  ASSERT_EQ(80, record1_obj->port());

  ASSERT_EQ("www.google.com", record1_obj->target());

  std::unique_ptr<SrvRecordRdata> record2_obj =
      SrvRecordRdata::Create(record2_strpiece, parser);
  ASSERT_TRUE(record2_obj != nullptr);
  ASSERT_EQ(257, record2_obj->priority());
  ASSERT_EQ(258, record2_obj->weight());
  ASSERT_EQ(259, record2_obj->port());

  ASSERT_EQ("www2.google.com", record2_obj->target());

  ASSERT_TRUE(record1_obj->IsEqual(record1_obj.get()));
  ASSERT_FALSE(record1_obj->IsEqual(record2_obj.get()));
}

TEST(RecordRdataTest, ParseARecord) {
  // These are just the rdata portions of the DNS records, rather than complete
  // records, but it works well enough for this test.

  const uint8_t record[] = {
      0x7F, 0x00, 0x00, 0x01  // 127.0.0.1
  };

  DnsRecordParser parser(record, sizeof(record), 0, /*num_records=*/0);
  base::StringPiece record_strpiece = MakeStringPiece(record, sizeof(record));

  std::unique_ptr<ARecordRdata> record_obj =
      ARecordRdata::Create(record_strpiece, parser);
  ASSERT_TRUE(record_obj != nullptr);

  ASSERT_EQ("127.0.0.1", record_obj->address().ToString());

  ASSERT_TRUE(record_obj->IsEqual(record_obj.get()));
}

TEST(RecordRdataTest, ParseAAAARecord) {
  // These are just the rdata portions of the DNS records, rather than complete
  // records, but it works well enough for this test.

  const uint8_t record[] = {
      0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09  // 1234:5678::9A
  };

  DnsRecordParser parser(record, sizeof(record), 0, /*num_records=*/0);
  base::StringPiece record_strpiece = MakeStringPiece(record, sizeof(record));

  std::unique_ptr<AAAARecordRdata> record_obj =
      AAAARecordRdata::Create(record_strpiece, parser);
  ASSERT_TRUE(record_obj != nullptr);

  ASSERT_EQ("1234:5678::9", record_obj->address().ToString());

  ASSERT_TRUE(record_obj->IsEqual(record_obj.get()));
}

TEST(RecordRdataTest, ParseCnameRecord) {
  // These are just the rdata portions of the DNS records, rather than complete
  // records, but it works well enough for this test.

  const uint8_t record[] = {0x03, 'w', 'w', 'w',  0x06, 'g', 'o', 'o',
                            'g',  'l', 'e', 0x03, 'c',  'o', 'm', 0x00};

  DnsRecordParser parser(record, sizeof(record), 0, /*num_records=*/0);
  base::StringPiece record_strpiece = MakeStringPiece(record, sizeof(record));

  std::unique_ptr<CnameRecordRdata> record_obj =
      CnameRecordRdata::Create(record_strpiece, parser);
  ASSERT_TRUE(record_obj != nullptr);

  ASSERT_EQ("www.google.com", record_obj->cname());

  ASSERT_TRUE(record_obj->IsEqual(record_obj.get()));
}

TEST(RecordRdataTest, ParsePtrRecord) {
  // These are just the rdata portions of the DNS records, rather than complete
  // records, but it works well enough for this test.

  const uint8_t record[] = {0x03, 'w', 'w', 'w',  0x06, 'g', 'o', 'o',
                            'g',  'l', 'e', 0x03, 'c',  'o', 'm', 0x00};

  DnsRecordParser parser(record, sizeof(record), 0, /*num_records=*/0);
  base::StringPiece record_strpiece = MakeStringPiece(record, sizeof(record));

  std::unique_ptr<PtrRecordRdata> record_obj =
      PtrRecordRdata::Create(record_strpiece, parser);
  ASSERT_TRUE(record_obj != nullptr);

  ASSERT_EQ("www.google.com", record_obj->ptrdomain());

  ASSERT_TRUE(record_obj->IsEqual(record_obj.get()));
}

TEST(RecordRdataTest, ParseTxtRecord) {
  // These are just the rdata portions of the DNS records, rather than complete
  // records, but it works well enough for this test.

  const uint8_t record[] = {0x03, 'w', 'w', 'w',  0x06, 'g', 'o', 'o',
                            'g',  'l', 'e', 0x03, 'c',  'o', 'm'};

  DnsRecordParser parser(record, sizeof(record), 0, /*num_records=*/0);
  base::StringPiece record_strpiece = MakeStringPiece(record, sizeof(record));

  std::unique_ptr<TxtRecordRdata> record_obj =
      TxtRecordRdata::Create(record_strpiece, parser);
  ASSERT_TRUE(record_obj != nullptr);

  std::vector<std::string> expected;
  expected.push_back("www");
  expected.push_back("google");
  expected.push_back("com");

  ASSERT_EQ(expected, record_obj->texts());

  ASSERT_TRUE(record_obj->IsEqual(record_obj.get()));
}

TEST(RecordRdataTest, ParseNsecRecord) {
  // These are just the rdata portions of the DNS records, rather than complete
  // records, but it works well enough for this test.

  const uint8_t record[] = {0x03, 'w',  'w',  'w',  0x06, 'g', 'o',
                            'o',  'g',  'l',  'e',  0x03, 'c', 'o',
                            'm',  0x00, 0x00, 0x02, 0x40, 0x01};

  DnsRecordParser parser(record, sizeof(record), 0, /*num_records=*/0);
  base::StringPiece record_strpiece = MakeStringPiece(record, sizeof(record));

  std::unique_ptr<NsecRecordRdata> record_obj =
      NsecRecordRdata::Create(record_strpiece, parser);
  ASSERT_TRUE(record_obj != nullptr);

  ASSERT_EQ(16u, record_obj->bitmap_length());

  EXPECT_FALSE(record_obj->GetBit(0));
  EXPECT_TRUE(record_obj->GetBit(1));
  for (int i = 2; i < 15; i++) {
    EXPECT_FALSE(record_obj->GetBit(i));
  }
  EXPECT_TRUE(record_obj->GetBit(15));

  ASSERT_TRUE(record_obj->IsEqual(record_obj.get()));
}

TEST(RecordRdataTest, CreateNsecRecordWithEmptyBitmapReturnsNull) {
  // These are just the rdata portions of the DNS records, rather than complete
  // records, but it works well enough for this test.
  // This record has a bitmap that is 0 bytes long.
  const uint8_t record[] = {0x03, 'w', 'w',  'w', 0x06, 'g', 'o',  'o',  'g',
                            'l',  'e', 0x03, 'c', 'o',  'm', 0x00, 0x00, 0x00};

  DnsRecordParser parser(record, sizeof(record), 0, /*num_records=*/0);
  base::StringPiece record_strpiece = MakeStringPiece(record, sizeof(record));

  std::unique_ptr<NsecRecordRdata> record_obj =
      NsecRecordRdata::Create(record_strpiece, parser);
  ASSERT_FALSE(record_obj);
}

TEST(RecordRdataTest, CreateNsecRecordWithOversizedBitmapReturnsNull) {
  // These are just the rdata portions of the DNS records, rather than complete
  // records, but it works well enough for this test.
  // This record has a bitmap that is 33 bytes long. The maximum size allowed by
  // RFC 3845, Section 2.1.2, is 32 bytes.
  const uint8_t record[] = {
      0x03, 'w',  'w',  'w',  0x06, 'g',  'o',  'o',  'g',  'l',  'e',
      0x03, 'c',  'o',  'm',  0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

  DnsRecordParser parser(record, sizeof(record), 0, /*num_records=*/0);
  base::StringPiece record_strpiece = MakeStringPiece(record, sizeof(record));

  std::unique_ptr<NsecRecordRdata> record_obj =
      NsecRecordRdata::Create(record_strpiece, parser);
  ASSERT_FALSE(record_obj);
}

// Test that for arbitrary IntegrityRecordRdata r, Parse(Serialize(r)) == r.
TEST(RecordRdataTest, IntegrityParseSerializeInverseProperty) {
  IntegrityRecordRdata record(IntegrityRecordRdata::Random());

  EXPECT_TRUE(record.IsIntact());
  absl::optional<std::vector<uint8_t>> serialized = record.Serialize();
  EXPECT_TRUE(serialized);

  std::unique_ptr<IntegrityRecordRdata> reparsed =
      IntegrityRecordRdata::Create(MakeStringPiece(*serialized));
  EXPECT_TRUE(reparsed);
  EXPECT_TRUE(reparsed->IsEqual(&record));
}

TEST(RecordRdataTest, IntegrityEmptyNonceCornerCase) {
  const IntegrityRecordRdata::Nonce empty_nonce;
  IntegrityRecordRdata record(empty_nonce);
  EXPECT_TRUE(record.IsIntact());

  absl::optional<std::vector<uint8_t>> serialized = record.Serialize();
  EXPECT_TRUE(serialized);
  std::unique_ptr<IntegrityRecordRdata> reparsed =
      IntegrityRecordRdata::Create(MakeStringPiece(*serialized));
  EXPECT_TRUE(reparsed);
  EXPECT_TRUE(reparsed->IsIntact());
  EXPECT_TRUE(reparsed->IsEqual(&record));
  EXPECT_EQ(reparsed->nonce().size(), 0u);
}

TEST(RecordRdataTest, IntegrityMoveConstructor) {
  IntegrityRecordRdata record_a(IntegrityRecordRdata::Random());
  EXPECT_TRUE(record_a.IsIntact());
  absl::optional<std::vector<uint8_t>> serialized_a = record_a.Serialize();
  EXPECT_TRUE(serialized_a);

  IntegrityRecordRdata record_b = std::move(record_a);
  EXPECT_TRUE(record_b.IsIntact());
  absl::optional<std::vector<uint8_t>> serialized_b = record_b.Serialize();
  EXPECT_TRUE(serialized_b);

  EXPECT_EQ(serialized_a, serialized_b);
}

TEST(RecordRdataTest, IntegrityRandomRecordsDiffer) {
  IntegrityRecordRdata record_a(IntegrityRecordRdata::Random());
  IntegrityRecordRdata record_b(IntegrityRecordRdata::Random());
  EXPECT_TRUE(!record_a.IsEqual(&record_b));
}

TEST(RecordRdataTest, IntegritySerialize) {
  IntegrityRecordRdata record({'A'});
  EXPECT_TRUE(record.IsIntact());
  const absl::optional<std::vector<uint8_t>> serialized = record.Serialize();
  EXPECT_TRUE(serialized);

  // Expected payload contains the SHA256 hash of 'A'. For the lazy:
  //   $ echo -n A | sha256sum | cut -f1 -d' ' | sed -e 's/\(..\)/0x\1, /g'
  const std::vector<uint8_t> expected = {
      0, 1, 'A',  // Length prefix and nonce
                  // Begin digest
      0x55, 0x9a, 0xea, 0xd0, 0x82, 0x64, 0xd5, 0x79, 0x5d, 0x39, 0x09, 0x71,
      0x8c, 0xdd, 0x05, 0xab, 0xd4, 0x95, 0x72, 0xe8, 0x4f, 0xe5, 0x55, 0x90,
      0xee, 0xf3, 0x1a, 0x88, 0xa0, 0x8f, 0xdf, 0xfd,  // End digest
  };

  EXPECT_TRUE(*serialized == expected);
}

TEST(RecordRdataTest, IntegrityParse) {
  const std::vector<uint8_t> serialized = {
      0,    6,    'f',  'o',  'o',  'b',  'a',  'r',  // Length prefix and nonce
      0xc3, 0xab, 0x8f, 0xf1, 0x37, 0x20, 0xe8, 0xad, 0x90,  // Begin digest
      0x47, 0xdd, 0x39, 0x46, 0x6b, 0x3c, 0x89, 0x74, 0xe5, 0x92, 0xc2,
      0xfa, 0x38, 0x3d, 0x4a, 0x39, 0x60, 0x71, 0x4c, 0xae, 0xf0, 0xc4,
      0xf2,  // End digest
  };
  auto record = IntegrityRecordRdata::Create(MakeStringPiece(serialized));
  EXPECT_TRUE(record);
  EXPECT_TRUE(record->IsIntact());
}

TEST(RecordRdataTest, IntegrityBadParseEmptyRdata) {
  const std::vector<uint8_t> serialized = {};
  auto record = IntegrityRecordRdata::Create(MakeStringPiece(serialized));
  EXPECT_TRUE(record);
  EXPECT_FALSE(record->IsIntact());
}

TEST(RecordRdataTest, IntegrityBadParseTruncatedNonce) {
  const std::vector<uint8_t> serialized = {
      0, 6, 'f', 'o', 'o'  // Length prefix and truncated nonce
  };
  auto record = IntegrityRecordRdata::Create(MakeStringPiece(serialized));
  EXPECT_TRUE(record);
  EXPECT_FALSE(record->IsIntact());
}

TEST(RecordRdataTest, IntegrityBadParseTruncatedDigest) {
  const std::vector<uint8_t> serialized = {
      0, 6, 'f', 'o', 'o', 'b', 'a', 'r',  // Length prefix and nonce
                                           // Begin Digest
      0xc3, 0xab, 0x8f, 0xf1, 0x37, 0x20, 0xe8, 0xad, 0x90, 0x47, 0xdd, 0x39,
      0x46, 0x6b, 0x3c, 0x89, 0x74, 0xe5, 0x92, 0xc2, 0xfa, 0x38, 0x3d,
      0x4a,  // End digest
  };
  auto record = IntegrityRecordRdata::Create(MakeStringPiece(serialized));
  EXPECT_TRUE(record);
  EXPECT_FALSE(record->IsIntact());
}

TEST(RecordRdataTest, IntegrityBadParseExtraBytes) {
  const std::vector<uint8_t> serialized = {
      0, 6, 'f', 'o', 'o', 'b', 'a', 'r',  // Length prefix and nonce
                                           // Begin digest
      0xc3, 0xab, 0x8f, 0xf1, 0x37, 0x20, 0xe8, 0xad, 0x90, 0x47, 0xdd, 0x39,
      0x46, 0x6b, 0x3c, 0x89, 0x74, 0xe5, 0x92, 0xc2, 0xfa, 0x38, 0x3d, 0x4a,
      0x39, 0x60, 0x71, 0x4c, 0xae, 0xf0, 0xc4, 0xf2,  // End digest
      'e', 'x', 't', 'r', 'a'                          // Trailing bytes
  };
  auto record = IntegrityRecordRdata::Create(MakeStringPiece(serialized));
  EXPECT_TRUE(record);
  EXPECT_FALSE(record->IsIntact());
}

TEST(RecordRdataTest, IntegrityCorruptedDigest) {
  const std::vector<uint8_t> serialized = {
      0,    6,    'f',  'o',  'o',  'b',  'a',  'r',  // Length prefix and nonce
      0xde, 0xad, 0xbe, 0xef, 0x37, 0x20, 0xe8, 0xad, 0x90,  // Begin digest
      0x47, 0xdd, 0x39, 0x46, 0x6b, 0x3c, 0x89, 0x74, 0xe5, 0x92, 0xc2,
      0xfa, 0x38, 0x3d, 0x4a, 0x39, 0x60, 0x71, 0x4c, 0xae, 0xf0, 0xc4,
      0xf2,  // End digest
  };
  auto record = IntegrityRecordRdata::Create(MakeStringPiece(serialized));
  EXPECT_TRUE(record);
  EXPECT_FALSE(record->IsIntact());
}

}  // namespace
}  // namespace net


text:
<?php

class php_Web {
	public function __construct(){}
	static function getParams() {
		$a = array_merge($_GET, $_POST);
		if(get_magic_quotes_gpc()) {
			reset($a); while(list($k, $v) = each($a)) $a[$k] = stripslashes((string)$v);
		}
		return php_Lib::hashOfAssociativeArray($a);
	}
	static function getMethod() {
		if(isset($_SERVER['REQUEST_METHOD'])) {
			return $_SERVER['REQUEST_METHOD'];
		} else {
			return null;
		}
	}
	static $isModNeko;
	function __toString() { return 'php.Web'; }
}
php_Web::$isModNeko = !php_Lib::isCli();


text:
'use strict';

var global = (function () {
  if (typeof globalThis !== 'undefined') {
    return globalThis;
  } else if (typeof global !== 'undefined') {
    return global;
  } else if (typeof self !== 'undefined') {
    return self;
  } else if (typeof window !== 'undefined') {
    return window;
  } else {
    return Function('return this')();
  }
})();

var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.default = void 0;

var fs = _interopRequireWildcard(require('graceful-fs'));

var _jestMessageUtil = require('jest-message-util');

var _InlineSnapshots = require('./InlineSnapshots');

var _utils = require('./utils');

function _getRequireWildcardCache(nodeInterop) {
  if (typeof WeakMap !== 'function') return null;
  var cacheBabelInterop = new WeakMap();
  var cacheNodeInterop = new WeakMap();
  return (_getRequireWildcardCache = function (nodeInterop) {
    return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
  })(nodeInterop);
}

function _interopRequireWildcard(obj, nodeInterop) {
  if (!nodeInterop && obj && obj.__esModule) {
    return obj;
  }
  if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
    return {default: obj};
  }
  var cache = _getRequireWildcardCache(nodeInterop);
  if (cache && cache.has(obj)) {
    return cache.get(obj);
  }
  var newObj = {};
  var hasPropertyDescriptor =
    Object.defineProperty && Object.getOwnPropertyDescriptor;
  for (var key in obj) {
    if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
      var desc = hasPropertyDescriptor
        ? Object.getOwnPropertyDescriptor(obj, key)
        : null;
      if (desc && (desc.get || desc.set)) {
        Object.defineProperty(newObj, key, desc);
      } else {
        newObj[key] = obj[key];
      }
    }
  }
  newObj.default = obj;
  if (cache) {
    cache.set(obj, newObj);
  }
  return newObj;
}

var global = (function () {
  if (typeof globalThis !== 'undefined') {
    return globalThis;
  } else if (typeof global !== 'undefined') {
    return global;
  } else if (typeof self !== 'undefined') {
    return self;
  } else if (typeof window !== 'undefined') {
    return window;
  } else {
    return Function('return this')();
  }
})();

var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;

var global = (function () {
  if (typeof globalThis !== 'undefined') {
    return globalThis;
  } else if (typeof global !== 'undefined') {
    return global;
  } else if (typeof self !== 'undefined') {
    return self;
  } else if (typeof window !== 'undefined') {
    return window;
  } else {
    return Function('return this')();
  }
})();

var jestExistsFile =
  global[Symbol.for('jest-native-exists-file')] || fs.existsSync;

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}

class SnapshotState {
  // @ts-expect-error
  constructor(snapshotPath, options) {
    _defineProperty(this, '_counters', void 0);

    _defineProperty(this, '_dirty', void 0);

    _defineProperty(this, '_index', void 0);

    _defineProperty(this, '_updateSnapshot', void 0);

    _defineProperty(this, '_snapshotData', void 0);

    _defineProperty(this, '_initialData', void 0);

    _defineProperty(this, '_snapshotPath', void 0);

    _defineProperty(this, '_inlineSnapshots', void 0);

    _defineProperty(this, '_uncheckedKeys', void 0);

    _defineProperty(this, '_prettierPath', void 0);

    _defineProperty(this, '_snapshotFormat', void 0);

    _defineProperty(this, 'added', void 0);

    _defineProperty(this, 'expand', void 0);

    _defineProperty(this, 'matched', void 0);

    _defineProperty(this, 'unmatched', void 0);

    _defineProperty(this, 'updated', void 0);

    this._snapshotPath = snapshotPath;
    const {data, dirty} = (0, _utils.getSnapshotData)(
      this._snapshotPath,
      options.updateSnapshot
    );
    this._initialData = data;
    this._snapshotData = data;
    this._dirty = dirty;
    this._prettierPath = options.prettierPath;
    this._inlineSnapshots = [];
    this._uncheckedKeys = new Set(Object.keys(this._snapshotData));
    this._counters = new Map();
    this._index = 0;
    this.expand = options.expand || false;
    this.added = 0;
    this.matched = 0;
    this.unmatched = 0;
    this._updateSnapshot = options.updateSnapshot;
    this.updated = 0;
    this._snapshotFormat = options.snapshotFormat;
  }

  markSnapshotsAsCheckedForTest(testName) {
    this._uncheckedKeys.forEach(uncheckedKey => {
      if ((0, _utils.keyToTestName)(uncheckedKey) === testName) {
        this._uncheckedKeys.delete(uncheckedKey);
      }
    });
  }

  _addSnapshot(key, receivedSerialized, options) {
    this._dirty = true;

    if (options.isInline) {
      const error = options.error || new Error();
      const lines = (0, _jestMessageUtil.getStackTraceLines)(
        (0, _utils.removeLinesBeforeExternalMatcherTrap)(error.stack || '')
      );
      const frame = (0, _jestMessageUtil.getTopFrame)(lines);

      if (!frame) {
        throw new Error(
          "Jest: Couldn't infer stack frame for inline snapshot."
        );
      }

      this._inlineSnapshots.push({
        frame,
        snapshot: receivedSerialized
      });
    } else {
      this._snapshotData[key] = receivedSerialized;
    }
  }

  clear() {
    this._snapshotData = this._initialData;
    this._inlineSnapshots = [];
    this._counters = new Map();
    this._index = 0;
    this.added = 0;
    this.matched = 0;
    this.unmatched = 0;
    this.updated = 0;
  }

  save() {
    const hasExternalSnapshots = Object.keys(this._snapshotData).length;
    const hasInlineSnapshots = this._inlineSnapshots.length;
    const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots;
    const status = {
      deleted: false,
      saved: false
    };

    if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) {
      if (hasExternalSnapshots) {
        (0, _utils.saveSnapshotFile)(this._snapshotData, this._snapshotPath);
      }

      if (hasInlineSnapshots) {
        (0, _InlineSnapshots.saveInlineSnapshots)(
          this._inlineSnapshots,
          this._prettierPath
        );
      }

      status.saved = true;
    } else if (!hasExternalSnapshots && jestExistsFile(this._snapshotPath)) {
      if (this._updateSnapshot === 'all') {
        fs.unlinkSync(this._snapshotPath);
      }

      status.deleted = true;
    }

    return status;
  }

  getUncheckedCount() {
    return this._uncheckedKeys.size || 0;
  }

  getUncheckedKeys() {
    return Array.from(this._uncheckedKeys);
  }

  removeUncheckedKeys() {
    if (this._updateSnapshot === 'all' && this._uncheckedKeys.size) {
      this._dirty = true;

      this._uncheckedKeys.forEach(key => delete this._snapshotData[key]);

      this._uncheckedKeys.clear();
    }
  }

  match({testName, received, key, inlineSnapshot, isInline, error}) {
    this._counters.set(testName, (this._counters.get(testName) || 0) + 1);

    const count = Number(this._counters.get(testName));

    if (!key) {
      key = (0, _utils.testNameToKey)(testName, count);
    } // Do not mark the snapshot as "checked" if the snapshot is inline and
    // there's an external snapshot. This way the external snapshot can be
    // removed with `--updateSnapshot`.

    if (!(isInline && this._snapshotData[key] !== undefined)) {
      this._uncheckedKeys.delete(key);
    }

    const receivedSerialized = (0, _utils.addExtraLineBreaks)(
      (0, _utils.serialize)(received, undefined, this._snapshotFormat)
    );
    const expected = isInline ? inlineSnapshot : this._snapshotData[key];
    const pass = expected === receivedSerialized;
    const hasSnapshot = expected !== undefined;
    const snapshotIsPersisted = isInline || fs.existsSync(this._snapshotPath);

    if (pass && !isInline) {
      // Executing a snapshot file as JavaScript and writing the strings back
      // when other snapshots have changed loses the proper escaping for some
      // characters. Since we check every snapshot in every test, use the newly
      // generated formatted string.
      // Note that this is only relevant when a snapshot is added and the dirty
      // flag is set.
      this._snapshotData[key] = receivedSerialized;
    } // These are the conditions on when to write snapshots:
    //  * There's no snapshot file in a non-CI environment.
    //  * There is a snapshot file and we decided to update the snapshot.
    //  * There is a snapshot file, but it doesn't have this snaphsot.
    // These are the conditions on when not to write snapshots:
    //  * The update flag is set to 'none'.
    //  * There's no snapshot file or a file without this snapshot on a CI environment.

    if (
      (hasSnapshot && this._updateSnapshot === 'all') ||
      ((!hasSnapshot || !snapshotIsPersisted) &&
        (this._updateSnapshot === 'new' || this._updateSnapshot === 'all'))
    ) {
      if (this._updateSnapshot === 'all') {
        if (!pass) {
          if (hasSnapshot) {
            this.updated++;
          } else {
            this.added++;
          }

          this._addSnapshot(key, receivedSerialized, {
            error,
            isInline
          });
        } else {
          this.matched++;
        }
      } else {
        this._addSnapshot(key, receivedSerialized, {
          error,
          isInline
        });

        this.added++;
      }

      return {
        actual: '',
        count,
        expected: '',
        key,
        pass: true
      };
    } else {
      if (!pass) {
        this.unmatched++;
        return {
          actual: (0, _utils.removeExtraLineBreaks)(receivedSerialized),
          count,
          expected:
            expected !== undefined
              ? (0, _utils.removeExtraLineBreaks)(expected)
              : undefined,
          key,
          pass: false
        };
      } else {
        this.matched++;
        return {
          actual: '',
          count,
          expected: '',
          key,
          pass: true
        };
      }
    }
  }

  fail(testName, _received, key) {
    this._counters.set(testName, (this._counters.get(testName) || 0) + 1);

    const count = Number(this._counters.get(testName));

    if (!key) {
      key = (0, _utils.testNameToKey)(testName, count);
    }

    this._uncheckedKeys.delete(key);

    this.unmatched++;
    return key;
  }
}

exports.default = SnapshotState;


text:
package com.rhizospherejs.gwt.rebind;

import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.core.ext.typeinfo.TypeOracle;

import java.io.PrintWriter;

/**
 * Code generator that generates
 * {@link com.rhizospherejs.gwt.client.RhizosphereMapping} implementations from
 * {@link com.rhizospherejs.gwt.client.RhizosphereModel} subclasses.
 *

 * The purpose of this generator is to let Rhizosphere users use their custom
 * POJOs to define the datasets Rhizosphere will visualize.
 *

 * Rhizosphere defines a dataset as a set of models (each model
 * represents a single datapoint of the dataset) and an associated
 * metamodel (to contain the dataset metadata). Rhizosphere internally
 * uses custom tailored JavaScriptObjects to represent both models and
 * metamodels.
 *

 * The generator parses POJOs marked with the
 * {@link com.rhizospherejs.gwt.client.RhizosphereModel} interface, associated
 * {@link com.rhizospherejs.gwt.client.RhizosphereModelAttribute} annotations
 * and related interfaces and emits implementations of
 * {@link com.rhizospherejs.gwt.client.RhizosphereMapping} which are capable of
 * transforming user provided POJOs into Rhizosphere-compatible models and
 * metamodel instances.
 *

 * Code generation proceeds as follows:
 *

 *
{@link BridgeCapabilities} determine which Java types can be successfully
 *   converted into Rhizosphere data types.

 *
{@link ModelInspector} analyzes the user-defined POJO and identifies
 *   all the attributes that must be exposed within Rhizosphere, along with
 *   the associated metadata.

 *
{@link MappingWriter} uses the information extracted by the previous 2
 *   steps a generates factories capable of converting user-provided POJOs into
 *   Rhizosphere-compatible JavaScriptObjects.

 *

 *
 * @author battlehorse@google.com (Riccardo Govoni)
 */
public class RhizosphereGenerator extends Generator {

  @Override
  public String generate(TreeLogger logger, GeneratorContext context, String requestedClass)
      throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    JClassType modelType;
    try {
      modelType = oracle.getType(requestedClass);
    } catch (NotFoundException e) {
      logger.log(TreeLogger.ERROR, "Unable to find class type for " + requestedClass + ":" + e);
      throw new UnableToCompleteException();
    }

    BridgeCapabilities bridgeCapabilities = new BridgeCapabilities(
        logger.branch(TreeLogger.TRACE, "Initializing BridgeCapabilities."), oracle).configure();
    ModelInspector inspector = new ModelInspector(
        logger.branch(TreeLogger.TRACE, "Initializing ModelInspector."),
        oracle,
        modelType,
        bridgeCapabilities).configure();

    String mappingPackageName = modelType.getPackage().getName();
    String mappingClassName = MappingWriter.getMappingClassName(modelType.getSimpleSourceName());
    PrintWriter pw = context.tryCreate(logger, mappingPackageName, mappingClassName);
    if (pw == null) {
      logger.log(TreeLogger.INFO, mappingClassName + " already exists. Nothing to do.");
      return mappingPackageName + "." + mappingClassName;
    }

    MappingWriter writer = new MappingWriter(
        logger.branch(TreeLogger.TRACE, "Initializing MappingWriter."),
        pw,
        mappingPackageName,
        modelType.getSimpleSourceName(),
        bridgeCapabilities,
        inspector);
    writer.write();
    context.commit(logger, pw);
    return mappingPackageName + "." + mappingClassName;
  }
}


text:
mySuperFastAndCleverBot - A PyRat I.A. from Team Roquette
=========================================================

Description
-----------

PyRat est un jeu proposé par [Télécom Bretagne](http://formations.telecom-bretagne.eu/pyrat/)
dont le but est de programmer une intelligence artificielle. Il s'agit de récupérer des pièces
dans un labyrinthe et ce plus rapidement que notre adversaire.

Vous trouverez ici nos I.A.s pour ce jeu.

Structure
---------

Le code est modulaire, dans lib plusieurs modules:

* PyratApi.py          : Communication avec le jeu PyRat.
* connard.py           : Mise en évidence et exploitation de failles du jeu.
* shortestPaths.py     : Algorithme de calcul de plus court chemin.
* travelHeuristics.py  : Plusieurs heuristiques de résolution du problème de voyageur de commerce.
* utils.py             : Divers petites fonctions.

Bots
----

Plusieurs bots sont dispos :

* enculay.py      : Met en oeuvre la lib connard pour tricher.
* fourmis.py      : Implémente une heuristique d'optimisation par colonie de fourmis.
* greedy.py       : Algorithme glouton avec annulation si l'adversaire a pris notre objectif.
* parralelTry.py  : Tentative de parralélisation du calcul du méta-graphe (mono-coeur sur python, abandon).
* template.py     : template d'I.A.s, va en haut à chaque tour.

Auteur/Contact
--------------

Théo JACQUIN et Quentin JODELET, élèves 1A FIG à Télécom Bretagne (et fiers de l'etre).