text:
Searches Cortex XSOAR incidents

## Permissions
---

This automation runs using the default Limited User role, unless you explicitly change the permissions.
For more information, see the section about permissions here: [https://docs.paloaltonetworks.com/cortex/cortex-xsoar/6-2/cortex-xsoar-admin/playbooks/automations.html
](https://docs.paloaltonetworks.com/cortex/cortex-xsoar/6-2/cortex-xsoar-admin/playbooks/automations.html)

## Script Data
---

| **Name** | **Description** |
| --- | --- |
| Script Type | python3 |
| Tags | Utility |
| Cortex XSOAR Version | 5.0.0 |

## Used In
---
This script is used in the following playbooks and scripts.
* ExtraHop - Ticket Tracking
* SafeBreach - Create Incidents per Insight and Associate Indicators
* Send Investigation Summary Reports

## Inputs
---

| **Argument Name** | **Description** |
| --- | --- |
| id | A comma-separated list of incident IDs by which to filter the results. |
| name | A comma-separated list of incident names by which to filter the results. |
| status | A comma-separated list of incident statuses by which to filter the results. For example: assigned. |
| notstatus | A comma-separated list of incident statuses to exclude from the results.  For example: assigned. |
| reason | A comma-separated list of incident close reasons by which to filter the results. |
| fromdate | Filter by from date \(e.g. 2006-01-02T15:04:05\+07:00 or 2006-01-02T15:04:05Z\) |
| todate | Filter by to date \(e.g. 2006-01-02T15:04:05\+07:00 or 2006-01-02T15:04:05Z\) |
| fromclosedate | Filter by from close date \(e.g. 2006-01-02T15:04:05\+07:00 or 2006-01-02T15:04:05Z\) |
| toclosedate | Filter by to close date \(e.g. 2006-01-02T15:04:05\+07:00 or 2006-01-02T15:04:05Z\) |
| fromduedate | Filter by from due date \(e.g. 2006-01-02T15:04:05\+07:00 or 2006-01-02T15:04:05Z\) |
| toduedate | Filter by to due date \(e.g. 2006-01-02T15:04:05\+07:00 or 2006-01-02T15:04:05Z\) |
| level | Filter by Severity |
| owner | Filter by incident owners |
| details | Filter by incident details |
| type | Filter by incident type |
| query | Use free form query \(use Lucene syntax\) as filter. All other filters will be ignored when this filter is used. |
| page | Filter by the page number |
| size | Number of incidents per page \(per fetch\) |
| sort | Sort in format of field.asc,field.desc,... |
| searchresultslabel | If provided, the value of this argument will be set under the searchResultsLabel context key for each incident found. |

## Outputs
---

| **Path** | **Description** | **Type** |
| --- | --- | --- |
| foundIncidents.id | A list of incident IDs returned from the query. | Unknown |
| foundIncidents.name | A list of incident names returned from the query. | Unknown |
| foundIncidents.severity | A list of incident severities returned from the query. | Unknown |
| foundIncidents.status | A list of incident statuses returned from the query. | Unknown |
| foundIncidents.owner | A list of incident owners returned from the query. | Unknown |
| foundIncidents.created | A list of the incident create date returned from the query. | Unknown |
| foundIncidents.closed | A list of incident close dates returned from the query. | Unknown |
| foundIncidents.labels | An array of labels per incident returned from the query. | Unknown |
| foundIncidents.details | Details of the incidents returned from the query. | Unknown |
| foundIncidents.dueDate | A list of incident due dates returned from the query. | Unknown |
| foundIncidents.phase | A list of incident phases returned from the query. | Unknown |
| foundIncidents.searchResultsLabel| The value provided in the searchresultslabel argument. | String |

## Script Example
```!SearchIncidentsV2 name="Incident to search"```

## Context Example
```
{
    "foundIncidents": [
        {
            "CustomFields": {
                "detectionsla": {
                    "accumulatedPause": 0,
                    "breachTriggered": false,
                    "dueDate": "0001-01-01T00:00:00Z",
                    "endDate": "0001-01-01T00:00:00Z",
                    "lastPauseDate": "0001-01-01T00:00:00Z",
                    "runStatus": "idle",
                    "sla": 20,
                    "slaStatus": -1,
                    "startDate": "0001-01-01T00:00:00Z",
                    "totalDuration": 0
                },
                "remediationsla": {
                    "accumulatedPause": 0,
                    "breachTriggered": false,
                    "dueDate": "0001-01-01T00:00:00Z",
                    "endDate": "0001-01-01T00:00:00Z",
                    "lastPauseDate": "0001-01-01T00:00:00Z",
                    "runStatus": "idle",
                    "sla": 7200,
                    "slaStatus": -1,
                    "startDate": "0001-01-01T00:00:00Z",
                    "totalDuration": 0
                },
                "timetoassignment": {
                    "accumulatedPause": 0,
                    "breachTriggered": false,
                    "dueDate": "0001-01-01T00:00:00Z",
                    "endDate": "0001-01-01T00:00:00Z",
                    "lastPauseDate": "0001-01-01T00:00:00Z",
                    "runStatus": "idle",
                    "sla": 0,
                    "slaStatus": -1,
                    "startDate": "0001-01-01T00:00:00Z",
                    "totalDuration": 0
                },
                "urlsslverification": []
            },
            "ShardID": 0,
            "account": "",
            "activated": "0001-01-01T00:00:00Z",
            "allRead": false,
            "allReadWrite": false,
            "attachment": null,
            "autime": 1601389784162034000,
            "canvases": null,
            "category": "",
            "closeNotes": "",
            "closeReason": "",
            "closed": "0001-01-01T00:00:00Z",
            "closingUserId": "",
            "created": "2020-09-29T17:29:44.162034+03:00",
            "dbotCreatedBy": "admin",
            "dbotCurrentDirtyFields": null,
            "dbotDirtyFields": null,
            "dbotMirrorDirection": "",
            "dbotMirrorId": "",
            "dbotMirrorInstance": "",
            "dbotMirrorLastSync": "0001-01-01T00:00:00Z",
            "dbotMirrorTags": null,
            "details": "",
            "droppedCount": 0,
            "dueDate": "2020-10-09T17:29:44.162034+03:00",
            "feedBased": false,
            "hasRole": false,
            "id": "978",
            "investigationId": "",
            "isPlayground": false,
            "labels": [
                {
                    "type": "Instance",
                    "value": "admin"
                },
                {
                    "type": "Brand",
                    "value": "Manual"
                }
            ],
            "lastJobRunTime": "0001-01-01T00:00:00Z",
            "lastOpen": "0001-01-01T00:00:00Z",
            "linkedCount": 0,
            "linkedIncidents": null,
            "modified": "2020-09-29T17:29:44.162202+03:00",
            "name": "Incident to search",
            "notifyTime": "0001-01-01T00:00:00Z",
            "occurred": "2020-09-29T17:29:44.162034+03:00",
            "openDuration": 0,
            "owner": "admin",
            "parent": "",
            "phase": "",
            "playbookId": "",
            "previousAllRead": false,
            "previousAllReadWrite": false,
            "previousRoles": null,
            "rawCategory": "",
            "rawCloseReason": "",
            "rawJSON": "",
            "rawName": "Incident to search",
            "rawPhase": "",
            "rawType": "Unclassified",
            "reason": "",
            "reminder": "0001-01-01T00:00:00Z",
            "roles": null,
            "runStatus": "",
            "severity": 0,
            "sla": 0,
            "sortValues": [
                "_score"
            ],
            "sourceBrand": "Manual",
            "sourceInstance": "admin",
            "status": 0,
            "type": "Unclassified",
            "version": 1
        }
    ]
}
```

## Human Readable Output
### Incidents found
|id|name|severity|status|owner|created|closed|
|---|---|---|---|---|---|---|
| 978 | Incident to search | 0 | 0 | admin | 2020-09-29T17:29:44.162034+03:00 | 0001-01-01T00:00:00Z |


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RA.Models.Input
{
    /// <summary>
    /// Common input class for all process profiles
    /// </summary>
    public class ProcessProfile
    {
        public ProcessProfile()
        {
            ExternalInputType = new List<string>();
            Jurisdiction = new List<Jurisdiction>();

            TargetCredential = new List<EntityReference>();
            TargetAssessment = new List<EntityReference>();
            TargetLearningOpportunity = new List<EntityReference>();
            TargetCompetencyFramework = new List<EntityReference>();
            //Region = new List<GeoCoordinates>();
        }
        public string Description { get; set; }
        public string SubjectWebpage { get; set; }
        public string DateEffective { get; set; }
        //public List<CredentialAlignmentObject> ExternalInputType { get; set; }
        public List<string> ExternalInputType { get; set; }
        public string ProcessFrequency { get; set; }
        public List<OrganizationReference> ProcessingAgent { get; set; } = new List<OrganizationReference>();
        public string ProcessMethod { get; set; }
        public string ProcessMethodDescription { get; set; }
        public string ProcessStandards { get; set; }
        public string ProcessStandardsDescription { get; set; }
        public string ScoringMethodDescription { get; set; }
        public string ScoringMethodExample { get; set; }
        public string ScoringMethodExampleDescription { get; set; }
        //public List<string> ScoringMethodType { get; set; }
        public List<EntityReference> TargetCredential { get; set; }
        public List<EntityReference> TargetAssessment { get; set; }
        public List<EntityReference> TargetLearningOpportunity { get; set; }
        public List<EntityReference> TargetCompetencyFramework { get; set; }
        public string VerificationMethodDescription { get; set; }
        public List<Jurisdiction> Jurisdiction { get; set; }
        //public List<GeoCoordinates> Region { get; set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
import uuid
import datetime

import bson

from st2tests import DbTestCase
from st2common.util import date as date_utils
from tests.unit.base import FakeModel, FakeModelDB

class TestPersistence(DbTestCase):

    @classmethod
    def setUpClass(cls):
        super(TestPersistence, cls).setUpClass()
        cls.access = FakeModel()

    def tearDown(self):
        FakeModelDB.drop_collection()
        super(TestPersistence, self).tearDown()

    def test_crud(self):
        obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'a': 1})
        obj1 = self.access.add_or_update(obj1)
        obj2 = self.access.get(name=obj1.name)
        self.assertIsNotNone(obj2)
        self.assertEqual(obj1.id, obj2.id)
        self.assertEqual(obj1.name, obj2.name)
        self.assertDictEqual(obj1.context, obj2.context)

        obj1.name = uuid.uuid4().hex
        obj1 = self.access.add_or_update(obj1)
        obj2 = self.access.get(name=obj1.name)
        self.assertIsNotNone(obj2)
        self.assertEqual(obj1.id, obj2.id)
        self.assertEqual(obj1.name, obj2.name)
        self.assertDictEqual(obj1.context, obj2.context)

        self.access.delete(obj1)
        obj2 = self.access.get(name=obj1.name)
        self.assertIsNone(obj2)

    def test_count(self):
        obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'system'})
        obj1 = self.access.add_or_update(obj1)
        obj2 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'stanley'})
        obj2 = self.access.add_or_update(obj2)
        self.assertEqual(self.access.count(), 2)

    def test_get_all(self):
        obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'system'})
        obj1 = self.access.add_or_update(obj1)
        obj2 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'stanley'})
        obj2 = self.access.add_or_update(obj2)
        objs = self.access.get_all()
        self.assertIsNotNone(objs)
        self.assertEqual(len(objs), 2)
        self.assertListEqual(list(objs), [obj1, obj2])

    def test_query_by_id(self):
        obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'system'})
        obj1 = self.access.add_or_update(obj1)
        obj2 = self.access.get_by_id(str(obj1.id))
        self.assertIsNotNone(obj2)
        self.assertEqual(obj1.id, obj2.id)
        self.assertEqual(obj1.name, obj2.name)
        self.assertDictEqual(obj1.context, obj2.context)
        self.assertRaises(ValueError, self.access.get_by_id, str(bson.ObjectId()))

    def test_query_by_name(self):
        obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'system'})
        obj1 = self.access.add_or_update(obj1)
        obj2 = self.access.get_by_name(obj1.name)
        self.assertIsNotNone(obj2)
        self.assertEqual(obj1.id, obj2.id)
        self.assertEqual(obj1.name, obj2.name)
        self.assertDictEqual(obj1.context, obj2.context)
        self.assertRaises(ValueError, self.access.get_by_name, uuid.uuid4().hex)

    def test_query_filter(self):
        obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'system'})
        obj1 = self.access.add_or_update(obj1)
        obj2 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'stanley'})
        obj2 = self.access.add_or_update(obj2)
        objs = self.access.query(context__user='system')
        self.assertIsNotNone(objs)
        self.assertGreater(len(objs), 0)
        self.assertEqual(obj1.id, objs[0].id)
        self.assertEqual(obj1.name, objs[0].name)
        self.assertDictEqual(obj1.context, objs[0].context)

    def test_null_filter(self):
        obj1 = FakeModelDB(name=uuid.uuid4().hex)
        obj1 = self.access.add_or_update(obj1)

        objs = self.access.query(index='null')
        self.assertEqual(len(objs), 1)
        self.assertEqual(obj1.id, objs[0].id)
        self.assertEqual(obj1.name, objs[0].name)
        self.assertIsNone(getattr(obj1, 'index', None))

        objs = self.access.query(index=None)
        self.assertEqual(len(objs), 1)
        self.assertEqual(obj1.id, objs[0].id)
        self.assertEqual(obj1.name, objs[0].name)
        self.assertIsNone(getattr(obj1, 'index', None))

    def test_datetime_range(self):
        base = date_utils.add_utc_tz(datetime.datetime(2014, 12, 25, 0, 0, 0))
        for i in range(60):
            timestamp = base + datetime.timedelta(seconds=i)
            obj = FakeModelDB(name=uuid.uuid4().hex, timestamp=timestamp)
            self.access.add_or_update(obj)

        dt_range = '2014-12-25T00:00:10Z..2014-12-25T00:00:19Z'
        objs = self.access.query(timestamp=dt_range)
        self.assertEqual(len(objs), 10)
        self.assertLess(objs[0].timestamp, objs[9].timestamp)

        dt_range = '2014-12-25T00:00:19Z..2014-12-25T00:00:10Z'
        objs = self.access.query(timestamp=dt_range)
        self.assertEqual(len(objs), 10)
        self.assertLess(objs[9].timestamp, objs[0].timestamp)

    def test_pagination(self):
        count = 100
        page_size = 25
        pages = count / page_size
        users = ['Peter', 'Susan', 'Edmund', 'Lucy']

        for user in users:
            context = {'user': user}
            for i in range(count):
                self.access.add_or_update(FakeModelDB(name=uuid.uuid4().hex,
                                                      context=context, index=i))

        self.assertEqual(self.access.count(), len(users) * count)

        for user in users:
            for i in range(pages):
                offset = i * page_size
                objs = self.access.query(context__user=user, order_by=['index'],
                                         offset=offset, limit=page_size)
                self.assertEqual(len(objs), page_size)
                for j in range(page_size):
                    self.assertEqual(objs[j].context['user'], user)
                    self.assertEqual(objs[j].index, (i * page_size) + j)

    def test_sort_multiple(self):
        count = 60
        base = date_utils.add_utc_tz(datetime.datetime(2014, 12, 25, 0, 0, 0))
        for i in range(count):
            category = 'type1' if i % 2 else 'type2'
            timestamp = base + datetime.timedelta(seconds=i)
            obj = FakeModelDB(name=uuid.uuid4().hex, timestamp=timestamp, category=category)
            self.access.add_or_update(obj)

        objs = self.access.query(order_by=['category', 'timestamp'])
        self.assertEqual(len(objs), count)
        for i in range(count):
            category = 'type1' if i < count / 2 else 'type2'
            self.assertEqual(objs[i].category, category)
        self.assertLess(objs[0].timestamp, objs[(count / 2) - 1].timestamp)
        self.assertLess(objs[count / 2].timestamp, objs[(count / 2) - 1].timestamp)
        self.assertLess(objs[count / 2].timestamp, objs[count - 1].timestamp)


text:
"""MultiDeviceIterator tests."""

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

from tensorflow.core.protobuf import config_pb2
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.ops import multi_device_iterator_ops
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import test

class MultiDeviceIteratorTest(test_base.DatasetTestBase):

  def testNoGetNext(self):
    dataset = dataset_ops.Dataset.range(10)
    multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(
        dataset, ["/cpu:1", "/cpu:2"])

    config = config_pb2.ConfigProto(device_count={"CPU": 3})
    with self.test_session(config=config) as sess:
      sess.run(multi_device_iterator.initializer)

  def testBasic(self):
    dataset = dataset_ops.Dataset.range(10)
    multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(
        dataset, ["/cpu:1", "/cpu:2"])
    elem_on_1, elem_on_2 = multi_device_iterator.get_next()

    config = config_pb2.ConfigProto(device_count={"CPU": 3})
    with self.test_session(config=config) as sess:
      sess.run(multi_device_iterator.initializer)
      for i in range(0, 10, 2):
        self.assertEqual(i, sess.run(elem_on_1))
        self.assertEqual(i + 1, sess.run(elem_on_2))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(elem_on_1)
        sess.run(elem_on_2)

  def testOneOnSameDevice(self):
    with ops.device("/cpu:0"):
      dataset = dataset_ops.Dataset.range(10)
    multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(
        dataset, ["/cpu:0", "/cpu:1"])
    elem_on_1, elem_on_2 = multi_device_iterator.get_next()

    config = config_pb2.ConfigProto(device_count={"CPU": 2})
    with self.test_session(config=config) as sess:
      sess.run(multi_device_iterator.initializer)
      for i in range(0, 10, 2):
        self.assertEqual(i, sess.run(elem_on_1))
        self.assertEqual(i + 1, sess.run(elem_on_2))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(elem_on_1)
        sess.run(elem_on_2)

  def testRepeatDevices(self):
    with ops.device("/cpu:0"):
      dataset = dataset_ops.Dataset.range(20)
    multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(
        dataset, ["/cpu:1", "/cpu:2", "/cpu:1", "/cpu:2"])
    elements = multi_device_iterator.get_next()
    elem_on_1, elem_on_2, elem_on_3, elem_on_4 = elements

    config = config_pb2.ConfigProto(device_count={"CPU": 3})
    with self.test_session(config=config) as sess:
      sess.run(multi_device_iterator.initializer)
      for i in range(0, 20, 4):
        self.assertEqual(i, sess.run(elem_on_1))
        self.assertEqual(i + 1, sess.run(elem_on_2))
        self.assertEqual(i + 2, sess.run(elem_on_3))
        self.assertEqual(i + 3, sess.run(elem_on_4))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(elem_on_1)
        sess.run(elem_on_2)
        sess.run(elem_on_3)
        sess.run(elem_on_4)

  def testNotFullyDivisible(self):
    dataset = dataset_ops.Dataset.range(9)
    multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(
        dataset, ["/cpu:1", "/cpu:2"])
    elem_on_1, elem_on_2 = multi_device_iterator.get_next()

    config = config_pb2.ConfigProto(device_count={"CPU": 3})
    with self.test_session(config=config) as sess:
      sess.run(multi_device_iterator.initializer)
      for i in range(0, 8, 2):
        self.assertEqual(i, sess.run(elem_on_1))
        self.assertEqual(i + 1, sess.run(elem_on_2))
      self.assertEqual(8, sess.run(elem_on_1))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(elem_on_1)
        sess.run(elem_on_2)

  def testUneven(self):
    dataset = dataset_ops.Dataset.range(10)
    multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(
        dataset, ["/cpu:1", "/cpu:2"], max_buffer_size=4)
    elem_on_1, elem_on_2 = multi_device_iterator.get_next()

    config = config_pb2.ConfigProto(device_count={"CPU": 3})
    with self.test_session(config=config) as sess:
      sess.run(multi_device_iterator.initializer)
      for i in range(0, 10, 2):
        self.assertEqual(i, sess.run(elem_on_1))
      for i in range(0, 10, 2):
        self.assertEqual(i + 1, sess.run(elem_on_2))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(elem_on_1)
        sess.run(elem_on_2)

  def testMultipleInitializations(self):
    with ops.device("/cpu:0"):
      epoch = array_ops.placeholder(dtypes.int64, shape=[])
      dataset1 = dataset_ops.Dataset.from_tensors(epoch).repeat(1000)
      dataset2 = dataset_ops.Dataset.range(1000)
      dataset = dataset_ops.Dataset.zip((dataset1, dataset2))
    multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(
        dataset, ["/cpu:1", "/cpu:2"], prefetch_buffer_size=4)
    elem_on_1, elem_on_2 = multi_device_iterator.get_next()
    init_op = multi_device_iterator.initializer

    config = config_pb2.ConfigProto(device_count={"CPU": 3})
    with self.test_session(config=config) as sess:
      for i in range(1000):
        sess.run(init_op, feed_dict={epoch: i})
        self.assertEqual([(i, 0), (i, 1)], sess.run([elem_on_1, elem_on_2]))

  def testBasicGpu(self):
    if not test_util.is_gpu_available():
      self.skipTest("No GPU available")

    dataset = dataset_ops.Dataset.range(10)
    multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(
        dataset, ["/cpu:1", "/gpu:0"])
    elem_on_1, elem_on_2 = multi_device_iterator.get_next()

    config = config_pb2.ConfigProto(device_count={"CPU": 2, "GPU": 1})
    with self.test_session(config=config) as sess:
      sess.run(multi_device_iterator.initializer)
      for i in range(0, 10, 2):
        self.assertEqual(i, sess.run(elem_on_1))
        self.assertEqual(i + 1, sess.run(elem_on_2))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(elem_on_1)
        sess.run(elem_on_2)

  def testUnevenGpu(self):
    if not test_util.is_gpu_available():
      self.skipTest("No GPU available")

    dataset = dataset_ops.Dataset.range(10)
    multi_device_iterator = multi_device_iterator_ops.MultiDeviceIterator(
        dataset, ["/cpu:1", "/gpu:0"], max_buffer_size=4)
    elem_on_1, elem_on_2 = multi_device_iterator.get_next()

    config = config_pb2.ConfigProto(device_count={"CPU": 2, "GPU": 1})
    with self.test_session(config=config) as sess:
      sess.run(multi_device_iterator.initializer)
      for i in range(0, 10, 2):
        self.assertEqual(i, sess.run(elem_on_1))
      for i in range(0, 10, 2):
        self.assertEqual(i + 1, sess.run(elem_on_2))
      with self.assertRaises(errors.OutOfRangeError):
        sess.run(elem_on_1)
        sess.run(elem_on_2)

if __name__ == "__main__":
  test.main()


text:
<!DOCTYPE html>
{% autoescape true %}

    <title>All Accounts</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link type="text/css" rel="stylesheet"
          href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"/>
    <link type="text/css" rel="stylesheet"
          href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css"/>
    <link type="text/css" rel="stylesheet"
          href="http://cdn.bootcss.com/bootstrap-table/1.7.0/bootstrap-table.min.css" />

            Create Account

                Key
                Author
                Account
                Type
                Create Time
                Last Modified

            {% for account in accounts %}

                {{ account.key.id() }}
                {{ account.author.nickname() }}
                {{ account.acct }}
                {{ account.acctType }}
                {{ account.createdTime }}
                {{ account.lastModifiedTime }}

                    Edit
                    Delete

            {% endfor %}

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Create Account

                <form id="createAcctForm" action="/Accounts/Create" method="post" class="form-horizontal"
                      data-ajax="true"
                      data-ajax-method="post" data-ajax-success="createAcctSucc">

                        Account

                            <input type="text" name="acct" placeholder="Account" data-val="true"
                                   data-val-required="Account is required."/>

                        Password

                            <input type="password" name="psw" placeholder="Password" data-val="true"
                                   data-val-required="Password is required."/>

                        Type

                            <select name="acctType" data-val="true" data-val-required="Type is required.">
                                <option value="">--Select--</option>
                                <option value="smzdm">SMZDM</option>
                            </select>

                </form>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button id="btnCreateAcct" type="button" class="btn btn-primary">Create Account</button>

{% endautoescape %}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<link rel="shortcut icon" href="http://media.mongodb.org/favicon.ico" />

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Binary JSON API — MongoDB Node.JS Driver 1.4.9 documentation</title>

    <link rel="stylesheet" href="../_static/mongodb-docs.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="MongoDB Node.JS Driver 1.4.9 documentation" href="../index.html" />

Navigation

| GitHub

Jira

MongoDB Node.JS Driver 1.4.9 documentation (index)  »

Binary JSON API¶

ObjectID()

Constructor

toHexString

equals

getTimestamp

ObjectID.createFromTime

ObjectID.createFromHexString

ObjectID.isValid

Binary()

Constructor

Constants

put

write

read

value

length

Code()

Constructor

DBRef()

Constructor

Double()

Constructor

valueOf

MinKey()

Constructor

MaxKey()

Constructor

Symbol()

Constructor

valueOf

Timestamp()

Constructor

toInt

toNumber

toJSON

toString

getHighBits

getLowBits

getLowBitsUnsigned

getNumBitsAbs

isZero

isNegative

isOdd

equals

notEquals

lessThan

lessThanOrEqual

greaterThan

greaterThanOrEqual

compare

negate

add

subtract

multiply

div

modulo

not

and

or

xor

shiftLeft

shiftRight

shiftRightUnsigned

Timestamp.fromInt

Timestamp.fromNumber

Timestamp.fromBits

Timestamp.fromString

Long()

Constructor

toInt

toNumber

toJSON

toString

getHighBits

getLowBits

getLowBitsUnsigned

getNumBitsAbs

isZero

isNegative

isOdd

equals

notEquals

lessThan

lessThanOrEqual

greaterThan

greaterThanOrEqual

compare

negate

add

subtract

multiply

div

modulo

not

and

or

xor

shiftLeft

shiftRight

shiftRightUnsigned

Long.fromInt

Long.fromNumber

Long.fromBits

Long.fromString

BSON()

Constructor

Constants

BSON.calculateObjectSize

BSON.serializeWithBufferAndIndex

BSON.serialize

BSON.deserializeStream

BSON.deserialize

deserialize

deserializeStream

serialize

calculateObjectSize

serializeWithBufferAndIndex

Contents

Binary JSON API

Manual

MongoClient()

Db()

Collection()

Admin()

Cursor()

CursorStream()

Grid()

GridStore()

ReadStream()

BSON()

ObjectID()

Binary()

Code()

Double()

Long()

Timestamp()

MaxKey()

Symbol()

Home: MongoDB Node.JS Driver Manual Home

Contents: MongoDB Node.JS Driver Manual Contents

Index: MongoDB Node.JS Driver Manual Index

Search

Search this manual.
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Search" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Search the MongoDB wiki.
    <form class="search" action="http://www.mongodb.org/dosearchsite.action" method="get">
      <input type="text" name="queryString" />
      <input type="submit" value="Wiki" />
    </form>

MongoDB Wiki

Getting Started

Quickstart

Introduction

Downloads

Features

SQL to MongoDB Mapping

Developer Documentation

Connections

Databases

Collections

Documents

GridFS

Indexes

Querying

Aggregation

Optimization

Inserting

Updating

Removing

MapReduce

Administrative Documentation

Components

Journaling

Production Notes

Replication

Sharding

Monitoring and Diagnostics

Backups

Durability and Repair

Security and Authentication

Starting/Stopping MongoDB

GridFS Tools

DB Operations from the Shell

Architecture and Components

Windows

Troubleshooting

Community and Ecosystem

10gen

MongoDB Events

MongoDB Masters

Slides and Video

Cookbook

Hosting Center

MongoDB Monitoring Service (docs)

Administrative Interfaces

International Documentation

MongoDB Books

Drivers

JavaScript (wiki, docs)

Python (wiki, docs)

Ruby (wiki, docs)

PHP (wiki, docs)

Perl (wiki, docs)

Java (wiki, docs)

Scala (wiki, docs)

C# (wiki, docs)

C (wiki, docs)

C++ (wiki, docs)

Haskell (wiki, docs)

Erlang (wiki, docs)

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

| GitHub

Jira

MongoDB Node.JS Driver 1.4.9 documentation (index)  »

        © Copyright 2013, MongoDB Node.JS Team
      Created using Sphinx 1.2b3.

The MongoDB Documentation Project uses GitHub. Fork the repository and submit pull requests to contribute.

If you find any issues with the documentation feel free to open a Jira Case and we'll work to resolve it promptly.


text:
package net.opengis.gml.impl;
/**
 * A document containing one valueProperty(@http://www.opengis.net/gml) element.
 *
 * This is a complex type.
 */
public class ValuePropertyDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements net.opengis.gml.ValuePropertyDocument
{
    private static final long serialVersionUID = 1L;

    public ValuePropertyDocumentImpl(org.apache.xmlbeans.SchemaType sType)
    {
        super(sType);
    }

    private static final javax.xml.namespace.QName VALUEPROPERTY$0 =
        new javax.xml.namespace.QName("http://www.opengis.net/gml", "valueProperty");

    /**
     * Gets the "valueProperty" element
     */
    public net.opengis.gml.ValuePropertyType getValueProperty()
    {
        synchronized (monitor())
        {
            check_orphaned();
            net.opengis.gml.ValuePropertyType target = null;
            target = (net.opengis.gml.ValuePropertyType)get_store().find_element_user(VALUEPROPERTY$0, 0);
            if (target == null)
            {
                return null;
            }
            return target;
        }
    }

    /**
     * Sets the "valueProperty" element
     */
     public void setValueProperty(net.opengis.gml.ValuePropertyType valueProperty)
    {
        generatedSetterHelperImpl(valueProperty, VALUEPROPERTY$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
    }

    /**
     * Appends and returns a new empty "valueProperty" element
     */
    public net.opengis.gml.ValuePropertyType addNewValueProperty()
    {
        synchronized (monitor())
        {
            check_orphaned();
            net.opengis.gml.ValuePropertyType target = null;
            target = (net.opengis.gml.ValuePropertyType)get_store().add_element_user(VALUEPROPERTY$0);
            return target;
        }
    }
}


text:
$LOAD_PATH.unshift File.dirname(__FILE__)
$LOAD_PATH.unshift File.dirname(__FILE__) + "/rubyrep"

require 'rubygems'
require 'yaml'

gem 'activerecord', '>= 2.2.2'
require 'active_record'

require 'version'
require 'configuration'
require 'initializer'
require 'session'
require 'connection_extenders/connection_extenders'
require 'table_scan_helper'
require 'table_scan'
require 'type_casting_cursor'
require 'proxy_cursor'
require 'proxy_block_cursor'
require 'proxy_row_cursor'
require 'direct_table_scan'
require 'proxied_table_scan'
require 'database_proxy'
require 'command_runner'
require 'proxy_runner'
require 'proxy_connection'
require 'table_spec_resolver'
require 'scan_report_printers/scan_report_printers'
require 'scan_report_printers/scan_summary_reporter'
require 'scan_report_printers/scan_detail_reporter'
require 'scan_progress_printers/scan_progress_printers'
require 'scan_progress_printers/progress_bar'
require 'base_runner'
require 'scan_runner'
require 'committers/committers'
require 'committers/buffered_committer'
require 'log_helper'
require 'sync_helper'
require 'table_sorter'
require 'table_sync'
require 'syncers/syncers'
require 'syncers/two_way_syncer'
require 'sync_runner'
require 'trigger_mode_switcher'
require 'logged_change_loader'
require 'logged_change'
require 'replication_difference'
require 'replication_helper'
require 'replicators/replicators'
require 'replicators/two_way_replicator'
require 'task_sweeper'
require 'replication_run'
require 'replication_runner'
require 'uninstall_runner'
require 'generate_runner'
require 'noisy_connection'

Dir["#{File.dirname(__FILE__)}/rubyrep/connection_extenders/*.rb"].each do |extender|
  # jdbc_extender.rb is only loaded if we are running on jruby
  require extender unless extender =~ /jdbc/ and not RUBY_PLATFORM =~ /java/
end

require 'replication_initializer'
require 'replication_extenders/replication_extenders'

Dir["#{File.dirname(__FILE__)}/rubyrep/replication_extenders/*.rb"].each do |extender|
  require extender
end

module RR

end


text:
namespace magritte {
using ::mediapipe::CalculatorContext;
using ::mediapipe::CalculatorContract;
using ::mediapipe::ImageFrame;
#if !defined(MEDIAPIPE_DISABLE_GPU)
using ::mediapipe::GlCalculatorHelper;
using ::mediapipe::GpuBuffer;
#endif  //  !MEDIAPIPE_DISABLE_GPU
using ::mediapipe::Color;
using ::mediapipe::formats::MatView;
namespace {
constexpr char kGpuBufferTag[] = "IMAGE_GPU";
constexpr char kImageFrameTag[] = "IMAGE";
}  // namespace

absl::Status NewCanvasCalculator::GetContract(CalculatorContract* cc) {
  RET_CHECK(cc != nullptr) << "CalculatorContract is nullptr";
  RET_CHECK(cc->Inputs().HasTag(kImageFrameTag) ^
            cc->Inputs().HasTag(kGpuBufferTag))
      << "Calculator can have one and only one input";
  RET_CHECK(cc->Outputs().HasTag(kImageFrameTag) ^
            cc->Outputs().HasTag(kGpuBufferTag))
      << "Calculator can have one and only one output";

  if (cc->Inputs().HasTag(kImageFrameTag)) {
    cc->Inputs().Tag(kImageFrameTag).Set<ImageFrame>();
    RET_CHECK(cc->Outputs().HasTag(kImageFrameTag))
        << "Input and output format must be identical";
    cc->Outputs().Tag(kImageFrameTag).Set<ImageFrame>();
  }

#if !defined(MEDIAPIPE_DISABLE_GPU)
  if (cc->Inputs().HasTag(kGpuBufferTag)) {
    cc->Inputs().Tag(kGpuBufferTag).Set<GpuBuffer>();
    RET_CHECK(cc->Outputs().HasTag(kGpuBufferTag))
        << "Input and output format must be identical";
    cc->Outputs().Tag(kGpuBufferTag).Set<GpuBuffer>();
  }

  MP_RETURN_IF_ERROR(mediapipe::GlCalculatorHelper::UpdateContract(cc));
#endif  //  !MEDIAPIPE_DISABLE_GPU

  // No input side packets.
  return absl::OkStatus();
}

absl::Status NewCanvasCalculator::Open(CalculatorContext* cc) {
#if !defined(MEDIAPIPE_DISABLE_GPU)
  return helper_.Open(cc);
#endif  //  !MEDIAPIPE_DISABLE_GPU
  return absl::OkStatus();
}

absl::Status NewCanvasCalculator::Process(CalculatorContext* cc) {
  RET_CHECK(cc != nullptr) << "CalculatorContext is nullptr";
  bool use_gpu = cc->Inputs().HasTag(kGpuBufferTag);
  if (use_gpu) {
    return ProcessGpu(cc);
  } else {
    return ProcessCpu(cc);
  }
}

absl::Status NewCanvasCalculator::ProcessCpu(CalculatorContext* cc) {
  const NewCanvasCalculatorOptions& options =
      cc->Options<NewCanvasCalculatorOptions>();

  if (cc->Inputs().Tag(kImageFrameTag).Value().IsEmpty()) {
    LOG(WARNING) << "No image frame at " << cc->InputTimestamp();
    return absl::OkStatus();
  }

  const auto& frame = cc->Inputs().Tag(kImageFrameTag).Get<ImageFrame>();
  std::pair<int, int> size =
      GetSizeFromOptions(options, frame.Width(), frame.Height());
  auto output_frame =
      std::make_unique<ImageFrame>(frame.Format(), size.first, size.second);

  cv::Mat src = MatView(output_frame.get());
  const mediapipe::Color color = options.color();
  src.setTo(cv::Scalar(color.r(), color.g(), color.b()));

  cc->Outputs()
      .Tag(kImageFrameTag)
      .Add(output_frame.release(), cc->InputTimestamp());
  return absl::OkStatus();
}

absl::Status NewCanvasCalculator::ProcessGpu(CalculatorContext* cc) {
  if (cc->Inputs().Tag(kGpuBufferTag).Value().IsEmpty()) {
    LOG(WARNING) << "No image frame at " << cc->InputTimestamp();
    return absl::OkStatus();
  }
#if !defined(MEDIAPIPE_DISABLE_GPU)
  const auto& input = cc->Inputs().Tag(kGpuBufferTag).Get<GpuBuffer>();
  helper_.RunInGlContext([this, &input, &cc] {
    const auto& options = cc->Options<NewCanvasCalculatorOptions>();

    std::pair<int, int> size =
        GetSizeFromOptions(options, input.width(), input.height());
    mediapipe::GlTexture src = helper_.CreateDestinationTexture(
        size.first, size.second, input.format());

    helper_.BindFramebuffer(src);
    mediapipe::Color color = options.has_color() ? options.color() : Color();
    glClearColor(color.r() / 255.0f, color.g() / 255.0f, color.b() / 255.0f,
                 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    std::unique_ptr<mediapipe::GpuBuffer> output = src.GetFrame<GpuBuffer>();
    glFlush();
    cc->Outputs()
        .Tag(kGpuBufferTag)
        .Add(output.release(), cc->InputTimestamp());
    src.Release();
  });
#endif  //  !MEDIAPIPE_DISABLE_GPU
  return absl::OkStatus();
}

std::pair<int, int> NewCanvasCalculator::GetSizeFromOptions(
    const NewCanvasCalculatorOptions& options, const int original_width,
    const int original_height) {
  if (options.has_scale_factor()) {
    return {options.scale_factor() * original_width,
            options.scale_factor() * original_height};
  }
  if (options.has_target_width() && options.has_target_height()) {
    return {options.target_width(), options.target_height()};
  }
  if (options.has_target_width()) {
    return {options.target_width(),
            original_height * options.target_width() / original_width};
  }
  if (options.has_target_height()) {
    return {original_width * options.target_height() / original_height,
            options.target_height()};
  }
  return {original_width, original_height};
}

REGISTER_CALCULATOR(NewCanvasCalculator);

}  // namespace magritte


text:
/* $Id: ClpQuadraticObjective.cpp 1723 2011-04-17 15:07:10Z forrest $ */
// Copyright (C) 2003, International Business Machines
// Corporation and others.  All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).

#include "CoinPragma.hpp"
#include "CoinHelperFunctions.hpp"
#include "CoinIndexedVector.hpp"
#include "ClpFactorization.hpp"
#include "ClpSimplex.hpp"
#include "ClpQuadraticObjective.hpp"
//#############################################################################
// Constructors / Destructor / Assignment
//#############################################################################
//-------------------------------------------------------------------
// Default Constructor
//-------------------------------------------------------------------
ClpQuadraticObjective::ClpQuadraticObjective ()
     : ClpObjective()
{
     type_ = 2;
     objective_ = NULL;
     quadraticObjective_ = NULL;
     gradient_ = NULL;
     numberColumns_ = 0;
     numberExtendedColumns_ = 0;
     activated_ = 0;
     fullMatrix_ = false;
}

//-------------------------------------------------------------------
// Useful Constructor
//-------------------------------------------------------------------
ClpQuadraticObjective::ClpQuadraticObjective (const double * objective ,
          int numberColumns,
          const CoinBigIndex * start,
          const int * column, const double * element,
          int numberExtendedColumns)
     : ClpObjective()
{
     type_ = 2;
     numberColumns_ = numberColumns;
     if (numberExtendedColumns >= 0)
          numberExtendedColumns_ = CoinMax(numberColumns_, numberExtendedColumns);
     else
          numberExtendedColumns_ = numberColumns_;
     if (objective) {
          objective_ = new double [numberExtendedColumns_];
          CoinMemcpyN(objective, numberColumns_, objective_);
          memset(objective_ + numberColumns_, 0, (numberExtendedColumns_ - numberColumns_)*sizeof(double));
     } else {
          objective_ = new double [numberExtendedColumns_];
          memset(objective_, 0, numberExtendedColumns_ * sizeof(double));
     }
     if (start)
          quadraticObjective_ = new CoinPackedMatrix(true, numberColumns, numberColumns,
                    start[numberColumns], element, column, start, NULL);
     else
          quadraticObjective_ = NULL;
     gradient_ = NULL;
     activated_ = 1;
     fullMatrix_ = false;
}

//-------------------------------------------------------------------
// Copy constructor
//-------------------------------------------------------------------
ClpQuadraticObjective::ClpQuadraticObjective (const ClpQuadraticObjective & rhs,
          int type)
     : ClpObjective(rhs)
{
     numberColumns_ = rhs.numberColumns_;
     numberExtendedColumns_ = rhs.numberExtendedColumns_;
     fullMatrix_ = rhs.fullMatrix_;
     if (rhs.objective_) {
          objective_ = new double [numberExtendedColumns_];
          CoinMemcpyN(rhs.objective_, numberExtendedColumns_, objective_);
     } else {
          objective_ = NULL;
     }
     if (rhs.gradient_) {
          gradient_ = new double [numberExtendedColumns_];
          CoinMemcpyN(rhs.gradient_, numberExtendedColumns_, gradient_);
     } else {
          gradient_ = NULL;
     }
     if (rhs.quadraticObjective_) {
          // see what type of matrix wanted
          if (type == 0) {
               // just copy
               quadraticObjective_ = new CoinPackedMatrix(*rhs.quadraticObjective_);
          } else if (type == 1) {
               // expand to full symmetric
               fullMatrix_ = true;
               const int * columnQuadratic1 = rhs.quadraticObjective_->getIndices();
               const CoinBigIndex * columnQuadraticStart1 = rhs.quadraticObjective_->getVectorStarts();
               const int * columnQuadraticLength1 = rhs.quadraticObjective_->getVectorLengths();
               const double * quadraticElement1 = rhs.quadraticObjective_->getElements();
               CoinBigIndex * columnQuadraticStart2 = new CoinBigIndex [numberExtendedColumns_+1];
               int * columnQuadraticLength2 = new int [numberExtendedColumns_];
               int iColumn;
               int numberColumns = rhs.quadraticObjective_->getNumCols();
               int numberBelow = 0;
               int numberAbove = 0;
               int numberDiagonal = 0;
               CoinZeroN(columnQuadraticLength2, numberExtendedColumns_);
               for (iColumn = 0; iColumn < numberColumns; iColumn++) {
                    for (CoinBigIndex j = columnQuadraticStart1[iColumn];
                              j < columnQuadraticStart1[iColumn] + columnQuadraticLength1[iColumn]; j++) {
                         int jColumn = columnQuadratic1[j];
                         if (jColumn > iColumn) {
                              numberBelow++;
                              columnQuadraticLength2[jColumn]++;
                              columnQuadraticLength2[iColumn]++;
                         } else if (jColumn == iColumn) {
                              numberDiagonal++;
                              columnQuadraticLength2[iColumn]++;
                         } else {
                              numberAbove++;
                         }
                    }
               }
               if (numberAbove > 0) {
                    if (numberAbove == numberBelow) {
                         // already done
                         quadraticObjective_ = new CoinPackedMatrix(*rhs.quadraticObjective_);
                         delete [] columnQuadraticStart2;
                         delete [] columnQuadraticLength2;
                    } else {
                         printf("number above = %d, number below = %d, error\n",
                                numberAbove, numberBelow);
                         abort();
                    }
               } else {
                    int numberElements = numberDiagonal + 2 * numberBelow;
                    int * columnQuadratic2 = new int [numberElements];
                    double * quadraticElement2 = new double [numberElements];
                    columnQuadraticStart2[0] = 0;
                    numberElements = 0;
                    for (iColumn = 0; iColumn < numberColumns; iColumn++) {
                         int n = columnQuadraticLength2[iColumn];
                         columnQuadraticLength2[iColumn] = 0;
                         numberElements += n;
                         columnQuadraticStart2[iColumn+1] = numberElements;
                    }
                    for (iColumn = 0; iColumn < numberColumns; iColumn++) {
                         for (CoinBigIndex j = columnQuadraticStart1[iColumn];
                                   j < columnQuadraticStart1[iColumn] + columnQuadraticLength1[iColumn]; j++) {
                              int jColumn = columnQuadratic1[j];
                              if (jColumn > iColumn) {
                                   // put in two places
                                   CoinBigIndex put = columnQuadraticLength2[jColumn] + columnQuadraticStart2[jColumn];
                                   columnQuadraticLength2[jColumn]++;
                                   quadraticElement2[put] = quadraticElement1[j];
                                   columnQuadratic2[put] = iColumn;
                                   put = columnQuadraticLength2[iColumn] + columnQuadraticStart2[iColumn];
                                   columnQuadraticLength2[iColumn]++;
                                   quadraticElement2[put] = quadraticElement1[j];
                                   columnQuadratic2[put] = jColumn;
                              } else if (jColumn == iColumn) {
                                   CoinBigIndex put = columnQuadraticLength2[iColumn] + columnQuadraticStart2[iColumn];
                                   columnQuadraticLength2[iColumn]++;
                                   quadraticElement2[put] = quadraticElement1[j];
                                   columnQuadratic2[put] = iColumn;
                              } else {
                                   abort();
                              }
                         }
                    }
                    // Now create
                    quadraticObjective_ =
                         new CoinPackedMatrix (true,
                                               rhs.numberExtendedColumns_,
                                               rhs.numberExtendedColumns_,
                                               numberElements,
                                               quadraticElement2,
                                               columnQuadratic2,
                                               columnQuadraticStart2,
                                               columnQuadraticLength2, 0.0, 0.0);
                    delete [] columnQuadraticStart2;
                    delete [] columnQuadraticLength2;
                    delete [] columnQuadratic2;
                    delete [] quadraticElement2;
               }
          } else {
               fullMatrix_ = false;
               abort(); // code when needed
          }

     } else {
          quadraticObjective_ = NULL;
     }
}
/* Subset constructor.  Duplicates are allowed
   and order is as given.
*/
ClpQuadraticObjective::ClpQuadraticObjective (const ClpQuadraticObjective &rhs,
          int numberColumns,
          const int * whichColumn)
     : ClpObjective(rhs)
{
     fullMatrix_ = rhs.fullMatrix_;
     objective_ = NULL;
     int extra = rhs.numberExtendedColumns_ - rhs.numberColumns_;
     numberColumns_ = 0;
     numberExtendedColumns_ = numberColumns + extra;
     if (numberColumns > 0) {
          // check valid lists
          int numberBad = 0;
          int i;
          for (i = 0; i < numberColumns; i++)
               if (whichColumn[i] < 0 || whichColumn[i] >= rhs.numberColumns_)
                    numberBad++;
          if (numberBad)
               throw CoinError("bad column list", "subset constructor",
                               "ClpQuadraticObjective");
          numberColumns_ = numberColumns;
          objective_ = new double[numberExtendedColumns_];
          for (i = 0; i < numberColumns_; i++)
               objective_[i] = rhs.objective_[whichColumn[i]];
          CoinMemcpyN(rhs.objective_ + rhs.numberColumns_,	(numberExtendedColumns_ - numberColumns_),
                      objective_ + numberColumns_);
          if (rhs.gradient_) {
               gradient_ = new double[numberExtendedColumns_];
               for (i = 0; i < numberColumns_; i++)
                    gradient_[i] = rhs.gradient_[whichColumn[i]];
               CoinMemcpyN(rhs.gradient_ + rhs.numberColumns_,	(numberExtendedColumns_ - numberColumns_),
                           gradient_ + numberColumns_);
          } else {
               gradient_ = NULL;
          }
     } else {
          gradient_ = NULL;
          objective_ = NULL;
     }
     if (rhs.quadraticObjective_) {
          quadraticObjective_ = new CoinPackedMatrix(*rhs.quadraticObjective_,
                    numberColumns, whichColumn,
                    numberColumns, whichColumn);
     } else {
          quadraticObjective_ = NULL;
     }
}

//-------------------------------------------------------------------
// Destructor
//-------------------------------------------------------------------
ClpQuadraticObjective::~ClpQuadraticObjective ()
{
     delete [] objective_;
     delete [] gradient_;
     delete quadraticObjective_;
}

//----------------------------------------------------------------
// Assignment operator
//-------------------------------------------------------------------
ClpQuadraticObjective &
ClpQuadraticObjective::operator=(const ClpQuadraticObjective& rhs)
{
     if (this != &rhs) {
          fullMatrix_ = rhs.fullMatrix_;
          delete quadraticObjective_;
          quadraticObjective_ = NULL;
          delete [] objective_;
          delete [] gradient_;
          ClpObjective::operator=(rhs);
          numberColumns_ = rhs.numberColumns_;
          numberExtendedColumns_ = rhs.numberExtendedColumns_;
          if (rhs.objective_) {
               objective_ = new double [numberExtendedColumns_];
               CoinMemcpyN(rhs.objective_, numberExtendedColumns_, objective_);
          } else {
               objective_ = NULL;
          }
          if (rhs.gradient_) {
               gradient_ = new double [numberExtendedColumns_];
               CoinMemcpyN(rhs.gradient_, numberExtendedColumns_, gradient_);
          } else {
               gradient_ = NULL;
          }
          if (rhs.quadraticObjective_) {
               quadraticObjective_ = new CoinPackedMatrix(*rhs.quadraticObjective_);
          } else {
               quadraticObjective_ = NULL;
          }
     }
     return *this;
}

// Returns gradient
double *
ClpQuadraticObjective::gradient(const ClpSimplex * model,
                                const double * solution, double & offset, bool refresh,
                                int includeLinear)
{
     offset = 0.0;
     bool scaling = false;
     if (model && (model->rowScale() ||
                   model->objectiveScale() != 1.0 || model->optimizationDirection() != 1.0))
          scaling = true;
     const double * cost = NULL;
     if (model)
          cost = model->costRegion();
     if (!cost) {
          // not in solve
          cost = objective_;
          scaling = false;
     }
     if (!scaling) {
          if (!quadraticObjective_ || !solution || !activated_) {
               return objective_;
          } else {
               if (refresh || !gradient_) {
                    if (!gradient_)
                         gradient_ = new double[numberExtendedColumns_];
                    const int * columnQuadratic = quadraticObjective_->getIndices();
                    const CoinBigIndex * columnQuadraticStart = quadraticObjective_->getVectorStarts();
                    const int * columnQuadraticLength = quadraticObjective_->getVectorLengths();
                    const double * quadraticElement = quadraticObjective_->getElements();
                    offset = 0.0;
                    // use current linear cost region
                    if (includeLinear == 1)
                         CoinMemcpyN(cost, numberExtendedColumns_, gradient_);
                    else if (includeLinear == 2)
                         CoinMemcpyN(objective_, numberExtendedColumns_, gradient_);
                    else
                         memset(gradient_, 0, numberExtendedColumns_ * sizeof(double));
                    if (activated_) {
                         if (!fullMatrix_) {
                              int iColumn;
                              for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
                                   double valueI = solution[iColumn];
                                   CoinBigIndex j;
                                   for (j = columnQuadraticStart[iColumn];
                                             j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                                        int jColumn = columnQuadratic[j];
                                        double valueJ = solution[jColumn];
                                        double elementValue = quadraticElement[j];
                                        if (iColumn != jColumn) {
                                             offset += valueI * valueJ * elementValue;
                                             //if (fabs(valueI*valueJ*elementValue)>1.0e-12)
                                             //printf("%d %d %g %g %g -> %g\n",
                                             //       iColumn,jColumn,valueI,valueJ,elementValue,
                                             //       valueI*valueJ*elementValue);
                                             double gradientI = valueJ * elementValue;
                                             double gradientJ = valueI * elementValue;
                                             gradient_[iColumn] += gradientI;
                                             gradient_[jColumn] += gradientJ;
                                        } else {
                                             offset += 0.5 * valueI * valueI * elementValue;
                                             //if (fabs(valueI*valueI*elementValue)>1.0e-12)
                                             //printf("XX %d %g %g -> %g\n",
                                             //       iColumn,valueI,elementValue,
                                             //       0.5*valueI*valueI*elementValue);
                                             double gradientI = valueI * elementValue;
                                             gradient_[iColumn] += gradientI;
                                        }
                                   }
                              }
                         } else {
                              // full matrix
                              int iColumn;
                              offset *= 2.0;
                              for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
                                   CoinBigIndex j;
                                   double value = 0.0;
                                   double current = gradient_[iColumn];
                                   for (j = columnQuadraticStart[iColumn];
                                             j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                                        int jColumn = columnQuadratic[j];
                                        double valueJ = solution[jColumn] * quadraticElement[j];
                                        value += valueJ;
                                   }
                                   offset += value * solution[iColumn];
                                   gradient_[iColumn] = current + value;
                              }
                              offset *= 0.5;
                         }
                    }
               }
               if (model)
                    offset *= model->optimizationDirection() * model->objectiveScale();
               return gradient_;
          }
     } else {
          // do scaling
          assert (solution);
          // for now only if half
          assert (!fullMatrix_);
          if (refresh || !gradient_) {
               if (!gradient_)
                    gradient_ = new double[numberExtendedColumns_];
               double direction = model->optimizationDirection() * model->objectiveScale();
               // direction is actually scale out not scale in
               //if (direction)
               //direction = 1.0/direction;
               const int * columnQuadratic = quadraticObjective_->getIndices();
               const CoinBigIndex * columnQuadraticStart = quadraticObjective_->getVectorStarts();
               const int * columnQuadraticLength = quadraticObjective_->getVectorLengths();
               const double * quadraticElement = quadraticObjective_->getElements();
               int iColumn;
               const double * columnScale = model->columnScale();
               // use current linear cost region (already scaled)
               if (includeLinear == 1) {
                    CoinMemcpyN(model->costRegion(), numberExtendedColumns_, gradient_);
               }	else if (includeLinear == 2) {
                    memset(gradient_ + numberColumns_, 0, (numberExtendedColumns_ - numberColumns_)*sizeof(double));
                    if (!columnScale) {
                         for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
                              gradient_[iColumn] = objective_[iColumn] * direction;
                         }
                    } else {
                         for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
                              gradient_[iColumn] = objective_[iColumn] * direction * columnScale[iColumn];
                         }
                    }
               } else {
                    memset(gradient_, 0, numberExtendedColumns_ * sizeof(double));
               }
               if (!columnScale) {
                    if (activated_) {
                         for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
                              double valueI = solution[iColumn];
                              CoinBigIndex j;
                              for (j = columnQuadraticStart[iColumn];
                                        j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                                   int jColumn = columnQuadratic[j];
                                   double valueJ = solution[jColumn];
                                   double elementValue = quadraticElement[j];
                                   elementValue *= direction;
                                   if (iColumn != jColumn) {
                                        offset += valueI * valueJ * elementValue;
                                        double gradientI = valueJ * elementValue;
                                        double gradientJ = valueI * elementValue;
                                        gradient_[iColumn] += gradientI;
                                        gradient_[jColumn] += gradientJ;
                                   } else {
                                        offset += 0.5 * valueI * valueI * elementValue;
                                        double gradientI = valueI * elementValue;
                                        gradient_[iColumn] += gradientI;
                                   }
                              }
                         }
                    }
               } else {
                    // scaling
                    if (activated_) {
                         for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
                              double valueI = solution[iColumn];
                              double scaleI = columnScale[iColumn] * direction;
                              CoinBigIndex j;
                              for (j = columnQuadraticStart[iColumn];
                                        j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                                   int jColumn = columnQuadratic[j];
                                   double valueJ = solution[jColumn];
                                   double elementValue = quadraticElement[j];
                                   double scaleJ = columnScale[jColumn];
                                   elementValue *= scaleI * scaleJ;
                                   if (iColumn != jColumn) {
                                        offset += valueI * valueJ * elementValue;
                                        double gradientI = valueJ * elementValue;
                                        double gradientJ = valueI * elementValue;
                                        gradient_[iColumn] += gradientI;
                                        gradient_[jColumn] += gradientJ;
                                   } else {
                                        offset += 0.5 * valueI * valueI * elementValue;
                                        double gradientI = valueI * elementValue;
                                        gradient_[iColumn] += gradientI;
                                   }
                              }
                         }
                    }
               }
          }
          if (model)
               offset *= model->optimizationDirection();
          return gradient_;
     }
}

//-------------------------------------------------------------------
// Clone
//-------------------------------------------------------------------
ClpObjective * ClpQuadraticObjective::clone() const
{
     return new ClpQuadraticObjective(*this);
}
/* Subset clone.  Duplicates are allowed
   and order is as given.
*/
ClpObjective *
ClpQuadraticObjective::subsetClone (int numberColumns,
                                    const int * whichColumns) const
{
     return new ClpQuadraticObjective(*this, numberColumns, whichColumns);
}
// Resize objective
void
ClpQuadraticObjective::resize(int newNumberColumns)
{
     if (numberColumns_ != newNumberColumns) {
          int newExtended = newNumberColumns + (numberExtendedColumns_ - numberColumns_);
          int i;
          double * newArray = new double[newExtended];
          if (objective_)
               CoinMemcpyN(objective_,	CoinMin(newExtended, numberExtendedColumns_), newArray);
          delete [] objective_;
          objective_ = newArray;
          for (i = numberColumns_; i < newNumberColumns; i++)
               objective_[i] = 0.0;
          if (gradient_) {
               newArray = new double[newExtended];
               if (gradient_)
                    CoinMemcpyN(gradient_,	CoinMin(newExtended, numberExtendedColumns_), newArray);
               delete [] gradient_;
               gradient_ = newArray;
               for (i = numberColumns_; i < newNumberColumns; i++)
                    gradient_[i] = 0.0;
          }
          if (quadraticObjective_) {
               if (newNumberColumns < numberColumns_) {
                    int * which = new int[numberColumns_-newNumberColumns];
                    int i;
                    for (i = newNumberColumns; i < numberColumns_; i++)
                         which[i-newNumberColumns] = i;
                    quadraticObjective_->deleteRows(numberColumns_ - newNumberColumns, which);
                    quadraticObjective_->deleteCols(numberColumns_ - newNumberColumns, which);
                    delete [] which;
               } else {
                    quadraticObjective_->setDimensions(newNumberColumns, newNumberColumns);
               }
          }
          numberColumns_ = newNumberColumns;
          numberExtendedColumns_ = newExtended;
     }

}
// Delete columns in  objective
void
ClpQuadraticObjective::deleteSome(int numberToDelete, const int * which)
{
     int newNumberColumns = numberColumns_ - numberToDelete;
     int newExtended = numberExtendedColumns_ - numberToDelete;
     if (objective_) {
          int i ;
          char * deleted = new char[numberColumns_];
          int numberDeleted = 0;
          memset(deleted, 0, numberColumns_ * sizeof(char));
          for (i = 0; i < numberToDelete; i++) {
               int j = which[i];
               if (j >= 0 && j < numberColumns_ && !deleted[j]) {
                    numberDeleted++;
                    deleted[j] = 1;
               }
          }
          newNumberColumns = numberColumns_ - numberDeleted;
          newExtended = numberExtendedColumns_ - numberDeleted;
          double * newArray = new double[newExtended];
          int put = 0;
          for (i = 0; i < numberColumns_; i++) {
               if (!deleted[i]) {
                    newArray[put++] = objective_[i];
               }
          }
          delete [] objective_;
          objective_ = newArray;
          delete [] deleted;
          CoinMemcpyN(objective_ + numberColumns_,	(numberExtendedColumns_ - numberColumns_),
                      objective_ + newNumberColumns);
     }
     if (gradient_) {
          int i ;
          char * deleted = new char[numberColumns_];
          int numberDeleted = 0;
          memset(deleted, 0, numberColumns_ * sizeof(char));
          for (i = 0; i < numberToDelete; i++) {
               int j = which[i];
               if (j >= 0 && j < numberColumns_ && !deleted[j]) {
                    numberDeleted++;
                    deleted[j] = 1;
               }
          }
          newNumberColumns = numberColumns_ - numberDeleted;
          newExtended = numberExtendedColumns_ - numberDeleted;
          double * newArray = new double[newExtended];
          int put = 0;
          for (i = 0; i < numberColumns_; i++) {
               if (!deleted[i]) {
                    newArray[put++] = gradient_[i];
               }
          }
          delete [] gradient_;
          gradient_ = newArray;
          delete [] deleted;
          CoinMemcpyN(gradient_ + numberColumns_,	(numberExtendedColumns_ - numberColumns_),
                      gradient_ + newNumberColumns);
     }
     numberColumns_ = newNumberColumns;
     numberExtendedColumns_ = newExtended;
     if (quadraticObjective_) {
          quadraticObjective_->deleteCols(numberToDelete, which);
          quadraticObjective_->deleteRows(numberToDelete, which);
     }
}

// Load up quadratic objective
void
ClpQuadraticObjective::loadQuadraticObjective(const int numberColumns, const CoinBigIndex * start,
          const int * column, const double * element, int numberExtended)
{
     fullMatrix_ = false;
     delete quadraticObjective_;
     quadraticObjective_ = new CoinPackedMatrix(true, numberColumns, numberColumns,
               start[numberColumns], element, column, start, NULL);
     numberColumns_ = numberColumns;
     if (numberExtended > numberExtendedColumns_) {
          if (objective_) {
               // make correct size
               double * newArray = new double[numberExtended];
               CoinMemcpyN(objective_, numberColumns_, newArray);
               delete [] objective_;
               objective_ = newArray;
               memset(objective_ + numberColumns_, 0, (numberExtended - numberColumns_)*sizeof(double));
          }
          if (gradient_) {
               // make correct size
               double * newArray = new double[numberExtended];
               CoinMemcpyN(gradient_, numberColumns_, newArray);
               delete [] gradient_;
               gradient_ = newArray;
               memset(gradient_ + numberColumns_, 0, (numberExtended - numberColumns_)*sizeof(double));
          }
          numberExtendedColumns_ = numberExtended;
     } else {
          numberExtendedColumns_ = numberColumns_;
     }
}
void
ClpQuadraticObjective::loadQuadraticObjective (  const CoinPackedMatrix& matrix)
{
     delete quadraticObjective_;
     quadraticObjective_ = new CoinPackedMatrix(matrix);
}
// Get rid of quadratic objective
void
ClpQuadraticObjective::deleteQuadraticObjective()
{
     delete quadraticObjective_;
     quadraticObjective_ = NULL;
}
/* Returns reduced gradient.Returns an offset (to be added to current one).
 */
double
ClpQuadraticObjective::reducedGradient(ClpSimplex * model, double * region,
                                       bool useFeasibleCosts)
{
     int numberRows = model->numberRows();
     int numberColumns = model->numberColumns();

     //work space
     CoinIndexedVector  * workSpace = model->rowArray(0);

     CoinIndexedVector arrayVector;
     arrayVector.reserve(numberRows + 1);

     int iRow;
#ifdef CLP_DEBUG
     workSpace->checkClear();
#endif
     double * array = arrayVector.denseVector();
     int * index = arrayVector.getIndices();
     int number = 0;
     const double * costNow = gradient(model, model->solutionRegion(), offset_,
                                       true, useFeasibleCosts ? 2 : 1);
     double * cost = model->costRegion();
     const int * pivotVariable = model->pivotVariable();
     for (iRow = 0; iRow < numberRows; iRow++) {
          int iPivot = pivotVariable[iRow];
          double value;
          if (iPivot < numberColumns)
               value = costNow[iPivot];
          else if (!useFeasibleCosts)
               value = cost[iPivot];
          else
               value = 0.0;
          if (value) {
               array[iRow] = value;
               index[number++] = iRow;
          }
     }
     arrayVector.setNumElements(number);

     // Btran basic costs
     model->factorization()->updateColumnTranspose(workSpace, &arrayVector);
     double * work = workSpace->denseVector();
     ClpFillN(work, numberRows, 0.0);
     // now look at dual solution
     double * rowReducedCost = region + numberColumns;
     double * dual = rowReducedCost;
     const double * rowCost = cost + numberColumns;
     for (iRow = 0; iRow < numberRows; iRow++) {
          dual[iRow] = array[iRow];
     }
     double * dj = region;
     ClpDisjointCopyN(costNow, numberColumns, dj);

     model->transposeTimes(-1.0, dual, dj);
     for (iRow = 0; iRow < numberRows; iRow++) {
          // slack
          double value = dual[iRow];
          value += rowCost[iRow];
          rowReducedCost[iRow] = value;
     }
     return offset_;
}
/* Returns step length which gives minimum of objective for
   solution + theta * change vector up to maximum theta.

   arrays are numberColumns+numberRows
*/
double
ClpQuadraticObjective::stepLength(ClpSimplex * model,
                                  const double * solution,
                                  const double * change,
                                  double maximumTheta,
                                  double & currentObj,
                                  double & predictedObj,
                                  double & thetaObj)
{
     const double * cost = model->costRegion();
     bool inSolve = true;
     if (!cost) {
          // not in solve
          cost = objective_;
          inSolve = false;
     }
     double delta = 0.0;
     double linearCost = 0.0;
     int numberRows = model->numberRows();
     int numberColumns = model->numberColumns();
     int numberTotal = numberColumns;
     if (inSolve)
          numberTotal += numberRows;
     currentObj = 0.0;
     thetaObj = 0.0;
     for (int iColumn = 0; iColumn < numberTotal; iColumn++) {
          delta += cost[iColumn] * change[iColumn];
          linearCost += cost[iColumn] * solution[iColumn];
     }
     if (!activated_ || !quadraticObjective_) {
          currentObj = linearCost;
          thetaObj = currentObj + delta * maximumTheta;
          if (delta < 0.0) {
               return maximumTheta;
          } else {
	    COIN_DETAIL_PRINT(printf("odd linear direction %g\n", delta));
               return 0.0;
          }
     }
     assert (model);
     bool scaling = false;
     if ((model->rowScale() ||
               model->objectiveScale() != 1.0 || model->optimizationDirection() != 1.0) && inSolve)
          scaling = true;
     const int * columnQuadratic = quadraticObjective_->getIndices();
     const CoinBigIndex * columnQuadraticStart = quadraticObjective_->getVectorStarts();
     const int * columnQuadraticLength = quadraticObjective_->getVectorLengths();
     const double * quadraticElement = quadraticObjective_->getElements();
     double a = 0.0;
     double b = delta;
     double c = 0.0;
     if (!scaling) {
          if (!fullMatrix_) {
               int iColumn;
               for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
                    double valueI = solution[iColumn];
                    double changeI = change[iColumn];
                    CoinBigIndex j;
                    for (j = columnQuadraticStart[iColumn];
                              j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                         int jColumn = columnQuadratic[j];
                         double valueJ = solution[jColumn];
                         double changeJ = change[jColumn];
                         double elementValue = quadraticElement[j];
                         if (iColumn != jColumn) {
                              a += changeI * changeJ * elementValue;
                              b += (changeI * valueJ + changeJ * valueI) * elementValue;
                              c += valueI * valueJ * elementValue;
                         } else {
                              a += 0.5 * changeI * changeI * elementValue;
                              b += changeI * valueI * elementValue;
                              c += 0.5 * valueI * valueI * elementValue;
                         }
                    }
               }
          } else {
               // full matrix stored
               int iColumn;
               for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
                    double valueI = solution[iColumn];
                    double changeI = change[iColumn];
                    CoinBigIndex j;
                    for (j = columnQuadraticStart[iColumn];
                              j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                         int jColumn = columnQuadratic[j];
                         double valueJ = solution[jColumn];
                         double changeJ = change[jColumn];
                         double elementValue = quadraticElement[j];
                         valueJ *= elementValue;
                         a += changeI * changeJ * elementValue;
                         b += changeI * valueJ;
                         c += valueI * valueJ;
                    }
               }
               a *= 0.5;
               c *= 0.5;
          }
     } else {
          // scaling
          // for now only if half
          assert (!fullMatrix_);
          const double * columnScale = model->columnScale();
          double direction = model->optimizationDirection() * model->objectiveScale();
          // direction is actually scale out not scale in
          if (direction)
               direction = 1.0 / direction;
          if (!columnScale) {
               for (int iColumn = 0; iColumn < numberColumns_; iColumn++) {
                    double valueI = solution[iColumn];
                    double changeI = change[iColumn];
                    CoinBigIndex j;
                    for (j = columnQuadraticStart[iColumn];
                              j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                         int jColumn = columnQuadratic[j];
                         double valueJ = solution[jColumn];
                         double changeJ = change[jColumn];
                         double elementValue = quadraticElement[j];
                         elementValue *= direction;
                         if (iColumn != jColumn) {
                              a += changeI * changeJ * elementValue;
                              b += (changeI * valueJ + changeJ * valueI) * elementValue;
                              c += valueI * valueJ * elementValue;
                         } else {
                              a += 0.5 * changeI * changeI * elementValue;
                              b += changeI * valueI * elementValue;
                              c += 0.5 * valueI * valueI * elementValue;
                         }
                    }
               }
          } else {
               // scaling
               for (int iColumn = 0; iColumn < numberColumns_; iColumn++) {
                    double valueI = solution[iColumn];
                    double changeI = change[iColumn];
                    double scaleI = columnScale[iColumn] * direction;
                    CoinBigIndex j;
                    for (j = columnQuadraticStart[iColumn];
                              j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                         int jColumn = columnQuadratic[j];
                         double valueJ = solution[jColumn];
                         double changeJ = change[jColumn];
                         double elementValue = quadraticElement[j];
                         elementValue *= scaleI * columnScale[jColumn];
                         if (iColumn != jColumn) {
                              a += changeI * changeJ * elementValue;
                              b += (changeI * valueJ + changeJ * valueI) * elementValue;
                              c += valueI * valueJ * elementValue;
                         } else {
                              a += 0.5 * changeI * changeI * elementValue;
                              b += changeI * valueI * elementValue;
                              c += 0.5 * valueI * valueI * elementValue;
                         }
                    }
               }
          }
     }
     double theta;
     //printf("Current cost %g\n",c+linearCost);
     currentObj = c + linearCost;
     thetaObj = currentObj + a * maximumTheta * maximumTheta + b * maximumTheta;
     // minimize a*x*x + b*x + c
     if (a <= 0.0) {
          theta = maximumTheta;
     } else {
          theta = -0.5 * b / a;
     }
     predictedObj = currentObj + a * theta * theta + b * theta;
     if (b > 0.0) {
          if (model->messageHandler()->logLevel() & 32)
               printf("a %g b %g c %g => %g\n", a, b, c, theta);
          b = 0.0;
     }
     return CoinMin(theta, maximumTheta);
}
// Return objective value (without any ClpModel offset) (model may be NULL)
double
ClpQuadraticObjective::objectiveValue(const ClpSimplex * model, const double * solution) const
{
     bool scaling = false;
     if (model && (model->rowScale() ||
                   model->objectiveScale() != 1.0))
          scaling = true;
     const double * cost = NULL;
     if (model)
          cost = model->costRegion();
     if (!cost) {
          // not in solve
          cost = objective_;
          scaling = false;
     }
     double linearCost = 0.0;
     int numberColumns = model->numberColumns();
     int numberTotal = numberColumns;
     double currentObj = 0.0;
     for (int iColumn = 0; iColumn < numberTotal; iColumn++) {
          linearCost += cost[iColumn] * solution[iColumn];
     }
     if (!activated_ || !quadraticObjective_) {
          currentObj = linearCost;
          return currentObj;
     }
     assert (model);
     const int * columnQuadratic = quadraticObjective_->getIndices();
     const CoinBigIndex * columnQuadraticStart = quadraticObjective_->getVectorStarts();
     const int * columnQuadraticLength = quadraticObjective_->getVectorLengths();
     const double * quadraticElement = quadraticObjective_->getElements();
     double c = 0.0;
     if (!scaling) {
          if (!fullMatrix_) {
               int iColumn;
               for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
                    double valueI = solution[iColumn];
                    CoinBigIndex j;
                    for (j = columnQuadraticStart[iColumn];
                              j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                         int jColumn = columnQuadratic[j];
                         double valueJ = solution[jColumn];
                         double elementValue = quadraticElement[j];
                         if (iColumn != jColumn) {
                              c += valueI * valueJ * elementValue;
                         } else {
                              c += 0.5 * valueI * valueI * elementValue;
                         }
                    }
               }
          } else {
               // full matrix stored
               int iColumn;
               for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
                    double valueI = solution[iColumn];
                    CoinBigIndex j;
                    for (j = columnQuadraticStart[iColumn];
                              j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                         int jColumn = columnQuadratic[j];
                         double valueJ = solution[jColumn];
                         double elementValue = quadraticElement[j];
                         valueJ *= elementValue;
                         c += valueI * valueJ;
                    }
               }
               c *= 0.5;
          }
     } else {
          // scaling
          // for now only if half
          assert (!fullMatrix_);
          const double * columnScale = model->columnScale();
          double direction = model->objectiveScale();
          // direction is actually scale out not scale in
          if (direction)
               direction = 1.0 / direction;
          if (!columnScale) {
               for (int iColumn = 0; iColumn < numberColumns_; iColumn++) {
                    double valueI = solution[iColumn];
                    CoinBigIndex j;
                    for (j = columnQuadraticStart[iColumn];
                              j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                         int jColumn = columnQuadratic[j];
                         double valueJ = solution[jColumn];
                         double elementValue = quadraticElement[j];
                         elementValue *= direction;
                         if (iColumn != jColumn) {
                              c += valueI * valueJ * elementValue;
                         } else {
                              c += 0.5 * valueI * valueI * elementValue;
                         }
                    }
               }
          } else {
               // scaling
               for (int iColumn = 0; iColumn < numberColumns_; iColumn++) {
                    double valueI = solution[iColumn];
                    double scaleI = columnScale[iColumn] * direction;
                    CoinBigIndex j;
                    for (j = columnQuadraticStart[iColumn];
                              j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
                         int jColumn = columnQuadratic[j];
                         double valueJ = solution[jColumn];
                         double elementValue = quadraticElement[j];
                         elementValue *= scaleI * columnScale[jColumn];
                         if (iColumn != jColumn) {
                              c += valueI * valueJ * elementValue;
                         } else {
                              c += 0.5 * valueI * valueI * elementValue;
                         }
                    }
               }
          }
     }
     currentObj = c + linearCost;
     return currentObj;
}
// Scale objective
void
ClpQuadraticObjective::reallyScale(const double * columnScale)
{
     const int * columnQuadratic = quadraticObjective_->getIndices();
     const CoinBigIndex * columnQuadraticStart = quadraticObjective_->getVectorStarts();
     const int * columnQuadraticLength = quadraticObjective_->getVectorLengths();
     double * quadraticElement = quadraticObjective_->getMutableElements();
     for (int iColumn = 0; iColumn < numberColumns_; iColumn++) {
          double scaleI = columnScale[iColumn];
          objective_[iColumn] *= scaleI;
          CoinBigIndex j;
          for (j = columnQuadraticStart[iColumn];
                    j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
               int jColumn = columnQuadratic[j];
               quadraticElement[j] *= scaleI * columnScale[jColumn];
          }
     }
}
/* Given a zeroed array sets nonlinear columns to 1.
   Returns number of nonlinear columns
*/
int
ClpQuadraticObjective::markNonlinear(char * which)
{
     int iColumn;
     const int * columnQuadratic = quadraticObjective_->getIndices();
     const CoinBigIndex * columnQuadraticStart = quadraticObjective_->getVectorStarts();
     const int * columnQuadraticLength = quadraticObjective_->getVectorLengths();
     for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
          CoinBigIndex j;
          for (j = columnQuadraticStart[iColumn];
                    j < columnQuadraticStart[iColumn] + columnQuadraticLength[iColumn]; j++) {
               int jColumn = columnQuadratic[j];
               which[jColumn] = 1;
               which[iColumn] = 1;
          }
     }
     int numberNonLinearColumns = 0;
     for (iColumn = 0; iColumn < numberColumns_; iColumn++) {
          if(which[iColumn])
               numberNonLinearColumns++;
     }
     return numberNonLinearColumns;
}


text:
/*
 * Start of xa.h header
 *
 * This file as per:
 *   The Open Group, Technical Standard
 *   Distributed Transaction Processing: The XA Specification
 *
 * Define a symbol to prevent multiple inclusions of this header file
 */
#ifndef XA_H
#define XA_H
/*
 * Transaction branch identification: XID and NULLXID:
 */
#define XIDDATASIZE	128	/* size in bytes */
#define MAXGTRIDSIZE	64	/* maximum size in bytes of gtrid */
#define MAXBQUALSIZE	64	/* maximum size in bytes of bqual */
struct xid_t {
	long formatID;		/* format identifier */
	long gtrid_length;	/* value from 1 through 64 */
	long bqual_length;	/* value from 1 through 64 */
	char data[XIDDATASIZE];
};
typedef struct xid_t XID;
/*
 * A value of -1 in formatID means that the XID is null.
 */
/*
 * Declarations of routines by which RMs call TMs:
 */
#ifdef __STDC__
extern int ax_reg(int, XID *, long);
extern int ax_unreg(int, long);
#else /* ifndef __STDC__ */
extern int ax_reg();
extern int ax_unreg();
#endif /* ifndef __STDC__ */
/*
 * XA Switch Data Structure
 */
#define RMNAMESZ	32	/* length of resource manager name, */
				/* including the null terminator */
#define MAXINFOSIZE	256	/* maximum size in bytes of xa_info */
				/* strings, including the null terminator*/
struct xa_switch_t {
	char name[RMNAMESZ];	/* name of resource manager */
	long flags;	/* options specific to the resource manager */
	long version;	/* must be 0 */
#ifdef __STDC__
	int (*xa_open_entry)(char *, int, long);		/* xa_open function pointer*/
	int (*xa_close_entry)(char *, int, long);		/* xa_close function pointer*/
	int (*xa_start_entry)(XID *, int, long);		/* xa_start function pointer*/
	int (*xa_end_entry)(XID *, int, long);			/* xa_end function pointer*/
	int (*xa_rollback_entry)(XID *, int, long);		/* xa_rollback function pointer*/
	int (*xa_prepare_entry)(XID *, int, long);		/* xa_prepare function pointer*/
	int (*xa_commit_entry)(XID *, int, long);		/* xa_commit function pointer*/
	int (*xa_recover_entry)(XID *, long, int, long);	/* xa_recover function pointer*/
	int (*xa_forget_entry)(XID *, int, long);		/* xa_forget function pointer*/
	int (*xa_complete_entry)(int *, int *, int, long);	/* xa_complete function pointer*/
#else /* ifndef __STDC__ */
	int (*xa_open_entry)();		/* xa_open function pointer */
	int (*xa_close_entry)();	/* xa_close function pointer */
	int (*xa_start_entry)();	/* xa_start function pointer */
	int (*xa_end_entry)();		/* xa_end function pointer */
	int (*xa_rollback_entry)();	/* xa_rollback function pointer*/
	int (*xa_prepare_entry)();	/* xa_prepare function pointer */
	int (*xa_commit_entry)();	/* xa_commit function pointer */
	int (*xa_recover_entry)();	/* xa_recover function pointer */
	int (*xa_forget_entry)();	/* xa_forget function pointer */
	int (*xa_complete_entry)();	/* xa_complete function pointer*/
#endif /* ifndef __STDC__ */
};
/*
 * Flag definitions for the RM switch
 */
#define TMNOFLAGS	0x00000000L	/* no resource manager features selected */
#define TMREGISTER	0x00000001L	/* resource manager dynamically registers */
#define TMNOMIGRATE	0x00000002L	/* resource manager does not support association migration */
#define TMUSEASYNC	0x00000004L	/* resource manager supports asynchronous operations */
/*
 * Flag definitions for xa_ and ax_ routines
 */
/* use TMNOFLAGS, defined above, when not specifying other flags */
#define TMASYNC		0x80000000L	/* perform routine asynchronously */
#define TMONEPHASE	0x40000000L	/* caller is using one-phase commit optimisation */
#define TMFAIL		0x20000000L	/* dissociates caller and marks transaction branch rollback-only */
#define TMNOWAIT	0x10000000L	/* return if blocking condition exists */
#define TMRESUME	0x08000000L	/* caller is resuming association with suspended transaction branch */
#define TMSUCCESS	0x04000000L	/* dissociate caller from transaction branch*/
#define TMSUSPEND	0x02000000L	/* caller is suspending, not ending, association */
#define TMSTARTRSCAN	0x01000000L	/* start a recovery scan */
#define TMENDRSCAN	0x00800000L	/* end a recovery scan */
#define TMMULTIPLE	0x00400000L	/* wait for any asynchronous operation */
#define TMJOIN		0x00200000L	/* caller is joining existing transaction branch */
#define TMMIGRATE	0x00100000L	/* caller intends to perform migration */
/*
 * ax_() return codes (transaction manager reports to resource manager)
 */
#define TM_JOIN		2	/* caller is joining existing transaction branch */
#define TM_RESUME	1	/* caller is resuming association with suspended transaction branch */
#define TM_OK		0	/* normal execution */
#define TMER_TMERR	-1	/* an error occurred in the transaction manager */
#define TMER_INVAL	-2	/* invalid arguments were given */
#define TMER_PROTO	-3	/* routine invoked in an improper context */
/*
 * xa_() return codes (resource manager reports to transaction manager)
 */
#define XA_RBBASE	100	/* the inclusive lower bound of the rollback codes */
#define XA_RBROLLBACK	XA_RBBASE	/* the rollback was caused by an unspecified reason */
#define XA_RBCOMMFAIL	XA_RBBASE+1	/* the rollback was caused by a communication failure */
#define XA_RBDEADLOCK	XA_RBBASE+2	/* a deadlock was detected */
#define XA_RBINTEGRITY	XA_RBBASE+3	/* a condition that violates the integrity of the resources was detected */
#define XA_RBOTHER	XA_RBBASE+4	/* the resource manager rolled back the transaction branch for a reason not on this list */
#define XA_RBPROTO	XA_RBBASE+5	/* a protocol error occurred in the resource manager */
#define XA_RBTIMEOUT	XA_RBBASE+6	/* a transaction branch took too long */
#define XA_RBTRANSIENT	XA_RBBASE+7	/* may retry the transaction branch */
#define XA_RBEND	XA_RBTRANSIENT	/* the inclusive upper bound of the rollback codes */
#define XA_NOMIGRATE	9	/* resumption must occur where suspension occurred */
#define XA_HEURHAZ	8	/* the transaction branch may have been heuristically completed */
#define XA_HEURCOM	7	/* the transaction branch has been heuristically committed */
#define XA_HEURRB	6	/* the transaction branch has been heuristically rolled back */
#define XA_HEURMIX	5	/* the transaction branch has been heuristically committed and rolled back */
#define XA_RETRY	4	/* routine returned with no effect and may be reissued */
#define XA_RDONLY	3	/* the transaction branch was read-only and has been committed */
#define XA_OK		0	/* normal execution */
#define XAER_ASYNC	-2	/* asynchronous operation already outstanding */
#define XAER_RMERR	-3	/* a resource manager error occurred in the transaction branch */
#define XAER_NOTA	-4	/* the XID is not valid */
#define XAER_INVAL	-5	/* invalid arguments were given */
#define XAER_PROTO	-6	/* routine invoked in an improper context */
#define XAER_RMFAIL	-7	/* resource manager unavailable */
#define XAER_DUPID	-8	/* the XID already exists */
#define XAER_OUTSIDE	-9	/* resource manager doing work outside */
/* global transaction */
#endif /* ifndef XA_H */
/*
 * End of xa.h header
 */


text:
using System.IO;
using SharpCompress.Common;
using SharpCompress.Readers;

namespace Ductus.FluentDocker.Extensions
{
  public static class CompressionExtensions
  {
    public static void UnTar(this string file, string destPath)
    {
      using (var stream = File.OpenRead(file))
      {
        using (var reader = ReaderFactory.Open(stream))
        {
          while (reader.MoveToNextEntry())
          {
            if (!reader.Entry.IsDirectory)
            {
              reader.WriteEntryToDirectory(destPath, new ExtractionOptions { ExtractFullPath = true, Overwrite = true });
            }
          }
        }
      }
    }
  }
}