text:
//
//  DDModelHttpClient+DDAddition.h
//  DDModel
//
//  Created by DeJohn on 15/5/25.
//  Copyright (c) 2015年 DDKit. All rights reserved.
//

#import "DDModelHttpClient.h"
#import "MBProgressHUD.h"

@interface DDModelHttpClient (DDAddition)

@property (nonatomic, strong) MBProgressHUD *hud;

/**
 *  show hud if flag is YES
 *
 *  @param flag flag
 */
- (void)showHud:(BOOL)flag;

/**
 *  hide hud if flag is YES
 *
 *  @param flag flag
 */
- (void)hideHud:(BOOL)flag;

@end

@interface DDModelHttpClient (NSURLSessionTaskHandler)

@property (nonatomic, strong) NSMutableDictionary *ddHttpQueueDict;

/**
 *  Add the requesting task into the tasks queue with the key. the tasks queue may have many keys, so we use the key value to
 *
 *  @param task requesting task
 *  @param key  key
 */
- (void)addTask:(NSURLSessionDataTask *)task withKey:(id)key;

/**
 *  Cancel the requesting task in the tasks queue with the key.
 *
 *  @param task requesting task
 *  @param key  key
 */
- (void)removeTask:(NSURLSessionDataTask *)task withKey:(id)key;

/**
 *  Cancel the all requesting tasks in tasks queue with the key.
 *
 *  @param key key
 */
- (void)cancelTasksWithKey:(id)key;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@android:color/darker_gray"
    android:layout_width="match_parent"
    android:layout_gravity="center"
    android:layout_height="match_parent">

    <TextView
        android:layout_gravity="center"
        android:id="@+id/custome_textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="dialog"
        android:textColor="#ee0000"
        android:gravity="center" />

    <Button
        android:id="@+id/changeTextBtn"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:text="change text" />
</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
namespace CharacterManager.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class ValidRacialClassesRenamed : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(ValidRacialClassesRenamed));

        string IMigrationMetadata.Id
        {
            get { return "201510210446043_ValidRacialClassesRenamed"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
import sys
import unittest

from unittest.mock import call, patch, Mock, DEFAULT
from supervisor.events import *

from supvisors.tests.base import MockedSupvisors

class ListenerTest(unittest.TestCase):
    """ Test case for the listener module. """

    def setUp(self):
        """ Create a logger that stores log traces. """
        self.supvisors = MockedSupvisors()

    @patch.dict('sys.modules', {'supvisors.statscollector': None})
    def test_creation_no_collector(self):
        """ Test the values set at construction. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # check attributes
        self.assertIs(self.supvisors, listener.supvisors)
        self.assertIsNone(listener.collector)
        self.assertEqual('127.0.0.1', listener.address)
        self.assertIsNone(listener.publisher)
        self.assertIsNone(listener.main_loop)
        # test that callbacks are set in Supervisor
        self.assertIn((SupervisorRunningEvent, listener.on_running), callbacks)
        self.assertIn((SupervisorStoppingEvent, listener.on_stopping), callbacks)
        self.assertIn((ProcessStateEvent, listener.on_process), callbacks)
        self.assertIn((Tick5Event, listener.on_tick), callbacks)
        self.assertIn((RemoteCommunicationEvent, listener.on_remote_event), callbacks)

    @patch.dict('sys.modules',
                **{'supvisors.statscollector': Mock(
                    **{'instant_statistics.side_effect': lambda: True})})
    def test_creation(self):
        """ Test the values set at construction. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # check attributes
        self.assertIs(self.supvisors, listener.supvisors)
        self.assertTrue(listener.collector())
        self.assertEqual('127.0.0.1', listener.address)
        self.assertIsNone(listener.publisher)
        self.assertIsNone(listener.main_loop)
        # test that callbacks are set in Supervisor
        self.assertIn((SupervisorRunningEvent, listener.on_running), callbacks)
        self.assertIn((SupervisorStoppingEvent, listener.on_stopping), callbacks)
        self.assertIn((ProcessStateEvent, listener.on_process), callbacks)
        self.assertIn((Tick5Event, listener.on_tick), callbacks)
        self.assertIn((RemoteCommunicationEvent, listener.on_remote_event), callbacks)

    def test_on_running(self):
        """ Test the reception of a Supervisor RUNNING event. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        ref_publisher = listener.publisher
        ref_main_loop = listener.main_loop
        with patch.object(self.supvisors.info_source, 'replace_default_handler') as mocked_infosource:
            with patch('supvisors.listener.SupervisorZmq') as mocked_zmq:
                with patch('supvisors.listener.SupvisorsMainLoop') as mocked_loop:
                    listener.on_running('')
                    # test attributes and calls
                    self.assertTrue(mocked_infosource.called)
                    self.assertTrue(mocked_zmq.called)
                    self.assertIsNot(ref_publisher, listener.publisher)
                    self.assertTrue(mocked_loop.called)
                    self.assertIsNot(ref_main_loop, listener.main_loop)
                    self.assertTrue(listener.main_loop.start.called)

    def test_on_stopping(self):
        """ Test the reception of a Supervisor STOPPING event. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # create a main_loop patch
        listener.main_loop = Mock(**{'stop.return_value': None})
        with patch.object(self.supvisors.info_source, 'close_httpservers') as mocked_infosource:
            # 1. test with unmarked logger, i.e. meant to be the supervisor logger
            listener.on_stopping('')
            self.assertEqual([], callbacks)
            self.assertTrue(mocked_infosource.called)
            self.assertTrue(listener.main_loop.stop.called)
            self.assertTrue(self.supvisors.zmq.close.called)
            self.assertFalse(self.supvisors.logger.close.called)
            # reset mocks
            mocked_infosource.reset_mock()
            listener.main_loop.stop.reset_mock()
            self.supvisors.zmq.close.reset_mock()
            # 2. test with marked logger, i.e. meant to be the Supvisors logger
            listener.logger.SUPVISORS = None
            listener.on_stopping('')
            self.assertEqual([], callbacks)
            self.assertTrue(mocked_infosource.called)
            self.assertTrue(listener.main_loop.stop.called)
            self.assertTrue(self.supvisors.zmq.close.called)
            self.assertTrue(self.supvisors.logger.close.called)

    @patch('supvisors.listener.time.time', return_value=77)
    def test_on_process(self, mocked_time):
        """ Test the reception of a Supervisor PROCESS event. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # create a publisher patch
        listener.publisher = Mock(**{'send_process_event.return_value': None})
        # test non-process event
        with self.assertRaises(AttributeError):
            listener.on_process(Tick60Event(0, None))
        # test process event
        process = Mock(pid=1234, spawnerr='resource not available',
                       **{'config.name': 'dummy_process',
                          'config.extra_args': '-s test',
                          'group.config.name': 'dummy_group'})
        event = ProcessStateFatalEvent(process, '')
        listener.on_process(event)
        self.assertEqual([call({'name': 'dummy_process',
                                'group': 'dummy_group',
                                'state': 200,
                                'extra_args': '-s test',
                                'now': 77,
                                'pid': 1234,
                                'expected': True,
                                'spawnerr': 'resource not available'})],
                         listener.publisher.send_process_event.call_args_list)

    @patch.dict('sys.modules',
                **{'supvisors.statscollector': Mock(
                    **{'instant_statistics.return_value': (8.5, [(25, 400)], 76.1, {'lo': (500, 500)}, {})})})
    def test_on_tick(self):
        """ Test the reception of a Supervisor TICK event. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # create patches
        listener.publisher = Mock(**{'send_tick_event.return_value': None,
                                     'send_statistics.return_value': None})
        listener.fsm.on_timer_event.return_value = ['10.0.0.1', '10.0.0.4']
        self.supvisors.context.addresses['127.0.0.1'] = Mock(**{'pid_processes.return_value': []})
        # test non-process event
        with self.assertRaises(AttributeError):
            listener.on_tick(ProcessStateFatalEvent(None, ''))
        # test process event
        event = Tick60Event(120, None)
        listener.on_tick(event)
        self.assertEqual([call({'when': 120})],
                         listener.publisher.send_tick_event.call_args_list)
        self.assertEqual([call((8.5, [(25, 400)], 76.1, {'lo': (500, 500)}, {}))],
                         listener.publisher.send_statistics.call_args_list)
        self.assertEqual([call()], listener.fsm.on_timer_event.call_args_list)
        self.assertEqual([call(['10.0.0.1', '10.0.0.4'])],
                         self.supvisors.zmq.pusher.send_isolate_addresses.call_args_list)

    def test_unstack_event(self):
        """ Test the processing of a Supvisors event. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # test tick event
        listener.unstack_event('[0, "10.0.0.1", "data"]')
        self.assertEqual([call('10.0.0.1', 'data')],
                         listener.fsm.on_tick_event.call_args_list)
        self.assertFalse(listener.fsm.on_process_event.called)
        self.assertFalse(listener.statistician.push_statistics.called)
        listener.fsm.on_tick_event.reset_mock()
        # test process event
        listener.unstack_event('[1, "10.0.0.2", {"name": "dummy"}]')
        self.assertFalse(listener.fsm.on_tick_event.called)
        self.assertEqual([call('10.0.0.2', {"name": "dummy"})],
                         listener.fsm.on_process_event.call_args_list)
        self.assertFalse(listener.statistician.push_statistics.called)
        listener.fsm.on_process_event.reset_mock()
        # test statistics event
        listener.unstack_event('[2, "10.0.0.3", [0, [[20, 30]], {"lo": [100, 200]}, {}]]')
        self.assertFalse(listener.fsm.on_tick_event.called)
        self.assertFalse(listener.fsm.on_process_event.called)
        self.assertEqual([call('10.0.0.3', [0, [[20, 30]], {"lo": [100, 200]}, {}])],
                         listener.statistician.push_statistics.call_args_list)

    def test_unstack_info(self):
        """ Test the processing of a Supvisors information. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # test info event
        listener.unstack_info('["10.0.0.4", {"name": "dummy"}]')
        self.assertEqual([call('10.0.0.4', {"name": "dummy"})],
                         listener.fsm.on_process_info.call_args_list)

    def test_authorization(self):
        """ Test the processing of a Supvisors authorization. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        listener.authorization('address_name:10.0.0.5 authorized:False master_address:10.0.0.1')
        self.assertEqual([call('10.0.0.5', False, '10.0.0.1')], listener.fsm.on_authorization.call_args_list)

    def test_on_remote_event(self):
        """ Test the reception of a Supervisor remote comm event. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # add patches for what is tested just above
        with patch.multiple(listener, unstack_event=DEFAULT,
                            unstack_info=DEFAULT, authorization=DEFAULT):
            # test unknown type
            event = Mock(type='unknown', data='')
            listener.on_remote_event(event)
            listener.unstack_event.assert_not_called()
            listener.unstack_info.assert_not_called()
            listener.authorization.assert_not_called()
            # test event
            event = Mock(type='event', data={'state': 'RUNNING'})
            listener.on_remote_event(event)
            self.assertEqual([call({'state': 'RUNNING'})],
                             listener.unstack_event.call_args_list)
            listener.unstack_info.assert_not_called()
            listener.authorization.assert_not_called()
            listener.unstack_event.reset_mock()
            # test info
            event = Mock(type='info', data={'name': 'dummy_process'})
            listener.on_remote_event(event)
            listener.unstack_event.assert_not_called()
            self.assertEqual([call({'name': 'dummy_process'})],
                             listener.unstack_info.call_args_list)
            listener.authorization.assert_not_called()
            listener.unstack_info.reset_mock()
            # test authorization
            event = Mock(type='auth', data=('10.0.0.1', True))
            listener.on_remote_event(event)
            listener.unstack_event.assert_not_called()
            listener.unstack_info.assert_not_called()
            self.assertEqual([call(('10.0.0.1', True))],
                             listener.authorization.call_args_list)

    @patch('supvisors.listener.time.time', return_value=56)
    def test_force_process_state(self, mocked_time):
        """ Test the sending of a fake Supervisor process event. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # patch publisher
        listener.publisher = Mock(**{'send_process_event.return_value': None})
        # test the call
        listener.force_process_state('appli:process', 200)
        self.assertEqual([call({'processname': 'process', 'groupname': 'appli', 'state': 200,
                                'now': 56, 'pid': 0, 'expected': False})],
                         listener.publisher.send_process_event.call_args_list)

    def test_force_process_fatal(self):
        """ Test the sending of a fake FATAL Supervisor process event. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # add patch for what is tested just above
        with patch.object(listener, 'force_process_state') as mocked_force:
            listener.force_process_fatal('appli:process')
            self.assertEqual([call('appli:process', 200)], mocked_force.call_args_list)

    def test_force_process_unknown(self):
        """ Test the sending of a fake UNKNOWN Supervisor process event. """
        from supvisors.listener import SupervisorListener
        listener = SupervisorListener(self.supvisors)
        # add patch for what is tested just above
        with patch.object(listener, 'force_process_state') as mocked_force:
            listener.force_process_unknown('appli:process')
            self.assertEqual([call('appli:process', 1000)], mocked_force.call_args_list)

def test_suite():
    return unittest.findTestCases(sys.modules[__name__])

if __name__ == '__main__':
    unittest.main(defaultTest='test_suite')


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Invoicedetail = mongoose.model('Invoicedetail'),
	_ = require('lodash');

/**
 * Create a Invoicedetail
 */
exports.create = function(req, res) {
	var invoicedetail = new Invoicedetail(req.body);
	invoicedetail.user = req.user;

	invoicedetail.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(invoicedetail);
		}
	});
};

/**
 * Show the current Invoicedetail
 */
exports.read = function(req, res) {
	res.jsonp(req.invoicedetail);
};

/**
 * Update a Invoicedetail
 */
exports.update = function(req, res) {
	var invoicedetail = req.invoicedetail ;

	invoicedetail = _.extend(invoicedetail , req.body);

	invoicedetail.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(invoicedetail);
		}
	});
};

/**
 * Delete an Invoicedetail
 */
exports.delete = function(req, res) {
	var invoicedetail = req.invoicedetail ;

	invoicedetail.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(invoicedetail);
		}
	});
};

/**
 * List of Invoicedetails
 */
exports.list = function(req, res) {
	Invoicedetail.find().sort('-created').populate('user', 'displayName').exec(function(err, invoicedetails) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(invoicedetails);
		}
	});
};

/**
 * Invoicedetail middleware
 */
exports.invoicedetailByID = function(req, res, next, id) {
	Invoicedetail.findById(id).populate('user', 'displayName').exec(function(err, invoicedetail) {
		if (err) return next(err);
		if (! invoicedetail) return next(new Error('Failed to load Invoicedetail ' + id));
		req.invoicedetail = invoicedetail ;
		next();
	});
};

/**
 * Invoicedetail authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.invoicedetail.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};


text:
/**
 *
 */
package com.kancolle.server.model.po.common.handler.immutableList;

import com.google.common.collect.ImmutableList;

import java.util.function.Function;

/**
 * @author J.K.SAGE
 * @Date 2015年5月30日
 */
public class IntegerImmutableListHandler extends ImmutableListHandler<Integer> {

    @Override
    protected Function<String, ImmutableList<Integer>> toImmutableList() {
        return toImmutableListFunction.apply(Integer.class);
    }
}


text:
from contextlib import redirect_stdout
import io
from unittest import TestCase
from unittest.mock import patch

from todone.backend import SavedList
from todone.backend.db import Todo as TodoSQL
from todone.commands.move import move_todo, parse_args
from todone.tests.base import DB_Backend, FolderMock
from todone.parser import exceptions as pe

class TestMoveTodo(DB_Backend):

    def setUp(self):
        self.todos = []
        self.todos.append(TodoSQL.create(action='Todo 1', folder='inbox'))
        self.todos.append(TodoSQL.create(action='Todo 2', folder='inbox'))
        self.todos.append(TodoSQL.create(action='Todo 3', folder='next'))
        self.todos.append(TodoSQL.create(action='Todo 4', folder='today'))
        self.todos.append(TodoSQL.create(action='project', folder='today'))
        self.todos.append(TodoSQL.create(action='other', folder='next'))
        SavedList.save_most_recent_search(self.todos)

    def test_todo_moves_to_designated_folder(self):
        move_todo(['1', 'today/'])
        moved_todo = TodoSQL.get(TodoSQL.action == 'Todo 1')
        self.assertEqual(moved_todo.folder.name, 'today')

    def test_todo_moves_to_designated_project(self):
        move_todo(['1', '[project]'])
        moved_todo = TodoSQL.get(TodoSQL.action == 'Todo 1')
        self.assertEqual(moved_todo.parent.action, 'project')

    def test_todo_moves_from_one_to_another_project(self):
        move_todo(['1', '[today/project]'])
        move_todo(['1', '[next/other]'])
        moved_todo = TodoSQL.get(TodoSQL.action == 'Todo 1')
        self.assertEqual(moved_todo.parent.action, 'other')

    def test_changing_todo_project_preserves_folder(self):
        move_todo(['1', '[project]'])
        moved_todo = TodoSQL.get(TodoSQL.action == 'Todo 1')
        self.assertEqual(moved_todo.folder.name, 'inbox')

    def test_move_folder_prints_action_taken(self):
        f = io.StringIO()
        with redirect_stdout(f):
            move_todo(['3', 'done/'])
        s = f.getvalue()
        self.assertIn('Moved: Todo 3 -> {}'.format('done'), s)

    def test_move_project_prints_action_taken(self):
        f = io.StringIO()
        with redirect_stdout(f):
            move_todo(['3', '[today/project]'])
        s = f.getvalue()
        self.assertIn('Moved: Todo 3 -> [{}]'.format('project'), s)

    def test_invalid_index_displays_error_message(self):
        pass

@patch('todone.commands.move.backend.Folder', FolderMock)
class TestMoveArgParse(TestCase):

    def test_parses_integer(self):
        args = parse_args(['5', 'today/'])
        self.assertEqual(args['index'], 5)

    def test_negative_integer_does_not_match(self):
        with self.assertRaises(pe.ArgumentError):
            parse_args(['-5', 'today/'])

    def test_parses_folder(self):
        args = parse_args(['0', 'in/'])
        self.assertEqual(args['folder'], 'inbox')

    @patch('todone.parser.factory.backend.Todo')
    def test_parses_project_and_calls_get_project_todo(self, MockTodo):
        args = parse_args(['1', '[project]'])
        self.assertEqual(
            args['parent'], MockTodo.get_projects('project').__getitem__(0)
        )


text:
package com.zhiji.phonemall.data.db.model;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;
import org.greenrobot.greendao.annotation.Generated;

/**
 * <pre>
 *     author : llj
 *     time   : 2017/07/28
 *     desc   :
 * </pre>
 */
@Entity(nameInDb = "user")
public class User {

  @Id(autoincrement = true)
  private Long id;
  @Property(nameInDb = "name")
  private String name;
  @Property(nameInDb = "password")
  private String password;
  @Generated(hash = 1691991404)
  public User(Long id, String name, String password) {
      this.id = id;
      this.name = name;
      this.password = password;
  }
  @Generated(hash = 586692638)
  public User() {
  }
  public Long getId() {
      return this.id;
  }
  public void setId(Long id) {
      this.id = id;
  }
  public String getName() {
      return this.name;
  }
  public void setName(String name) {
      this.name = name;
  }
  public String getPassword() {
      return this.password;
  }
  public void setPassword(String password) {
      this.password = password;
  }
}


text:
'use strict';

/**
 * Is string
 */
module.exports = function isString(value) {
  if (typeof value !== 'string') {
    throw new Error('Expected string value');
  }
};


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

import org.w3c.dom.*;

import org.w3c.domts.DOMTestCase;
import org.w3c.domts.DOMTestDocumentBuilderFactory;

/**
 * An attempt to add remove an entity should result in a NO_MODIFICATION_ERR.
* @author Curt Arnold
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-1788794630
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-D58B193
*/
public final class hc_entitiesremovenameditem1 extends DOMTestCase {

   /**
    * Constructor.
    * @param factory document factory, may not be null
    * @throws org.w3c.domts.DOMTestIncompatibleException Thrown if test is not compatible with parser configuration
    */
   public hc_entitiesremovenameditem1(final DOMTestDocumentBuilderFactory factory)  throws org.w3c.domts.DOMTestIncompatibleException {
      super(factory);
      if (factory.hasFeature("XML", null) != true) {
         throw org.w3c.domts.DOMTestIncompatibleException.incompatibleFeature("XML", null);
      }

    //
    //   check if loaded documents are supported for content type
    //
    String contentType = getContentType();
    preload(contentType, "hc_staff", true);
    }

   /**
    * Runs the test case.
    * @throws Throwable Any uncaught exception causes test to fail
    */
   public void runTest() throws Throwable {
      Document doc;
      NamedNodeMap entities;
      DocumentType docType;
      Node retval;
      doc = (Document) load("hc_staff", true);
      docType = doc.getDoctype();

      if (
    !(("text/html".equals(getContentType())))
) {
          assertNotNull("docTypeNotNull", docType);
      entities = docType.getEntities();
      assertNotNull("entitiesNotNull", entities);

      {
         boolean success = false;
         try {
            retval = entities.removeNamedItem("alpha");
          } catch (DOMException ex) {
            success = (ex.code == DOMException.NO_MODIFICATION_ALLOWED_ERR);
         }
         assertTrue("throw_NO_MODIFICATION_ALLOWED_ERR", success);
      }
}
    }
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
   public String getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_entitiesremovenameditem1";
   }
   /**
    * Runs this test from the command line.
    * @param args command line arguments
    */
   public static void main(final String[] args) {
        DOMTestCase.doMain(hc_entitiesremovenameditem1.class, args);
   }
}


text:
namespace html
{
Attribute::Attribute(std::wstring attribute, const wchar_t *value):
	Attribute(attribute, std::wstring(value))
{
}

Attribute::Attribute(std::wstring attribute, std::wstring attrValue):
	attribute(std::move(attribute)),
	value(std::move(attrValue))
{}

Attribute::Attribute(std::wstring attribute, bool boolValue) :
	attribute(std::move(attribute)),
	value(boolValue ? L"true" : L"false")
{}
}


text:
package com.mmnaseri.utils.spring.data.domain.impl.id;

import com.mmnaseri.utils.spring.data.domain.IdPropertyResolver;
import com.mmnaseri.utils.spring.data.error.MultipleIdPropertiesException;
import com.mmnaseri.utils.spring.data.tools.GetterMethodFilter;
import org.springframework.data.annotation.Id;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicReference;

import static com.mmnaseri.utils.spring.data.domain.impl.id.IdPropertyResolverUtils.getPropertyNameFromAnnotatedMethod;
import static com.mmnaseri.utils.spring.data.domain.impl.id.IdPropertyResolverUtils.isAnnotated;

/**
 * This class will resolve ID property name from a getter method that is annotated with {@link
 * Id @Id}.
 *
 * @author Milad Naseri (m.m.naseri@gmail.com)
 * @since 1.0 (9/23/15)
 */
@SuppressWarnings("WeakerAccess")
public class AnnotatedGetterIdPropertyResolver implements IdPropertyResolver {

  @Override
  public String resolve(final Class<?> entityType, Class<?> idType) {
    final AtomicReference<Method> found = new AtomicReference<>();
    ReflectionUtils.doWithMethods(
        entityType,
        method -> {
          if (isAnnotated(method)) {
            if (found.get() == null) {
              found.set(method);
            } else {
              throw new MultipleIdPropertiesException(entityType);
            }
          }
        },
        new GetterMethodFilter());
    final Method idAnnotatedMethod = found.get();
    return getPropertyNameFromAnnotatedMethod(entityType, idType, idAnnotatedMethod);
  }
}


text:
define(function() {
  var ControlNavigation = function(module, vent, router, section) {
    this.vent = vent;
    this.router = router;
    this.section = section;
    this.isActive = false;

    this.initialize(module);
  };

  ControlNavigation.prototype.initialize = function(module) {
    var self = this;

    module.listenTo(this.router, 'route', function() {
      self.vent.trigger('section:activated', { name: self.section });
    });

    module.listenTo(this.vent, 'section:activated', function(params) {
      self.isActive = (params.name === self.section);
    });

    // Update groupBy param in URL when changed
    module.listenTo(this.vent, 'controls:groupby', function(groupBy) {
      if (self.isActive === true) {
        self.router.navigate(self.section + '/' + groupBy.name, {trigger: false});
      }
    });
  };

  return ControlNavigation;
});


text:
DROP TABLE IF EXISTS `job_recipe`;
DROP TABLE IF EXISTS `job_recipe_log`;

CREATE TABLE IF NOT EXISTS `job_recipe` (
    `id` INT UNSIGNED AUTO_INCREMENT,
    `recipe` TEXT NOT NULL,
    `created_at` DATETIME NOT NULL,
    `updated_at` DATETIME NOT NULL,
    PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `job_recipe_log` (
    `id` INT UNSIGNED AUTO_INCREMENT ,
    `job` VARCHAR(100) NOT NULL,
    `status` INT NOT NULL DEFAULT 0,
    `created_at` DATETIME NOT NULL,
    `updated_at` DATETIME NOT NULL,
    PRIMARY KEY (`id`)
);


text:
using System;
using System.Linq;

class SumIntegers
{
   static void Main()
   {
      //input
      string integers = Console.ReadLine();
      //output
      Console.WriteLine(Sum(integers));
   }

   public static int Sum(string integers)
   {
      int[] ints = integers.Split(' ').Select(int.Parse).ToArray();
      int sum = 0;

      foreach (var item in ints)
      {
         sum += item;
      }
      return sum;
   }
}


text:
from django.contrib import admin

from .models import Choice, Poll, ActualVote

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3

class PollAdmin(admin.ModelAdmin):
    inlines = [ChoiceInline]
    list_display = ('question', 'pub_date', 'was_published_recently', 'created_by')
    list_filter = ['pub_date']
    search_fields = ['question']
    date_hierarchy = 'pub_date'

admin.site.register(Poll, PollAdmin)
admin.site.register(Choice)
admin.site.register(ActualVote)


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'EconomicAgent.text_consumes'
        db.add_column('clusters_economicagent', 'text_consumes',
                      self.gf('django.db.models.fields.CharField')(max_length=512, null=True, blank=True),
                      keep_default=False)

        # Adding field 'EconomicAgent.text_produces'
        db.add_column('clusters_economicagent', 'text_produces',
                      self.gf('django.db.models.fields.CharField')(max_length=512, null=True, blank=True),
                      keep_default=False)

        # Adding field 'EconomicAgent.text_info_provided_by'
        db.add_column('clusters_economicagent', 'text_info_provided_by',
                      self.gf('django.db.models.fields.CharField')(max_length=128, null=True, blank=True),
                      keep_default=False)

        # Adding field 'EconomicAgent.text_contact'
        db.add_column('clusters_economicagent', 'text_contact',
                      self.gf('django.db.models.fields.CharField')(max_length=128, null=True, blank=True),
                      keep_default=False)

        # Adding field 'EconomicAgent.text_degree_of_separation'
        db.add_column('clusters_economicagent', 'text_degree_of_separation',
                      self.gf('django.db.models.fields.CharField')(max_length=128, null=True, blank=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'EconomicAgent.text_consumes'
        db.delete_column('clusters_economicagent', 'text_consumes')

        # Deleting field 'EconomicAgent.text_produces'
        db.delete_column('clusters_economicagent', 'text_produces')

        # Deleting field 'EconomicAgent.text_info_provided_by'
        db.delete_column('clusters_economicagent', 'text_info_provided_by')

        # Deleting field 'EconomicAgent.text_contact'
        db.delete_column('clusters_economicagent', 'text_contact')

        # Deleting field 'EconomicAgent.text_degree_of_separation'
        db.delete_column('clusters_economicagent', 'text_degree_of_separation')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'clusters.agentfunction': {
            'Meta': {'ordering': "('agent', 'function')", 'object_name': 'AgentFunction'},
            'agent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'functions'", 'to': "orm['clusters.EconomicAgent']"}),
            'function': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'agents'", 'to': "orm['clusters.EconomicFunction']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'clusters.agentfunctionresourcetype': {
            'Meta': {'ordering': "('agent_function', 'role', 'resource_type')", 'object_name': 'AgentFunctionResourceType'},
            'agent_function': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'function_resources'", 'to': "orm['clusters.AgentFunction']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'price': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '8', 'decimal_places': '2'}),
            'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'agent_functions'", 'to': "orm['clusters.EconomicResourceType']"}),
            'role': ('django.db.models.fields.CharField', [], {'max_length': '12'}),
            'value': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        'clusters.agentresourceflow': {
            'Meta': {'ordering': "('from_function', 'to_function', 'resource_type')", 'object_name': 'AgentResourceFlow'},
            'from_function': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'outgoing_flows'", 'to': "orm['clusters.AgentFunction']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'price': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '8', 'decimal_places': '2'}),
            'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'agent_flows'", 'to': "orm['clusters.EconomicResourceType']"}),
            'to_function': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'incoming_flows'", 'to': "orm['clusters.AgentFunction']"}),
            'value': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        'clusters.agentresourcetype': {
            'Meta': {'ordering': "('agent', 'role', 'resource_type')", 'object_name': 'AgentResourceType'},
            'agent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'resources'", 'to': "orm['clusters.EconomicAgent']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'price': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '8', 'decimal_places': '2'}),
            'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'agents'", 'to': "orm['clusters.EconomicResourceType']"}),
            'role': ('django.db.models.fields.CharField', [], {'max_length': '12'}),
            'value': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        'clusters.cluster': {
            'Meta': {'object_name': 'Cluster'},
            'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'changed_cluster'", 'null': 'True', 'to': "orm['auth.User']"}),
            'community': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'clusters'", 'to': "orm['clusters.Community']"}),
            'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'created_cluster'", 'null': 'True', 'to': "orm['auth.User']"}),
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'function_aspect_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'root_function': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'cluster_root'", 'null': 'True', 'to': "orm['clusters.EconomicFunction']"}),
            'root_resource': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'cluster_root'", 'null': 'True', 'to': "orm['clusters.EconomicResourceType']"}),
            'sharing': ('django.db.models.fields.CharField', [], {'default': "'private'", 'max_length': '12'}),
            'when_changed': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
            'when_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'})
        },
        'clusters.clusteragent': {
            'Meta': {'ordering': "('cluster', 'agent')", 'object_name': 'ClusterAgent'},
            'agent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'clusters'", 'to': "orm['clusters.EconomicAgent']"}),
            'cluster': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'cluster_agents'", 'to': "orm['clusters.Cluster']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'clusters.community': {
            'Meta': {'ordering': "('name',)", 'object_name': 'Community'},
            'agent_geographic_area_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
            'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'changed_community'", 'null': 'True', 'to': "orm['auth.User']"}),
            'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'created_community'", 'null': 'True', 'to': "orm['auth.User']"}),
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'latitude': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
            'longitude': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
            'map_center': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'map_zoom_level': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'resource_aspect_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
            'unit_of_value': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'community_units'", 'null': 'True', 'to': "orm['clusters.Unit']"}),
            'when_changed': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
            'when_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'})
        },
        'clusters.communityagent': {
            'Meta': {'ordering': "('community', 'agent')", 'object_name': 'CommunityAgent'},
            'agent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'communities'", 'to': "orm['clusters.EconomicAgent']"}),
            'community': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'agents'", 'to': "orm['clusters.Community']"}),
            'geographic_area': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'group': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'region_latitude': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
            'region_longitude': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'})
        },
        'clusters.communitymember': {
            'Meta': {'object_name': 'CommunityMember'},
            'community': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'members'", 'to': "orm['clusters.Community']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'member': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'communities'", 'to': "orm['auth.User']"}),
            'permission_role': ('django.db.models.fields.CharField', [], {'max_length': '12'})
        },
        'clusters.communityresourcetype': {
            'Meta': {'ordering': "('community', 'resource_type')", 'object_name': 'CommunityResourceType'},
            'aspect': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
            'community': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'resources'", 'to': "orm['clusters.Community']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'communities'", 'to': "orm['clusters.EconomicResourceType']"})
        },
        'clusters.economicagent': {
            'Meta': {'ordering': "('name',)", 'object_name': 'EconomicAgent'},
            'address': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'latitude': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
            'longitude': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
            'text_consumes': ('django.db.models.fields.CharField', [], {'max_length': '512', 'null': 'True', 'blank': 'True'}),
            'text_contact': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
            'text_degree_of_separation': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
            'text_info_provided_by': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
            'text_produces': ('django.db.models.fields.CharField', [], {'max_length': '512', 'null': 'True', 'blank': 'True'})
        },
        'clusters.economicfunction': {
            'Meta': {'ordering': "('cluster', 'name')", 'object_name': 'EconomicFunction'},
            'aspect': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
            'cluster': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'functions'", 'to': "orm['clusters.Cluster']"}),
            'color': ('django.db.models.fields.CharField', [], {'default': "'green'", 'max_length': '12'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'})
        },
        'clusters.economicresourcetype': {
            'Meta': {'ordering': "('name',)", 'object_name': 'EconomicResourceType'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['clusters.EconomicResourceType']"}),
            'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
            'unit_of_quantity': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'resource_units'", 'null': 'True', 'to': "orm['clusters.Unit']"})
        },
        'clusters.functionresourceflow': {
            'Meta': {'ordering': "('from_function', 'to_function', 'resource_type')", 'object_name': 'FunctionResourceFlow'},
            'from_function': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'outgoing_flows'", 'to': "orm['clusters.EconomicFunction']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'price': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '8', 'decimal_places': '2'}),
            'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'function_flows'", 'to': "orm['clusters.EconomicResourceType']"}),
            'to_function': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'incoming_flows'", 'to': "orm['clusters.EconomicFunction']"}),
            'value': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        'clusters.functionresourcetype': {
            'Meta': {'ordering': "('function', 'role', 'resource_type')", 'object_name': 'FunctionResourceType'},
            'function': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'resources'", 'to': "orm['clusters.EconomicFunction']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'price': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '8', 'decimal_places': '2'}),
            'quantity': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'functions'", 'to': "orm['clusters.EconomicResourceType']"}),
            'role': ('django.db.models.fields.CharField', [], {'max_length': '12'}),
            'value': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        },
        'clusters.sitesettings': {
            'Meta': {'object_name': 'SiteSettings'},
            'featured_cluster': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'featured'", 'to': "orm['clusters.Cluster']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'clusters.unit': {
            'Meta': {'object_name': 'Unit'},
            'abbrev': ('django.db.models.fields.CharField', [], {'max_length': '8'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
            'symbol': ('django.db.models.fields.CharField', [], {'max_length': '1', 'blank': 'True'}),
            'type': ('django.db.models.fields.CharField', [], {'max_length': '12'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        }
    }

    complete_apps = ['clusters']


text:
<?php
/**
 * Bootstraps the Elgg engine.
 *
 * This file loads the full Elgg engine, checks the installation
 * state, and triggers a series of events to finish booting Elgg:
 * 	- {@elgg_event boot system}
 * 	- {@elgg_event init system}
 * 	- {@elgg_event ready system}
 *
 * If Elgg is fully uninstalled, the browser will be redirected to an
 * installation page.
 *
 * @see install.php
 * @package Elgg.Core
 * @subpackage Core
 */

/**
 * The time with microseconds when the Elgg engine was started.
 *
 * @global float
 */
global $START_MICROTIME;
$START_MICROTIME = microtime(true);

/**
 * Configuration values.
 *
 * The $CONFIG global contains configuration values required
 * for running Elgg as defined in the settings.php file.
 *
 * Plugin authors are encouraged to use elgg_get_config() instead of accessing
 * the global directly.
 *
 * @see elgg_get_config()
 * @see engine/settings.php
 * @global stdClass $CONFIG
 */
global $CONFIG;
if (!isset($CONFIG)) {
	$CONFIG = new stdClass;
}
$CONFIG->boot_complete = false;

$engine_dir = dirname(__FILE__);

/*
 * No settings means a fresh install
 */
if (!include_once("$engine_dir/settings.php")) {
	header("Location: install.php");
	exit;
}

$lib_dir = "$engine_dir/lib";

require_once("$lib_dir/autoloader.php");
require_once("$lib_dir/elgglib.php");

// load the rest of the library files from engine/lib/
// All on separate lines to make diffs easy to read + make it apparent how much
// we're actually loading on every page (Hint: it's too much).
$lib_files = array(
	'access.php',
	'actions.php',
	'admin.php',
	'annotations.php',
	'cache.php',
	'comments.php',
	'configuration.php',
	'cron.php',
	'database.php',
	'entities.php',
	'extender.php',
	'filestore.php',
	'friends.php',
	'group.php',
	'input.php',
	'languages.php',
	'mb_wrapper.php',
	'memcache.php',
	'metadata.php',
	'metastrings.php',
	'navigation.php',
	'notification.php',
	'objects.php',
	'output.php',
	'pagehandler.php',
	'pageowner.php',
	'pam.php',
	'plugins.php',
	'private_settings.php',
	'relationships.php',
	'river.php',
	'sessions.php',
	'sites.php',
	'statistics.php',
	'system_log.php',
	'tags.php',
	'user_settings.php',
	'users.php',
	'upgrade.php',
	'views.php',
	'widgets.php',

	// backward compatibility
	'deprecated-1.7.php',
	'deprecated-1.8.php',
	'deprecated-1.9.php',
);

foreach ($lib_files as $file) {
	require_once("$lib_dir/$file");
}

// Connect to database, load language files, load configuration, init session
// Plugins can't use this event because they haven't been loaded yet.
elgg_trigger_event('boot', 'system');

// Load the plugins that are active
_elgg_load_plugins();

// @todo move loading plugins into a single boot function that replaces 'boot', 'system' event
// and then move this code in there.
// This validates the view type - first opportunity to do it is after plugins load.
$viewtype = elgg_get_viewtype();
if (!elgg_is_registered_viewtype($viewtype)) {
	elgg_set_viewtype('default');
}

// @todo deprecate as plugins can use 'init', 'system' event
elgg_trigger_event('plugins_boot', 'system');

// Complete the boot process for both engine and plugins
elgg_trigger_event('init', 'system');

$CONFIG->boot_complete = true;

// System loaded and ready
elgg_trigger_event('ready', 'system');


text:
import {Component} from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'card-demo',
  templateUrl: 'card-demo.html',
  styleUrls: ['card-demo.css'],
})
export class CardDemo {}


text:
package com.sensorberg.sdk;

public class SensorbergServiceMessage {

    public static final int MSG_APPLICATION_IN_FOREGROUND = 1;

    public static final int MSG_APPLICATION_IN_BACKGROUND = 2;

    public static final int MSG_SET_API_TOKEN = 3;

    public static final int MSG_PRESENT_ACTION = 4;

    public static final int MSG_SHUTDOWN = 6;

    public static final int MSG_PING = 7;

    public static final int MSG_BLUETOOTH = 8;

    public static final int MSG_SDK_SCANNER_MESSAGE = 9;

    public static final int MSG_UPLOAD_HISTORY = 10;

    public static final int MSG_BEACON_LAYOUT_UPDATE = 11;

    public static final int MSG_LOCATION_SERVICES_IS_SET = 13;

    public static final int MSG_SET_API_ADVERTISING_IDENTIFIER = 12;

    public static final int GENERIC_TYPE_BEACON_ACTION = 1001;

    public static final int MSG_REGISTER_PRESENTATION_DELEGATE = 100;

    public static final int MSG_UNREGISTER_PRESENTATION_DELEGATE = 101;

    public static final int MSG_SETTINGS_UPDATE = 102;

    public static final int MSG_TYPE_DISABLE_LOGGING = 103;

    public static final int MSG_TYPE_ENABLE_LOGGING = 104;

    public static final int MSG_LOCATION_NOT_SET_WHEN_NEEDED = 106;

    public static final int MSG_LOCATION_SET = 107;

    public static final int MSG_CONVERSION = 200;

    public static final int MSG_ATTRIBUTES = 300;

    public static final int MSG_GEOFENCE_EVENT = 400;

    public static final int MSG_GEOFENCE_NOT_AVAILABLE = 401;

    public static final int MSG_LOCATION_UPDATED = 600;

    public static final int MSG_LOCATION_ENABLED = 601;

    public static final String MSG_SET_API_TOKEN_TOKEN = "com.sensorberg.android.sdk.message.setApiToken.apiTokenString";

    public static final String MSG_PRESENT_ACTION_BEACONEVENT = "com.sensorberg.android.sdk.message.presentBeaconEvent.beaconEvent";

    public static final String MSG_SET_API_ADVERTISING_IDENTIFIER_ADVERTISING_IDENTIFIER
            = "com.sensorberg.android.sdk.message.setAdvertisingIdentifier.advertisingIdentifier";

    public static final String SERVICE_CONFIGURATION = "serviceConfiguration";

    public static final String EXTRA_API_KEY = "com.sensorberg.android.sdk.intent.apiKey";

    public static final String EXTRA_BLUETOOTH_STATE = "com.sensorberg.android.sdk.intent.bluetoothState";

    public static final String EXTRA_GENERIC_WHAT = "com.sensorberg.android.sdk.intent.generic.what";

    public static final String EXTRA_GENERIC_TYPE = "com.sensorberg.android.sdk.intent.generic.type";

    public static final String EXTRA_GENERIC_INDEX = "com.sensorberg.android.sdk.intent.generic.index";

    public static final String EXTRA_START_SERVICE = "com.sensorberg.android.sdk.intent.startService";

    public static final String EXTRA_MESSENGER = "com.sensorberg.android.sdk.intent.messenger";

    public static final String EXTRA_LOCATION_PERMISSION = "com.sensorberg.android.sdk.intent.permissionState";

    public static final String EXTRA_CONVERSION = "com.sensorberg.android.sdk.intent.conversion";

    public static final String EXTRA_ATTRIBUTES = "com.sensorberg.android.sdk.intent.attributes";

    public static final String EXTRA_LOCATION = "com.sensorberg.android.sdk.intent.geofence.location";

    public static final String EXTRA_LOCATION_AVAILABILITY = "com.sensorberg.android.sdk.intent.geofence.location.availability";

    public static final String EXTRA_GEOFENCE_DATA = "com.sensorberg.android.sdk.intent.geofence.data";

    public static final String EXTRA_GEOFENCE_ENTRY = "com.sensorberg.android.sdk.intent.geofence.entry";

    private SensorbergServiceMessage() {
        throw new IllegalAccessError("Utility class");
    }

    @SuppressWarnings({"squid:S1142", "squid:MethodCyclomaticComplexity"})
    public static String stringFrom(int what) {
        switch (what) {
            case MSG_APPLICATION_IN_FOREGROUND:
                return "MSG_APPLICATION_IN_FOREGROUND";
            case MSG_APPLICATION_IN_BACKGROUND:
                return "MSG_APPLICATION_IN_BACKGROUND";
            case MSG_SET_API_TOKEN:
                return "MSG_SET_API_TOKEN";
            case MSG_PRESENT_ACTION:
                return "MSG_PRESENT_ACTION";
            case MSG_REGISTER_PRESENTATION_DELEGATE:
                return "MSG_REGISTER_PRESENTATION_DELEGATE";
            case MSG_UNREGISTER_PRESENTATION_DELEGATE:
                return "MSG_UNREGISTER_PRESENTATION_DELEGATE";
            case MSG_SHUTDOWN:
                return "MSG_SHUTDOWN";
            case MSG_PING:
                return "MSG_PING";
            case MSG_BLUETOOTH:
                return "MSG_BLUETOOTH";
            case MSG_SETTINGS_UPDATE:
                return "MSG_SETTINGS_UPDATE";
            case GENERIC_TYPE_BEACON_ACTION:
                return "GENERIC_TYPE_BEACON_ACTION";
            case MSG_TYPE_DISABLE_LOGGING:
                return "MSG_TYPE_DISABLE_LOGGING";
            case MSG_TYPE_ENABLE_LOGGING:
                return "MSG_TYPE_ENABLE_LOGGING";
            case MSG_SDK_SCANNER_MESSAGE:
                return "MSG_SDK_SCANNER_MESSAGE";
            case MSG_UPLOAD_HISTORY:
                return "MSG_UPLOAD_HISTORY";
            case MSG_BEACON_LAYOUT_UPDATE:
                return "MSG_BEACON_LAYOUT_UPDATE";
            case MSG_SET_API_ADVERTISING_IDENTIFIER:
                return "MSG_SET_API_ADVERTISING_IDENTIFIER";
            case MSG_LOCATION_SERVICES_IS_SET:
                return "MSG_LOCATION_SERVICES_IS_SET";
            case MSG_CONVERSION:
                return "MSG_CONVERSION";
            case MSG_ATTRIBUTES:
                return "MSG_ATTRIBUTES";
            case MSG_GEOFENCE_EVENT:
                return "MSG_GEOFENCE_EVENT";
            case MSG_GEOFENCE_NOT_AVAILABLE:
                return "MSG_GEOFENCE_NOT_AVAILABLE";
            case MSG_LOCATION_UPDATED:
                return "MSG_LOCATION_UPDATED";
            case MSG_LOCATION_ENABLED:
                return "MSG_LOCATION_ENABLED";
            default:
                return "unknown message" + what;
        }
    }
}


text:
.PHONY: all clean

FSTAR_HOME?=../../..
ROOTS=$(wildcard *.fst) #scan these files for dependences
OUTPUT_DIR=output
MAIN=Main.fst #this is the main entry point file of your project
EXECUTABLE=$(subst .fst,.exe, $(MAIN))
INCLUDE_PATHS=

ifeq ($(OS),Windows_NT)
  FSTAR_EXE := $(shell cygpath -m $(FSTAR_HOME)/bin/fstar.exe)
else
  FSTAR_EXE := $(FSTAR_HOME)/bin/fstar.exe
endif

#cache_dir: where to find checked files
#odir: where to put all output artifacts
#include: where to find source and checked files
#already_cached: fstarlib is already built

FSTAR=$(FSTAR_EXE) \
	--cache_dir $(OUTPUT_DIR) \
	--odir $(OUTPUT_DIR) \
	$(addprefix --include , $(INCLUDE_PATHS) $(OUTPUT_DIR)) \
	--already_cached 'Prims FStar'

all: $(EXECUTABLE)

# generate a dependency graph
.depend: $(wildcard *.fst *.fsti)
	$(FSTAR) --dep full $(ROOTS) --extract '* -Prims -FStar' > .depend

# this defines the $(ALL_ML_FILES) variable and dependences to produce them
include .depend

# call the makefile in output after extracting all ml files
$(OUTPUT_DIR)/$(EXECUTABLE): $(ALL_ML_FILES)
	$(MAKE) -C output $(EXECUTABLE)

# recipe to verify a file and produce its .checked file
$(OUTPUT_DIR)/%.checked:
	$(FSTAR) $< --cache_checked_modules

# recipe to extract a .ml from a .checked file
$(OUTPUT_DIR)/%.ml:
	$(FSTAR) $(notdir $(subst .checked,,$<)) --codegen OCaml --extract_module $(basename $(notdir $(subst .checked,,$<)))

clean:
	rm $(OUTPUT_DIR)/*.checked $(OUTPUT_DIR)/*.ml .depend
	$(MAKE) -C $(OUTPUT_DIR) clean


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
require 'background_queue'

describe "Client" do

  context "initializing" do
    it "loads from config path" do
      BackgroundQueue::ClientLib::Config.stub(:load_file).with(:path_that_exists) { BackgroundQueue::ClientLib::Config.new(:a, :b, :c) }
      bq_client = BackgroundQueue::Client.new(:path_that_exists)
      bq_client.config.server.should eq(:a)
    end
  end

  context "initialized" do
    subject {
      BackgroundQueue::ClientLib::Config.stub(:load_file).with(:path_that_exists) {
        BackgroundQueue::ClientLib::Config.new(:primary_server, [:failover_1, :failover_2], :memcache_server)
      }
      BackgroundQueue::Client.new(:path_that_exists)
    }

    context "sending a command" do
      it "can send a command to a server" do
        BackgroundQueue::ClientLib::Connection.any_instance.should_receive(:send_command).with(:command) { true }
        subject.__prv__send_command_to_server(:command, :primary_server).should eq([true, :primary_server])
      end

      it "can succeed first time" do
        subject.should_receive(:send_command_to_server).with(:command, :primary_server) { true }
        subject.__prv__send_command(:command).should eq(true)
      end

      it "can use failover server if main server fails" do
        subject.should_receive(:send_command_to_server).with(:command, :primary_server) { raise BackgroundQueue::ClientLib::ConnectionError, "Primary" }
        subject.should_receive(:send_command_to_server).with(:command, :failover_1) { true }
        subject.__prv__send_command(:command).should eq(true)
      end

      it "can use second failover server if needed" do
        subject.should_receive(:send_command_to_server).with(:command, :primary_server) { raise BackgroundQueue::ClientLib::ConnectionError, "Primary" }
        subject.should_receive(:send_command_to_server).with(:command, :failover_1) { raise BackgroundQueue::ClientLib::ConnectionError, "Failure 1" }
        subject.should_receive(:send_command_to_server).with(:command, :failover_2) { true }
        subject.__prv__send_command(:command).should eq(true)
      end

      it "throws an exception if all connections fail" do
        subject.should_receive(:send_command_to_server).with(:command, :primary_server) { raise BackgroundQueue::ClientLib::ConnectionError, "Primary" }
        subject.should_receive(:send_command_to_server).with(:command, :failover_1) { raise BackgroundQueue::ClientLib::ConnectionError, "Failure 1" }
        subject.should_receive(:send_command_to_server).with(:command, :failover_2) { raise BackgroundQueue::ClientLib::ConnectionError, "Failure 2" }
        expect { subject.__prv__send_command(:command) }.to raise_error(BackgroundQueue::ClientException, "Primary, Attempt 2: Failure 1, Attempt 3: Failure 2")
      end
    end

    context "single call commands" do
      before do
        subject.should_receive(:send_command).with(any_args) { [true, :server] }
      end

      context "#add_task" do
        it "can build and send an add task command" do
          job_handle = subject.add_task(:worker, :owner_id, :job_id, :task_id, 1, {}, {} )
          job_handle.owner_id.should eq(:owner_id)
          job_handle.job_id.should eq(:job_id)
          job_handle.server.should eq(:server)
        end

        it "will dynamically generate a job id/task id if not passed" do
          subject.should_receive(:generate_ids).and_return([:jjj, :ttt])
          job_handle = subject.add_task(:worker, :owner_id, nil, nil, 1, {}, {} )
          job_handle.job_id.should eq(:jjj)
        end
      end

      it "can build and send an add tasks command" do
        job_handle = subject.add_tasks(:worker, :owner_id, :job_id, :tasks, 1, {}, {} )
        job_handle.job_id.should eq(:job_id)
      end

      #it "can build and send a remove task command" do
      #  subject.remove_tasks(:tasks, {}).should eq(true)
      #end

    end

    context "#get_status" do
      it "passes the requested server" do
        job_handle = double("jh", :server=>:another_server, :job_id=>:job_id)
        BackgroundQueue::ClientLib::Command.should_receive(:get_status_command).with(:job_id, {} ).and_return(:cmd)
        subject.should_receive(:send_command).with(:cmd, :another_server) { [true, :another_server] }
        subject.get_status(job_handle, {}).should eq(true)
      end
    end
  end
end


text:
layout: post
title: From Word Embeddings To Document Distances
subtitle: Title of paper - From Word Embeddings To Document Distances
category: NLP papers - Metrics
tags: [metrics, distance]
permalink: /2020/04/02/From_Word_Embedding_To_Document_Distances/
css : /css/ForYouTubeByHyun.css
bigimg:
  - "/img/Image/BigImages/carmel.jpg" : "Carmel-by-the-Sea, CA (2016)"
  - "/img/Image/BigImages/monterey.jpg" : "Monterey, CA (2016)"
  - "/img/Image/BigImages/stanford_dish.jpg" : "Stanford Dish, CA (2016)"
  - "/img/Image/BigImages/marian_beach_in_sanfran.jpg" : "MRINA of San Francisco, CA (2016)"
  - "/img/Image/BigImages/carmel2.jpg" : "Carmel-by-the-Sea, CA (2016)"
  - "/img/Image/BigImages/marina.jpg" : "MRINA of San Francisco, CA (2016)"
  - "/img/Image/BigImages/sanfrancisco.jpg" : "San Francisco, CA (2016)"

---

This is a brief summary of paper for me to study and organize it, [From word embeddings to document distances (Kusner et al., ICML 2015)](https://dl.acm.org/doi/10.5555/3045118.3045221) I read and studied.
{% include MathJax.html %}

WMD use word embeddings to calculate the distance so that it can calculate even though there is no common word. The assumption is that similar words should have similar vectors.

![Captured from Kusner et al. publication](/img/Image/NaturalLanguageProcessing/NLPLabs/Paper_Investigation/Metrics/2020-04-02-From_Word_Embedding_To_Document_Distances/Dist1.PNG)

First of all, lower case and removing stopwords is an essential step to reduce complexity and preventing misleading.

> Sentence 1: obama speaks media illinois
> Sentence 2: president greets press chicago

Retrieve vectors from any pre-trained word embeddings models. It can be GloVe, word2vec, fasttext or custom vectors. After that it using normalized bag-of-words (nBOW) to represent the weight or importance. It assumes that higher frequency implies that it is more important.

![Captured from Kusner et al. publication](/img/Image/NaturalLanguageProcessing/NLPLabs/Paper_Investigation/Metrics/2020-04-02-From_Word_Embedding_To_Document_Distances/Dist2.PNG)

Strengths of WMD:

  - Hyperparameter-free
  - Straight-forward to understand and use, highly interpretable
  - leads to unprecedented low k-nearest neighbor document classification error rates

 Note(Abstract):
They present the Word Mover's Distance (WMD), a novel distance function between text documents. Their work is based on recent results in word embeddings that learn semantically meaningful representations for words from local cooccurrences in sentences. The WMD distance
measures the dissimilarity between two text documents as the minimum amount of distance that the embedded words of one document need to
"travel" to reach the embedded words of another document.

 Download URL:

  The paper: From word embeddings to document distances (Kusner et al., ICML 2015)

# Reference

- Paper
  - [ICML Version: From word embeddings to document distances (Kusner et al., ICML 2015)](https://dl.acm.org/doi/10.5555/3045118.3045221)

- How to use html for alert
  - [how to use icon](http://idratherbewriting.com/documentation-theme-jekyll/mydoc_icons.html)

- References
  - [Word Embedding to Document distances at slideshare](https://www.slideshare.net/GaneshBorle/word-embedding-to-document-distances)
  - [From Word Embeddings To Document Distances pdf](https://stat.snu.ac.kr/idea/seminar/20180426/RNN_tex.pdf)
  - [Earth mover's distance on towards data science](https://towardsdatascience.com/earth-movers-distance-68fff0363ef2)
  - [Paper: The Earth Mover's Distance as a Metric for Image Retrieval. Rubner et al. 2000 in International journal of computer vision](http://robotics.stanford.edu/~rubner/papers/rubnerIjcv00.pdf)
  - [The Earth Mover's Distance as a Metric for Image Retrieval. Rubner et al. 2000](https://www.cs.cmu.edu/~efros/courses/LBMV07/Papers/rubner-jcviu-00.pdf)
  - [The Earth Mover's Distance](http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/RUBNER/emd.htm)
  - [Finding similar documents with Word2Vec and WMD](https://markroxor.github.io/gensim/static/notebooks/WMD_tutorial.html)
  - [Navigating themes in restaurant reviews with Word Mover's Distance](http://tech.opentable.com/2015/08/11/navigating-themes-in-restaurant-reviews-with-word-movers-distance/)
  - [A Word is Worth a Thousand Vectors](https://multithreaded.stitchfix.com/blog/2015/03/11/word-is-worth-a-thousand-vectors/)
  - [Word Distance between Word Embeddings on towards data science](https://towardsdatascience.com/word-distance-between-word-embeddings-cc3e9cf1d632)
  - [Word Mover's Distance as a Linear Programming Problem on Medium](https://medium.com/@stephenhky/word-movers-distance-as-a-linear-programming-problem-6b0c2658592e)


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28916_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans630.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">13


text:
package org.elasticsearch.cluster.routing.allocation.decider;

import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.ShardRoutingState;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.settings.NodeSettingsService;

/**
 * {@link ThrottlingAllocationDecider} controls the recovery process per node in
 * the cluster. It exposes two settings via the cluster update API that allow
 * changes in real-time:
 *

 *
<tt>cluster.routing.allocation.node_initial_primaries_recoveries</tt> -
 * restricts the number of initial primary shard recovery operations on a single
 * node. The default is <tt>4</tt>

 *
<tt>cluster.routing.allocation.node_concurrent_recoveries</tt> -
 * restricts the number of total concurrent shards initializing on a single node. The
 * default is <tt>2</tt>

 *

 *

 * If one of the above thresholds is exceeded per node this allocation decider
 * will return {@link Decision#THROTTLE} as a hit to upstream logic to throttle
 * the allocation process to prevent overloading nodes due to too many concurrent recovery
 * processes.
 *
 * TODO 这个类用于recovery过程中,控制节点在恢复过程。
 * 如果上面的阀值有一个被超过了,该allocation decider会返回THROTTLE,用以限制allocate的过程,以阻止太多的recovery导致node过载;
 */
public class ThrottlingAllocationDecider extends AllocationDecider {

    public static final String NAME = "throttling";

    // TODO recovery时同一个节点上允许同时恢复几个主分片,默认4个
    public static final String CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES = "cluster.routing.allocation.node_initial_primaries_recoveries";
    // TODO 限制在同一个node上,除了主分片重启恢复以外其他shard做recovery的并发数,默认是 2 个
    public static final String CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES = "cluster.routing.allocation.node_concurrent_recoveries";
    // TODO
    public static final String CLUSTER_ROUTING_ALLOCATION_CONCURRENT_RECOVERIES = "cluster.routing.allocation.concurrent_recoveries";

    public static final int DEFAULT_CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES = 2;
    public static final int DEFAULT_CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES = 4;

    private volatile int primariesInitialRecoveries;
    private volatile int concurrentRecoveries;

    @Inject
    public ThrottlingAllocationDecider(Settings settings, NodeSettingsService nodeSettingsService) {
        super(settings);

        this.primariesInitialRecoveries = settings.getAsInt(CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES, DEFAULT_CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES);
        this.concurrentRecoveries = settings.getAsInt(CLUSTER_ROUTING_ALLOCATION_CONCURRENT_RECOVERIES, settings.getAsInt(CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES, DEFAULT_CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES));
        logger.debug("using node_concurrent_recoveries [{}], node_initial_primaries_recoveries [{}]", concurrentRecoveries, primariesInitialRecoveries);

        nodeSettingsService.addListener(new ApplySettings());
    }

    @Override
    public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
        if (shardRouting.primary()) {
            assert shardRouting.unassigned() || shardRouting.active();
            if (shardRouting.unassigned()) {
                // primary is unassigned, means we are going to do recovery from gateway
                // count *just the primary* currently doing recovery on the node and check against concurrent_recoveries
                int primariesInRecovery = 0;
                for (ShardRouting shard : node) {
                    // when a primary shard is INITIALIZING, it can be because of *initial recovery* or *relocation from another node*
                    // we only count initial recoveries here, so we need to make sure that relocating node is null
                    if (shard.initializing() && shard.primary() && shard.relocatingNodeId() == null) {
                        primariesInRecovery++;
                    }
                }
                if (primariesInRecovery >= primariesInitialRecoveries) {
                    return allocation.decision(Decision.THROTTLE, NAME, "too many primaries currently recovering [%d], limit: [%d]",
                            primariesInRecovery, primariesInitialRecoveries);
                } else {
                    return allocation.decision(Decision.YES, NAME, "below primary recovery limit of [%d]", primariesInitialRecoveries);
                }
            }
        }

        // either primary or replica doing recovery (from peer shard)

        // count the number of recoveries on the node, its for both target (INITIALIZING) and source (RELOCATING)
        return canAllocate(node, allocation);
    }

    @Override
    public Decision canAllocate(RoutingNode node, RoutingAllocation allocation) {
        int currentRecoveries = 0;
        for (ShardRouting shard : node) {
            if (shard.initializing()) {
                currentRecoveries++;
            }
        }
        if (currentRecoveries >= concurrentRecoveries) {
            return allocation.decision(Decision.THROTTLE, NAME, "too many shards currently recovering [%d], limit: [%d]",
                    currentRecoveries, concurrentRecoveries);
        } else {
            return allocation.decision(Decision.YES, NAME, "below shard recovery limit of [%d]", concurrentRecoveries);
        }
    }

    class ApplySettings implements NodeSettingsService.Listener {
        @Override
        public void onRefreshSettings(Settings settings) {
            int primariesInitialRecoveries = settings.getAsInt(CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES, ThrottlingAllocationDecider.this.primariesInitialRecoveries);
            if (primariesInitialRecoveries != ThrottlingAllocationDecider.this.primariesInitialRecoveries) {
                logger.info("updating [cluster.routing.allocation.node_initial_primaries_recoveries] from [{}] to [{}]", ThrottlingAllocationDecider.this.primariesInitialRecoveries, primariesInitialRecoveries);
                ThrottlingAllocationDecider.this.primariesInitialRecoveries = primariesInitialRecoveries;
            }

            int concurrentRecoveries = settings.getAsInt(CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES, ThrottlingAllocationDecider.this.concurrentRecoveries);
            if (concurrentRecoveries != ThrottlingAllocationDecider.this.concurrentRecoveries) {
                logger.info("updating [cluster.routing.allocation.node_concurrent_recoveries] from [{}] to [{}]", ThrottlingAllocationDecider.this.concurrentRecoveries, concurrentRecoveries);
                ThrottlingAllocationDecider.this.concurrentRecoveries = concurrentRecoveries;
            }
        }
    }
}


text:
use crate::metrics::{PRUNER_BATCH_SIZE, PRUNER_WINDOW};

use aptos_config::config::StateMerklePrunerConfig;
use aptos_infallible::Mutex;

use crate::pruner::pruner_manager::PrunerManager;
use aptos_jellyfish_merkle::StaleNodeIndex;
use aptos_types::transaction::Version;
use schemadb::schema::KeyCodec;
use schemadb::DB;
use std::{sync::Arc, thread::JoinHandle};

use crate::pruner::db_pruner::DBPruner;
use crate::pruner::state_pruner_worker::StatePrunerWorker;
use crate::pruner::state_store::generics::StaleNodeIndexSchemaTrait;
use crate::pruner::state_store::StateMerklePruner;
use crate::pruner_utils;

/// The `Pruner` is meant to be part of a `AptosDB` instance and runs in the background to prune old
/// data.
///
/// If the state pruner is enabled, it creates a worker thread on construction and joins it on
/// destruction. When destructed, it quits the worker thread eagerly without waiting for all
/// pending work to be done.
#[derive(Debug)]
pub struct StatePrunerManager<S: StaleNodeIndexSchemaTrait>
where
    StaleNodeIndex: KeyCodec<S>,
{
    pruner_enabled: bool,
    /// DB version window, which dictates how many versions of state store
    /// to keep.
    prune_window: Version,
    /// State pruner. Is always initialized regardless if the pruner is enabled to keep tracks
    /// of the min_readable_version.
    pruner: Arc<StateMerklePruner<S>>,
    /// Wrapper class of the state pruner.
    pub(crate) pruner_worker: Arc<StatePrunerWorker<S>>,
    /// The worker thread handle for state_pruner, created upon Pruner instance construction and
    /// joined upon its destruction. It is `None` when state pruner is not enabled or it only
    /// becomes `None` after joined in `drop()`.
    worker_thread: Option<JoinHandle<()>>,
    /// We send a batch of version to the underlying pruners for performance reason. This tracks the
    /// last version we sent to the pruner. Will only be set if the pruner is enabled.
    last_version_sent_to_pruner: Arc<Mutex<Version>>,
    /// latest version
    latest_version: Arc<Mutex<Version>>,
}

impl<S: StaleNodeIndexSchemaTrait> PrunerManager for StatePrunerManager<S>
where
    StaleNodeIndex: KeyCodec<S>,
{
    type Pruner = StateMerklePruner<S>;

    fn pruner(&self) -> &Self::Pruner {
        &self.pruner
    }

    fn is_pruner_enabled(&self) -> bool {
        self.pruner_enabled
    }

    fn get_prune_window(&self) -> Version {
        self.prune_window
    }

    fn get_min_readable_version(&self) -> Version {
        self.pruner.as_ref().min_readable_version()
    }

    fn get_min_viable_version(&self) -> Version {
        unimplemented!()
    }

    /// Sets pruner target version when necessary.
    fn maybe_set_pruner_target_db_version(&self, latest_version: Version) {
        *self.latest_version.lock() = latest_version;

        // Always wake up the state pruner.
        if self.pruner_enabled {
            self.set_pruner_target_db_version(latest_version);
            *self.last_version_sent_to_pruner.as_ref().lock() = latest_version;
        }
    }

    fn set_pruner_target_db_version(&self, latest_version: Version) {
        assert!(self.pruner_enabled);
        self.pruner_worker
            .as_ref()
            .set_target_db_version(latest_version.saturating_sub(self.prune_window));
    }
}

impl<S: StaleNodeIndexSchemaTrait> StatePrunerManager<S>
where
    StaleNodeIndex: KeyCodec<S>,
{
    /// Creates a worker thread that waits on a channel for pruning commands.
    pub fn new(state_merkle_rocksdb: Arc<DB>, config: StateMerklePrunerConfig) -> Self {
        let state_db_clone = Arc::clone(&state_merkle_rocksdb);
        let pruner = pruner_utils::create_state_pruner(state_db_clone);

        if config.enable {
            PRUNER_WINDOW
                .with_label_values(&[S::name()])
                .set(config.prune_window as i64);

            PRUNER_BATCH_SIZE
                .with_label_values(&[S::name()])
                .set(config.batch_size as i64);
        }

        let pruner_worker = Arc::new(StatePrunerWorker::new(Arc::clone(&pruner), config));
        let state_pruner_worker_clone = Arc::clone(&pruner_worker);

        let worker_thread = if config.enable {
            Some(
                std::thread::Builder::new()
                    .name("aptosdb_state_pruner".into())
                    .spawn(move || state_pruner_worker_clone.as_ref().work())
                    .expect("Creating state pruner thread should succeed."),
            )
        } else {
            None
        };

        let min_readable_version = pruner.as_ref().min_readable_version();
        Self {
            pruner_enabled: config.enable,
            prune_window: config.prune_window,
            pruner,
            pruner_worker,
            worker_thread,
            last_version_sent_to_pruner: Arc::new(Mutex::new(min_readable_version)),
            latest_version: Arc::new(Mutex::new(min_readable_version)),
        }
    }

    #[cfg(test)]
    pub fn testonly_update_min_version(&self, version: Version) {
        self.pruner.testonly_update_min_version(version);
    }
}

impl<S: StaleNodeIndexSchemaTrait> Drop for StatePrunerManager<S>
where
    StaleNodeIndex: KeyCodec<S>,
{
    fn drop(&mut self) {
        if self.pruner_enabled {
            self.pruner_worker.stop_pruning();
            assert!(self.worker_thread.is_some());
            self.worker_thread
                .take()
                .expect("Ledger pruner worker thread must exist.")
                .join()
                .expect("Ledger pruner worker thread should join peacefully.");
        }
    }
}


text:
@media screen and (min-width: 768px) {
    .animated-element { position: relative; opacity: 0.01; }
    .animated-element.from-left { left: -500px; }
    .animated-element.from-right { right: -500px; }
    .animated-element.from-top { top: -500px; }
    .animated-element.from-bottom { bottom: -500px; }
    .animated-element.lift { bottom: -100px; }
    .animated-element.drop { top: -100px; }
}


text:
package com.android.mediaframeworktest.unit;

import android.media.MediaRecorder;

/**
 * All MediaRecorder method unit test subclass must implement this interface.
 */
interface MediaRecorderMethodUnderTest {
    public void checkStateErrors(MediaRecorderStateErrors stateErrors);
    public void invokeMethodUnderTest(MediaRecorder player);
}


text:
package io.github.kongeor.mocking.anonymous.model;

public class Worm {

	private String name;
	private int kills;
	private int xp;
	private boolean alive;

	public Worm(String name, int kills, int xp, boolean alive) {
		this.name = name;
		this.kills = kills;
		this.xp = xp;
		this.alive = alive;
	}

	public String getName() {
		return name;
	}

	public boolean isHero() {
		return !alive &&
				(kills >= 10 ||
				xp > 1000);
	}

	@Override
	public String toString() {
		return name + "(" + (alive ? "\u263A" : "\u271D") + ")" +
				" [" + xp + "] {" + kills + "\u2620}";
	}
}


text:
package com.devopsjavaspring.test.integration;

import com.devopsjavaspring.backend.persistence.domain.backend.Role;
import com.devopsjavaspring.backend.persistence.domain.backend.User;
import com.devopsjavaspring.backend.persistence.domain.backend.UserRole;
import com.devopsjavaspring.backend.service.UserService;
import com.devopsjavaspring.enums.PlansEnum;
import com.devopsjavaspring.enums.RolesEnum;
import com.devopsjavaspring.utils.UserUtils;
import org.junit.rules.TestName;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by stephenasamoah on 9/12/16.
 */
public class AbstractServiceIntegrationTest {
    @Autowired
    protected UserService userService;

    protected User createUser(TestName testName) {
        String username = testName.getMethodName();
        String email = testName.getMethodName() + "@gmail.com";

        Set<UserRole> userRoles = new HashSet<>();

        User basicUser = UserUtils.createBasicUser(username, email);
        userRoles.add(new UserRole(basicUser, new Role(RolesEnum.BASIC)));

        return userService.createUser(basicUser, PlansEnum.BASIC, userRoles);
    }
}


text:
"""Baseline captioning model with MLE objective."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from compare_gan.tpu import tpu_summaries
from bert import optimization
from language.capwap.utils import checkpoint_utils
from language.capwap.utils import tensor_utils
from language.capwap.utils import transformer_utils
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1 import estimator as tf_estimator

def model_fn(features, labels, mode, params, vocab):
  """Model function that satisfies the Estimator API.

  Args:
    features: Dictionary of model input tensors.
    labels: Ununsed.
    mode: A tf.estimator.ModeKeys value.
    params: Dictionary of model parameters.
    vocab: A utils.text_utils.Vocab instance.

  Returns:
    spec: A tf.estimator.TPUEstimatorSpec.
  """
  del labels

  # ----------------------------------------------------------------------------
  # INITIALIZATION.
  # ----------------------------------------------------------------------------

  model = transformer_utils.TransformerModel(
      config=transformer_utils.TransformerConfig.from_dict(params),
      is_training=(mode == tf_estimator.ModeKeys.TRAIN))

  # image_features: [batch_size, num_regions, feature_size]
  # image_positions: [batch_size, num_regions]
  # image_mask: [batch_size, num_regions]
  image_features = features["object_features"].features
  image_positions = features["object_features"].positions
  image_mask = features["object_features"].mask

  # Expand mask by 1 to account for the leading [IMG] token.
  # [batch_size, num_regions + 1]
  batch_size = tensor_utils.shape(image_mask, 0)
  input_mask = tf.pad(image_mask, [[0, 0], [1, 0]], constant_values=1)

  # Encode the image and store the cached transformer values.
  # [batch_size, num_regions + 1, num_layers, num_heads, head_size]
  _, input_cache = model.compute_image_transformer(
      input_ids=tf.fill([batch_size, 1], vocab.t2i(vocab.IMG)),
      input_image=image_features,
      input_image_mask=input_mask,
      input_positions=image_positions)

  if params.get("conditional_decoding"):
    # Add additional (text) conditioning information to the input cache.
    # The conditioning information gets to see the image information.
    # The new input consists of both the image and the extra encoded text.
    # This is used for the LEARN function of Alg. 1 in the paper.

    # [batch_size, num_regions + condition_length + 1]
    input_mask = tf.concat([input_mask, features["condition_inputs"].mask], 1)

    # [batch_size, condition_length, num_layers, num_heads, head_size]
    _, condition_cache = model.compute_transformer(
        input_ids=features["condition_inputs"].token_ids,
        input_segment_id=features["condition_inputs"].segment_ids,
        input_positions=features["condition_inputs"].positions,
        attention_mask=tf.expand_dims(input_mask, 1),
        input_cache=input_cache,
        reuse=tf.AUTO_REUSE,
        conditional=True)

    # [batch_size, input_length, num_layers, num_heads, head_size]
    input_cache = transformer_utils.TransformerCache(
        keys=tf.concat([input_cache.keys, condition_cache.keys], 1),
        values=tf.concat([input_cache.values, condition_cache.values], 1))

  # ----------------------------------------------------------------------------
  # TRAINING
  # ----------------------------------------------------------------------------

  if mode == tf_estimator.ModeKeys.TRAIN:
    # During training, apply forced decoding with a diagonal attention mask.
    # [batch_size, caption_length - 1, input_length + caption_length - 1]
    attention_mask = transformer_utils.compute_attention_mask(
        token_mask=features["token_inputs"].mask, input_mask=input_mask)

    # [batch_size, caption_length - 1, hidden_size]
    target_emb, _ = model.compute_transformer(
        input_ids=features["token_inputs"].token_ids,
        input_segment_id=features["token_inputs"].segment_ids,
        input_positions=features["token_inputs"].positions,
        attention_mask=attention_mask,
        input_cache=input_cache,
        reuse=tf.AUTO_REUSE)

    # [batch_size, caption_length - 1, vocab_size]
    target_logits = model.compute_logits(target_emb, reuse=tf.AUTO_REUSE)

    # Compute the MLE objective (cross-entropy loss).
    loss = tf.losses.sparse_softmax_cross_entropy(
        labels=features["token_outputs"].token_ids,
        logits=target_logits,
        weights=features["token_outputs"].mask)

    # BERT-style optimization with linear warmp.
    train_op = optimization.create_optimizer(
        loss=loss,
        init_lr=params["learning_rate"],
        num_train_steps=params["num_train_steps"],
        num_warmup_steps=params["num_warmup_steps"],
        use_tpu=params.get("use_tpu"))

    summaries = tpu_summaries.TpuSummaries(params["model_dir"])
    summaries.scalar("loss", loss)
    host_call = summaries.get_host_call()
  else:
    loss = None
    train_op = None
    host_call = None

  # ----------------------------------------------------------------------------
  # TESTING.
  # ----------------------------------------------------------------------------

  if mode == tf_estimator.ModeKeys.PREDICT:
    decode_output = transformer_utils.beam_search_decode(
        model=model,
        encoder_cache=input_cache,
        encoder_cache_mask=input_mask,
        start_id=vocab.t2i(vocab.CLS),
        stop_id=vocab.t2i(vocab.SEP),
        segment_id=0,
        num_steps=params["decode_length"],
        beam_size=params["beam_size"],
        alpha=params["beam_length_penalty"],
        reuse=tf.AUTO_REUSE)
    predictions = dict(
        image_id=features.get("image_id", -1),
        question_id=features.get("question_id", -1),
        token_ids=decode_output.token_ids[:, :, 1:])
  else:
    predictions = None

  # ----------------------------------------------------------------------------
  # WARM-START.
  # ----------------------------------------------------------------------------

  # Initialize from pretrained model.
  def scaffold_fn():
    """Init op run on host."""
    checkpoint = params.get("warm_start_path")
    if checkpoint:
      checkpoint_utils.init_from_checkpoint(checkpoint)
    return tf.train.Scaffold()

  return tf_estimator.tpu.TPUEstimatorSpec(
      mode=mode,
      loss=loss,
      train_op=train_op,
      predictions=predictions,
      scaffold_fn=scaffold_fn,
      host_call=host_call,
  )