text:
package io.fabric8.kubernetes.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.kubernetes.api.model.base.Status;
import io.fabric8.utils.IOHelpers;
import io.fabric8.utils.Strings;
import org.apache.cxf.jaxrs.client.ResponseExceptionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;

public class ExceptionResponseMapper implements ResponseExceptionMapper<Exception> {
    private static final transient Logger LOG = LoggerFactory.getLogger(ExceptionResponseMapper.class);

    @Override
    public Exception fromResponse(Response response) {
        try {
            Object entity = response.getEntity();
            String message = extractErrorMessage(entity);
            message = "HTTP " + response.getStatus() + " " + message;
            return new WebApplicationException(message, response);
        } catch (Exception ex) {
            return new Exception(
                    "Could not deserialize server side exception: " + ex.getMessage());
        }
    }

    public static String extractErrorMessage(Object entity) {
        String message = "No message";
        ObjectMapper mapper = KubernetesFactory.createObjectMapper();
        try {
            String json = null;
            if (entity instanceof InputStream) {
                InputStream inputStream = (InputStream) entity;
                json = IOHelpers.readFully(inputStream);
            } else if (entity != null) {
                json = entity.toString();
            }
            if (Strings.isNotBlank(json)) {
                message = json;
                if (textLooksLikeJsonObject(json)) {
                    try {
                        Status error = mapper.readValue(json, Status.class);
                        if (error != null) {
                            message = error.getMessage();
                            if (Strings.isNullOrBlank(message)) {
                                message = error.getReason();
                            }
                        }
                    } catch (IOException e) {
                        LOG.warn("Failed to parse Status from JSON:" + json + ". Reason: " + e, e);
                    }
                }
            }
        } catch (Exception e) {
            message = "Failed to extract message from request: " + e;
        }
        return message;
    }

    protected static boolean textLooksLikeJsonObject(String text) {
        text = text.trim();
        return text.startsWith("{") && text.endsWith("}");
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.chipsolutions.cartodbapi;

/**
 *
 * @author luis
 */
public class CbImportStatus {
    public String id;
    public String user_id;
    public String table_id;
    public String data_type;//	file, url, external_table, query, table or datasource.
    public String table_name;
    public String state;// enqueued, pending, uploading, unpacking, importing, guessing, complete, or failure.
    public String error_code;//
    public String queue_id;
    public String tables_created_count;
    public String synchronization_id;
    public boolean type_guessing;
    public boolean quoted_fields_guessing;
    public boolean content_guessing;
    public boolean create_visualization;
    public String visualization_id;
    public String user_defined_limits;
    public CbErrorText get_error_text;
    public String display_name;
    public boolean success;
    public String warnings;
    public boolean is_raster;
}

redpajama_set_name: RedPajamaGithub


text:
001
018    package org.apache.hadoop.hdfs.server.datanode.fsdataset;
019
020    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_THRESHOLD_DEFAULT;
021    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_THRESHOLD_KEY;
022    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_DEFAULT;
023    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_KEY;
024
025    import java.io.IOException;
026    import java.util.ArrayList;
027    import java.util.List;
028    import java.util.Random;
029
030    import org.apache.commons.logging.Log;
031    import org.apache.commons.logging.LogFactory;
032    import org.apache.hadoop.conf.Configurable;
033    import org.apache.hadoop.conf.Configuration;
034    import org.apache.hadoop.util.DiskChecker.DiskOutOfSpaceException;
035
036    /**
037     * A DN volume choosing policy which takes into account the amount of free
038     * space on each of the available volumes when considering where to assign a
039     * new replica allocation. By default this policy prefers assigning replicas to
040     * those volumes with more available free space, so as to over time balance the
041     * available space of all the volumes within a DN.
042     */
043    public class AvailableSpaceVolumeChoosingPolicy<V extends FsVolumeSpi>
044        implements VolumeChoosingPolicy<V>, Configurable {
045
046      private static final Log LOG = LogFactory.getLog(AvailableSpaceVolumeChoosingPolicy.class);
047
048      private static final Random RAND = new Random();
049
050      private long balancedSpaceThreshold = DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_THRESHOLD_DEFAULT;
051      private float balancedPreferencePercent = DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_DEFAULT;
052
053      @Override
054      public synchronized void setConf(Configuration conf) {
055        balancedSpaceThreshold = conf.getLong(
056            DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_THRESHOLD_KEY,
057            DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_THRESHOLD_DEFAULT);
058        balancedPreferencePercent = conf.getFloat(
059            DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_KEY,
060            DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_DEFAULT);
061
062        LOG.info("Available space volume choosing policy initialized: " +
063            DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_THRESHOLD_KEY +
064            " = " + balancedSpaceThreshold + ", " +
065            DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_KEY +
066            " = " + balancedPreferencePercent);
067
068        if (balancedPreferencePercent > 1.0) {
069          LOG.warn("The value of " + DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_KEY +
070                   " is greater than 1.0 but should be in the range 0.0 - 1.0");
071        }
072
073        if (balancedPreferencePercent < 0.5) {
074          LOG.warn("The value of " + DFS_DATANODE_AVAILABLE_SPACE_VOLUME_CHOOSING_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_KEY +
075                   " is less than 0.5 so volumes with less available disk space will receive more block allocations");
076        }
077      }
078
079      @Override
080      public synchronized Configuration getConf() {
081        // Nothing to do. Only added to fulfill the Configurable contract.
082        return null;
083      }
084
085      private VolumeChoosingPolicy<V> roundRobinPolicyBalanced =
086          new RoundRobinVolumeChoosingPolicy<V>();
087      private VolumeChoosingPolicy<V> roundRobinPolicyHighAvailable =
088          new RoundRobinVolumeChoosingPolicy<V>();
089      private VolumeChoosingPolicy<V> roundRobinPolicyLowAvailable =
090          new RoundRobinVolumeChoosingPolicy<V>();
091
092      @Override
093      public synchronized V chooseVolume(List<V> volumes,
094          final long replicaSize) throws IOException {
095        if (volumes.size() < 1) {
096          throw new DiskOutOfSpaceException("No more available volumes");
097        }
098
099        AvailableSpaceVolumeList volumesWithSpaces =
100            new AvailableSpaceVolumeList(volumes);
101
102        if (volumesWithSpaces.areAllVolumesWithinFreeSpaceThreshold()) {
103          // If they're actually not too far out of whack, fall back on pure round
104          // robin.
105          V volume = roundRobinPolicyBalanced.chooseVolume(volumes, replicaSize);
106          if (LOG.isDebugEnabled()) {
107            LOG.debug("All volumes are within the configured free space balance " +
108                "threshold. Selecting " + volume + " for write of block size " +
109                replicaSize);
110          }
111          return volume;
112        } else {
113          V volume = null;
114          // If none of the volumes with low free space have enough space for the
115          // replica, always try to choose a volume with a lot of free space.
116          long mostAvailableAmongLowVolumes = volumesWithSpaces
117              .getMostAvailableSpaceAmongVolumesWithLowAvailableSpace();
118
119          List<V> highAvailableVolumes = extractVolumesFromPairs(
120              volumesWithSpaces.getVolumesWithHighAvailableSpace());
121          List<V> lowAvailableVolumes = extractVolumesFromPairs(
122              volumesWithSpaces.getVolumesWithLowAvailableSpace());
123
124          float preferencePercentScaler =
125              (highAvailableVolumes.size() * balancedPreferencePercent) +
126              (lowAvailableVolumes.size() * (1 - balancedPreferencePercent));
127          float scaledPreferencePercent =
128              (highAvailableVolumes.size() * balancedPreferencePercent) /
129              preferencePercentScaler;
130          if (mostAvailableAmongLowVolumes < replicaSize ||
131              RAND.nextFloat() < scaledPreferencePercent) {
132            volume = roundRobinPolicyHighAvailable.chooseVolume(
133                highAvailableVolumes,
134                replicaSize);
135            if (LOG.isDebugEnabled()) {
136              LOG.debug("Volumes are imbalanced. Selecting " + volume +
137                  " from high available space volumes for write of block size "
138                  + replicaSize);
139            }
140          } else {
141            volume = roundRobinPolicyLowAvailable.chooseVolume(
142                lowAvailableVolumes,
143                replicaSize);
144            if (LOG.isDebugEnabled()) {
145              LOG.debug("Volumes are imbalanced. Selecting " + volume +
146                  " from low available space volumes for write of block size "
147                  + replicaSize);
148            }
149          }
150          return volume;
151        }
152      }
153
154      /**
155       * Used to keep track of the list of volumes we're choosing from.
156       */
157      private class AvailableSpaceVolumeList {
158        private final List<AvailableSpaceVolumePair> volumes;
159
160        public AvailableSpaceVolumeList(List<V> volumes) throws IOException {
161          this.volumes = new ArrayList<AvailableSpaceVolumePair>();
162          for (V volume : volumes) {
163            this.volumes.add(new AvailableSpaceVolumePair(volume));
164          }
165        }
166
167        /**
168         * Check if the available space on all the volumes is roughly equal.
169         *
170         * @param volumes the volumes to check
171         * @return true if all volumes' free space is within the configured threshold,
172         *         false otherwise.
173         * @throws IOException
174         *           in the event of error checking amount of available space
175         */
176        public boolean areAllVolumesWithinFreeSpaceThreshold() {
177          long leastAvailable = Long.MAX_VALUE;
178          long mostAvailable = 0;
179          for (AvailableSpaceVolumePair volume : volumes) {
180            leastAvailable = Math.min(leastAvailable, volume.getAvailable());
181            mostAvailable = Math.max(mostAvailable, volume.getAvailable());
182          }
183          return (mostAvailable - leastAvailable) < balancedSpaceThreshold;
184        }
185
186        /**
187         * @return the minimum amount of space available on a single volume,
188         *         across all volumes.
189         */
190        private long getLeastAvailableSpace() {
191          long leastAvailable = Long.MAX_VALUE;
192          for (AvailableSpaceVolumePair volume : volumes) {
193            leastAvailable = Math.min(leastAvailable, volume.getAvailable());
194          }
195          return leastAvailable;
196        }
197
198        /**
199         * @return the maximum amount of space available across volumes with low space.
200         */
201        public long getMostAvailableSpaceAmongVolumesWithLowAvailableSpace() {
202          long mostAvailable = Long.MIN_VALUE;
203          for (AvailableSpaceVolumePair volume : getVolumesWithLowAvailableSpace()) {
204            mostAvailable = Math.max(mostAvailable, volume.getAvailable());
205          }
206          return mostAvailable;
207        }
208
209        /**
210         * @return the list of volumes with relatively low available space.
211         */
212        public List<AvailableSpaceVolumePair> getVolumesWithLowAvailableSpace() {
213          long leastAvailable = getLeastAvailableSpace();
214          List<AvailableSpaceVolumePair> ret = new ArrayList<AvailableSpaceVolumePair>();
215          for (AvailableSpaceVolumePair volume : volumes) {
216            if (volume.getAvailable() <= leastAvailable + balancedSpaceThreshold) {
217              ret.add(volume);
218            }
219          }
220          return ret;
221        }
222
223        /**
224         * @return the list of volumes with a lot of available space.
225         */
226        public List<AvailableSpaceVolumePair> getVolumesWithHighAvailableSpace() {
227          long leastAvailable = getLeastAvailableSpace();
228          List<AvailableSpaceVolumePair> ret = new ArrayList<AvailableSpaceVolumePair>();
229          for (AvailableSpaceVolumePair volume : volumes) {
230            if (volume.getAvailable() > leastAvailable + balancedSpaceThreshold) {
231              ret.add(volume);
232            }
233          }
234          return ret;
235        }
236
237      }
238
239      /**
240       * Used so that we only check the available space on a given volume once, at
241       * the beginning of {@link AvailableSpaceVolumeChoosingPolicy#chooseVolume(List, long)}.
242       */
243      private class AvailableSpaceVolumePair {
244        private final V volume;
245        private final long availableSpace;
246
247        public AvailableSpaceVolumePair(V volume) throws IOException {
248          this.volume = volume;
249          this.availableSpace = volume.getAvailable();
250        }
251
252        public long getAvailable() {
253          return availableSpace;
254        }
255
256        public V getVolume() {
257          return volume;
258        }
259      }
260
261      private List<V> extractVolumesFromPairs(List<AvailableSpaceVolumePair> volumes) {
262        List<V> ret = new ArrayList<V>();
263        for (AvailableSpaceVolumePair volume : volumes) {
264          ret.add(volume.getVolume());
265        }
266        return ret;
267      }
268
269    }


text:
import parser from 'cheerio-without-node-native'

export default function (html) {

  const $ = parser.load(html, {
    decodeEntities: true
  })

  const list = []
  $('ul[class=dd_ul]').find('li').each(function (i, elem) {
    const $this = $(this)
    const img = $this.find('img').attr('src')
    const text = $this.text()
    const arr = ($this.find('div').first().text() || '').split('\n').map(item => item.trim()).filter(item => item)
    const contentArr = Array.from($this.children('div').last().contents().map(function() {
        return $(this).html() || $(this).text() || ''
      })
    ).map(item => item.trim().replace(/\s+/igm, ' ')).filter(item => item)
    contentArr[contentArr.length - 1] = `<div class="pd10">${contentArr[contentArr.length - 1].replace(/\<\/.*?>/igm, text => text + ' ')}</div>`
    const prevContent = contentArr.join('<br>')
    const storeLink = prevContent.match(/store\(\'(.*?)\',\'(.*?)\'/)
    const isOK = storeLink && storeLink[1] && storeLink[2]
    const onclick = isOK ? `https://psnine.com/store/${storeLink[1]}::${storeLink[2]}` : ''
    const mock = {
      avatar: img,
      platform: arr[0],
      price: arr[1],
      content: prevContent.replace('javascript:void(0)', onclick),
      id: ($this.find('.dd_title a').attr('href') || '').split('/').pop(),
      isOff: $this.find('.dd_status').text(),
      type: 'outter'
    }
    if (!mock.id) {
      mock.id = ($this.find('.dd_info a').attr('href') || '').split('/').pop()
      mock.type = 'inner'
    }
    list.push(mock)
  })
  const games = []
  const matched = html.match(/<title>(.*?)<\/title>/)
  const title = matched ? matched[1] : '游折'
    $('tr').each(function (i, elem) {

    const $this = $(this)
    const img = $this.find('img').attr('src')

    const text = $this.text()
    const arr = text.split('\n').map(item => item.replace(/\t/g, '').trim()).filter(item => item.trim())

    const title = $this.find('td p a').text()
    const matched = img.match(/\/(\d+)\./)

    const id = matched ? matched[1] : arr[1] + arr[2]

    const startIndex = arr.some(item => item.includes('%')) ? -8 : -7
    const regionArr = arr.slice(1, startIndex)
    const trophyArr = arr.slice(startIndex)

    const mock = {
      title: title,
      avatar: img,
      id,
      region: regionArr.join(''),
      platium: trophyArr[1],
      gold: trophyArr[2],
      selver: trophyArr[3],
      bronze: trophyArr[4],
      platform: $this.find('td p span').text()
    }

    games.push(mock)
  })
  return {
    list,
    games,
    title
  }
}


text:
<?php declare(strict_types=1);

namespace PHPUnit\Framework\MockObject\Stub;

use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
use SebastianBergmann\Exporter\Exporter;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 */
final class ReturnStub implements Stub
{
    private readonly mixed $value;

    public function __construct(mixed $value)
    {
        $this->value = $value;
    }

    public function invoke(Invocation $invocation): mixed
    {
        return $this->value;
    }

    public function toString(): string
    {
        $exporter = new Exporter;

        return sprintf(
            'return user-specified value %s',
            $exporter->export($this->value)
        );
    }
}


text:
var itemsPerPage = 10;

Ext.define('FeedViewer.FeedGrid', {
    extend: 'Ext.grid.Panel',

    alias: 'widget.feedgrid',

    initComponent: function(){
        this.addEvents(
            /**
             * @event rowdblclick
             * Fires when a row is double clicked
             * @param {FeedViewer.FeedGrid} this
             * @param {Ext.data.Model} model
             */
            'rowdblclick',
            /**
             * @event select
             * Fires when a grid row is selected
             * @param {FeedViewer.FeedGrid} this
             * @param {Ext.data.Model} model
             */
            'select'
        );

        var store = Ext.create('Ext.data.Store', {
            fields:['_id', 'title', 'body', 'tags'],
            pageSize: itemsPerPage,
            autoLoad: {start: 0, limit: itemsPerPage},
            proxy: {
                type: 'ajax',
                url: '/resultJson',
                enablePaging: true,
                reader: {
                    type: 'json',
                    root: 'items',
                    totalProperty: 'total'
                },
                listeners: {
                    exception: this.onProxyException,
                    scope: this
                }
            },
            listeners: {
                load: this.onLoad,
                remove: this.onRemove,
                scope: this
            }
        });

        Ext.apply(this, {
            cls: 'feed-grid',
            store: store,
            viewConfig: {
                itemId: 'view',
                plugins: [{
                    pluginId: 'preview',
                    ptype: 'preview',
                    bodyField: 'body',
                    expanded: true
                }],
                listeners: {
                    scope: this,
                    itemdblclick: this.onRowDblClick
                }
            },
            columns: [{
                text: 'Title',
                dataIndex: 'title',
                flex: 1,
                renderer: this.formatTitle
            }, {
                text: 'Tags',
                dataIndex: 'tags'
            }],
            bbar: {
                xtype: 'pagingtoolbar',
                pageSize: itemsPerPage,
                store: store,
                displayInfo: true
            }
        });
        this.callParent(arguments);
        this.on('selectionchange', this.onSelect, this);
    },

        /**
     * Reacts to a double click
     * @private
     * @param {Object} view The view
     * @param {Object} index The row index
     */
    onRowDblClick: function(view, record, item, index, e) {
        this.fireEvent('rowdblclick', this, this.store.getAt(index));
    },

    /**
     * React to a grid item being selected
     * @private
     * @param {Ext.model.Selection} model The selection model
     * @param {Array} selections An array of selections
     */
    onSelect: function(model, selections){
        var selected = selections[0];
        if (selected) {
            this.fireEvent('select', this, selected);
        }
    },

    /**
     * Listens for the store loading
     * @private
     */
    onLoad: function(store, records, success) {
        if (this.getStore().getCount()) {
            this.getSelectionModel().select(0);
        }
    },

    /**
     * Listen for proxy eerrors.
     */
    onProxyException: function(proxy, response, operation) {
        Ext.Msg.alert("Error with data from server", operation.error);
        this.view.el.update('');

        // Update the detail view with a dummy empty record
        this.fireEvent('select', this, {data:{}});
    },

    /**
     * Title renderer
     * @private
     */
    formatTitle: function(value, p, record){
        //return Ext.String.format('
{0}{1}
', value, record.get('author') || "Unknown");
        return Ext.String.format('
{0}
', value);
    },

});


text:
@implementation LOFormHiddenField

- (id)init {
    self = [super init];
    if (self) {
        self.isInput = YES;
        self.height = @0;
    }
    return self;
}

@end


text:
Build from GitHub Sources
+++++++++++++++++++++++++

Compressonator comes with pre-built binaries for all of our stable releases:

https://github.com/GPUOpen-Tools/Compressonator/releases

which includes command line tools, GUI and binaries for use in developer applications.

The following build instructions are provided for developers interested in building the latest sources available on `Compressonator GitHub <https://github.com/GPUOpen-Tools/Compressonator>`_ or from the source code downloaded from the `releases <https://github.com/GPUOpen-Tools/Compressonator/releases>`_ page.

.. code-block:: console

    git clone --recursive https://github.com/GPUOpen-Tools/Compressonator.git

to get all the source code including the submodules contents.

Build Instructions for Compressonator SDK Libs
==============================================

VS2017 project soultion files are provided to build SDK libs in the folder compressonator/vs2017

Build Instructions for Compressonator GUI and CLI applications
==============================================================

Building on Windows
As a preliminary step, make sure that you have the following installed on your system:

- CMake 3.15 or above
- Vulkan SDK version 1.2.141.2 or above is required
- Python 3.6 or above
- Qt 5.12.6 is recommended

Once installed users can run any of the following to build:

Documents
---------
cd to the Compressonator folder, and run:

.. code-block:: console

    call scripts/windows_build_docs.bat

Applications
-------------

.. code-block:: console

    call scripts/windows_build_apps.bat

This call will first download additional dependencies used into a "common" folder above the compressonator source folder. It calls a python script called "fetch_dependencies.py" and cmake to build a vs2017 solution file into a "build" folder

Building all sdk libs
---------------------
.. code-block:: console

    call scripts/windows_build_sdk.bat

If you have Visual Studio 2017, build solutions can also be setup by running the vsbuild.bat file that calls fetch_dependencies.py and cmake.

Linux Builds Ubuntu 18.04
--------------------------

As a preliminary step, make sure that you have the following packages installed on your system:

- CMake 3.10 or above
- Vulkan SDK version 1.2.141.2 or above is required
- Python 3.6 or above
- Qt 5.9.2 (Qt 5.12.6 is recommended)

Additional packages are required and can be installed using the shell script: initsetup_ubuntu.sh

Then run the following in the compressonator/scripts folder

.. code-block:: console

    python3 fetch_dependencies.py --no-hooks

To build applications use

.. code-block:: console

    cd compressonator
    export VULKAN_SDK_VER=1.2.141.2
    export VULKAN_SDK=/opt/VulkanSDK/$VULKAN_SDK_VER/
    QT_ROOT=/opt/Qt/Qt5.9.2/5.9.2/gcc_64
    cmake -DQT_PACKAGE_ROOT=$QT_ROOT .
    make

The QT_ROOT and VULKAN_SDK should be set to your package install folder

To build documents use

.. code-block:: console

    set -x
    cd compressonator/docs
    make -j 4 clean
    make -j 4 html


text:
'use strict';/**
 * @module
 * @description
 * This module provides a set of common Pipes.
 */
var async_pipe_1 = require('./async_pipe');
var uppercase_pipe_1 = require('./uppercase_pipe');
var lowercase_pipe_1 = require('./lowercase_pipe');
var json_pipe_1 = require('./json_pipe');
var slice_pipe_1 = require('./slice_pipe');
var date_pipe_1 = require('./date_pipe');
var number_pipe_1 = require('./number_pipe');
var lang_1 = require('angular2/src/facade/lang');
exports.COMMON_PIPES = lang_1.CONST_EXPR([
    async_pipe_1.AsyncPipe,
    uppercase_pipe_1.UpperCasePipe,
    lowercase_pipe_1.LowerCasePipe,
    json_pipe_1.JsonPipe,
    slice_pipe_1.SlicePipe,
    number_pipe_1.DecimalPipe,
    number_pipe_1.PercentPipe,
    number_pipe_1.CurrencyPipe,
    date_pipe_1.DatePipe
]);
//# sourceMappingURL=common_pipes.js.map


text:
$.fn.extend({

  dmWidgetNavigationMenuForm: function(widget)
  {
    var self = this,

    formName = self.metadata().form_name,

    $form = self.find('form:first'),

    $tabs = $form.find('div.dm_tabbed_form').dmCoreTabForm(),

    $items = $form.find('.items_list'),
    itemIndex = 0,

    metadata = $items.metadata(),

    createItemElement = function(item)
    {
      item = $.extend({
        position: 0,
        link: '',
        text: '',
        secure: false,
        nofollow: false,
        target: ''
      }, item);

      var $li = $('
')
      .html('\
'+item.text+' \

 \

'+metadata.text_message+':<input class="text" type="text" name="'+formName+'[text]['+itemIndex+']" />
 \

'+metadata.link_message+':<input class="link" type="text" name="'+formName+'[link]['+itemIndex+']" />
 \

 \
'+metadata.delete_message+' \
'+metadata.extended_show_message+' \

 \

 \

'+metadata.secure_message+':<input class="secure" type="checkbox" name="'+formName+'[secure]['+itemIndex+']" value="1" />
 \

'+metadata.nofollow_message+':<input class="nofollow" type="checkbox" name="'+formName+'[nofollow]['+itemIndex+']" value="1" />
 \

'+metadata.depth_message+':<select class="depth" name="'+formName+'[depth]['+itemIndex+']">'+self.getDepthOptions(item.depth)+'</select>
\

'+metadata.target_message+':<input class="target" type="text" name="'+formName+'[target]['+itemIndex+']" />
 \

 \

 \

 \

'
        );

      $li.find('div.extended').hide().end()
        .find('input.text').val(item.text).end()
        .find('input.link').val(item.link).end()
        .find('input.secure').prop('checked', item.secure).end()
        .find('input.nofollow').prop('checked', item.nofollow).end()
        .find('input.target').val(item.target);

      $items.append($li);
      itemIndex++;

      var $itemText = $li.find('a.item_text');

      $itemText.click(function()
      {
        if (!$li.hasClass('dm_dragging'))
        {
          $li.find('ul.item_form').toggle(200);
        }
      })
      .end()
      .find('a.extend').click(function() {
         var extended = $('.extended', $(this).parent());
         $(this).text(extended.is(":hidden") ? metadata.extended_hide_message:metadata.extended_show_message);
         extended.toggle();
       })
      .end()
      .find('a.remove').click(function() {
        if (confirm($(this).text()+' ?'))
        {
          $li.remove();
        }
      })
      .end()
      .find('input.text').bind('keyup', function() {
        $itemText.text($(this).val());
      })
      .end()
      .find('input.link').bind('keyup', function() {
        $li.find('li.for_depth')[$(this).val().substr(0, 5) == 'page:' ? 'show' : 'hide']();
      }).trigger('keyup');

      self.dmFrontForm('linkDroppable');

      if ($items.hasClass('ui-sortable'))
      {
        $items.sortable('refresh');
      }
    };

    $.each($items.metadata().items, function() {
      createItemElement(this);
    });

    $items.droppable({
      accept:       '#dm_page_bar li > a',
      activeClass:  'droppable_active',
      hoverClass:   'droppable_hover',
      tolerance:    'touch',
      drop:         function(event, ui)
      {
        createItemElement({
          link: 'page:'+ui.draggable.attr('data-page-id'),
          text: ui.draggable.text()
        });

        $items.attr('scrollTop', 999999);
      }
    }).sortable({
      containment:            'parent',
      opacity:                0.5,
      distance:               5,
      revert:                 false,
      scroll:                 true,
      tolerance:              'pointer',
      start:                  function(e, ui) {
        ui.item.addClass('dm_dragging');
      },
      stop:                   function(e, ui) {
        setTimeout(function() {
          ui.item.removeClass('dm_dragging');
        }, 200);
        $(this).trigger('resort');
      }
    });

    $form.find('a.external_link').click(function() {
      createItemElement({
        link: '',
        text: '',
        target: ''
      });

      $items.attr('scrollTop', 999999).find('li.item_element:last a.item_text').trigger('click');
    });
  },

  // show/hide for_depth

  getDepthOptions: function(value)
  {
    value = value || 0;
    html = '';
    for(i=0; i<10; i++)
    {
      text = 0 == i ? '-' : i;
      html += (value == i
        ? '<option value="'+i+'" selected="selected">'+text+'</option>'
        : '<option value="'+i+'">'+text+'</option>');
    }
    return html;
  }
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<title>disabled attribute of button element</title>

<form action="../hlp/get.php">

<input type="hidden" name="result" value="FAIL"/>
<button type="submit" name="sub" disabled="disabled">Press Me</button>

</form>

Nothing should happen if you press button above


text:
module.exports = function() {
	var config = {
		client: {
			root: './client/',
			allTs: './src/client/**/*.ts',
			favicon: './src/client/favicon.ico',
			typings: './typings/main/**/*.d.ts',
			srcTemplateHTML: ['./src/client/index.html', './src/client/**/*.html'],
			srcTemplateCSS: './src/client/**/*.css',

			images: ['./src/client/assets/images/**/*.jpeg','./src/client/assets/images/**/*.jpg', './src/client/assets/images/**/*.png'],
			fonts: ['./src/client/assets/fonts/**/*', './src/client/assets/fonts/*'],
			svgImages: './src/client/assets/images/**/*.svg',
			scss: ['./src/client/assets/scss/**/*.scss', './src/client/assets/partials/*.scss'],

			fontsOut: './client/assets/fonts/',
			imagesOut: './client/assets/images/',
			scssOut: './client/assets/css/',
		},
		server: {
			allTs: ['./src/server/**/*.**', './src/server/bin/www'],
			toOutputhPath: './server/'
		}
	}
	return config;
}


text:
import os

import magnum.conf
from magnum.drivers.heat import template_def

CONF = magnum.conf.CONF

class UbuntuMesosTemplateDefinition(template_def.BaseTemplateDefinition):
    """Mesos template for Ubuntu VM."""

    def __init__(self):
        super(UbuntuMesosTemplateDefinition, self).__init__()
        self.add_parameter('external_network',
                           cluster_template_attr='external_network_id',
                           required=True)
        self.add_parameter('fixed_network',
                           cluster_template_attr='fixed_network')
        self.add_parameter('fixed_subnet',
                           cluster_template_attr='fixed_subnet')
        self.add_parameter('cluster_name',
                           cluster_attr='name')
        self.add_parameter('volume_driver',
                           cluster_template_attr='volume_driver')

        self.add_output('api_address',
                        cluster_attr='api_address')
        self.add_output('mesos_master_private',
                        cluster_attr=None)
        self.add_output('mesos_slaves_private',
                        cluster_attr=None)

    def get_nodegroup_param_maps(self, master_params=None, worker_params=None):
        master_params = master_params or dict()
        worker_params = worker_params or dict()
        master_params.update({
            'master_flavor': 'flavor_id',
            'master_image': 'image_id',
        })
        worker_params.update({
            'number_of_slaves': 'node_count',
            'slave_flavor': 'flavor_id',
            'slave_image': 'image_id',
        })
        return super(
            UbuntuMesosTemplateDefinition, self).get_nodegroup_param_maps(
                master_params=master_params, worker_params=worker_params)

    def update_outputs(self, stack, cluster_template, cluster,
                       nodegroups=None):
        nodegroups = nodegroups or [cluster.default_ng_worker,
                                    cluster.default_ng_master]
        for nodegroup in nodegroups:
            if nodegroup.role == 'master':
                self.add_output(
                    'mesos_master', nodegroup_attr='node_addresses',
                    nodegroup_uuid=nodegroup.uuid,
                    mapping_type=template_def.NodeGroupOutputMapping)
            else:
                self.add_output(
                    'mesos_slaves', nodegroup_attr='node_addresses',
                    nodegroup_uuid=nodegroup.uuid,
                    mapping_type=template_def.NodeGroupOutputMapping)
                self.add_output(
                    'number_of_slaves', nodegroup_attr='node_count',
                    nodegroup_uuid=nodegroup.uuid, is_stack_param=True,
                    mapping_type=template_def.NodeGroupOutputMapping)
        super(UbuntuMesosTemplateDefinition,
              self).update_outputs(stack, cluster_template, cluster,
                                   nodegroups=nodegroups)

    def get_params(self, context, cluster_template, cluster, **kwargs):
        extra_params = kwargs.pop('extra_params', {})
        # HACK(apmelton) - This uses the user's bearer token, ideally
        # it should be replaced with an actual trust token with only
        # access to do what the template needs it to do.
        osc = self.get_osc(context)
        extra_params['auth_url'] = context.auth_url
        extra_params['username'] = context.user_name
        extra_params['tenant_name'] = context.project_id
        extra_params['domain_name'] = context.domain_name
        extra_params['region_name'] = osc.cinder_region_name()
        extra_params['nodes_affinity_policy'] = \
            CONF.cluster.nodes_affinity_policy

        label_list = ['rexray_preempt', 'mesos_slave_isolation',
                      'mesos_slave_image_providers',
                      'mesos_slave_work_dir',
                      'mesos_slave_executor_env_variables']

        labels = self._get_relevant_labels(cluster, kwargs)

        for label in label_list:
            extra_params[label] = labels.get(label)

        return super(UbuntuMesosTemplateDefinition,
                     self).get_params(context, cluster_template, cluster,
                                      extra_params=extra_params,
                                      **kwargs)

    def get_scale_params(self, context, cluster, node_count,
                         scale_manager=None, nodes_to_remove=None):
        scale_params = dict()
        if nodes_to_remove:
            scale_params['slaves_to_remove'] = nodes_to_remove
        if scale_manager:
            hosts = self.get_output('mesos_slaves_private')
            scale_params['slaves_to_remove'] = (
                scale_manager.get_removal_nodes(hosts))
        scale_params['number_of_slaves'] = node_count
        return scale_params

    def get_env_files(self, cluster_template, cluster, nodegroup=None):
        env_files = []

        template_def.add_priv_net_env_file(env_files, cluster_template,
                                           cluster)
        template_def.add_lb_env_file(env_files, cluster)

        return env_files

    @property
    def driver_module_path(self):
        return __name__[:__name__.rindex('.')]

    @property
    def template_path(self):
        return os.path.join(os.path.dirname(os.path.realpath(__file__)),
                            'templates/mesoscluster.yaml')


text:
package com.intellij.application.options.colors;

import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.FileStatusFactory;

import java.util.Collection;
import java.util.ArrayList;

class FileStatusColorsPageFactory implements ColorAndFontPanelFactory {
  public NewColorAndFontPanel createPanel(ColorAndFontOptions options) {
    return NewColorAndFontPanel.create(new PreviewPanel.Empty(), ColorAndFontOptions.FILE_STATUS_GROUP, options, collectFileTypes(), null);
  }

  public String getPanelDisplayName() {
    return ColorAndFontOptions.FILE_STATUS_GROUP;
  }

  private static Collection<String> collectFileTypes() {
    ArrayList<String> result = new ArrayList<String>();
    FileStatus[] statuses = FileStatusFactory.SERVICE.getInstance().getAllFileStatuses();

    for (FileStatus status : statuses) {
      result.add(status.getText());
    }
    return result;
  }
}


text:
/**
 * @file random_selection.hpp
 * @author Ryan Curtin
 *
 * Randomly select some points (with replacement) to use for the Nystroem
 * method.  Replacement is suboptimal, but for rank << number of points, this is
 * unlikely.
 */
#ifndef MLPACK_METHODS_NYSTROEM_METHOD_RANDOM_SELECTION_HPP
#define MLPACK_METHODS_NYSTROEM_METHOD_RANDOM_SELECTION_HPP

#include <mlpack/core.hpp>

namespace mlpack {
namespace kernel {

class RandomSelection
{
 public:
  /**
   * Randomly select the specified number of points in the dataset.
   *
   * @param data Dataset to sample from.
   * @param m Number of points to select.
   * @return Indices of selected points from the dataset.
   */
  const static arma::Col<size_t> Select(const arma::mat& data, const size_t m)
  {
    arma::Col<size_t> selectedPoints(m);
    for (size_t i = 0; i < m; ++i)
      selectedPoints(i) = math::RandInt(0, data.n_cols);

    return selectedPoints;
  }
};

} // namespace kernel
} // namespace mlpack

#endif


text:
package com.glipka.easyReactJS.react
import scala.scalajs.js
import scala.scalajs.js._
import org.scalajs.dom.html
import js.{ UndefOr, Any, Function => JFn }
import js.annotation.{ JSBracketAccess, JSName }
import js.{ Any => jAny }

// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/react/react.d.ts
@js.native
abstract class ValidationMap[T] extends js.Any {
  def $get(key: String): Validator[T] = js.native
}


text:
from pysmi.mibinfo import MibInfo
from pysmi.codegen.base import AbstractCodeGen
from pysmi import debug

class NullCodeGen(AbstractCodeGen):
    """Dummy code generation backend.

       Could be used for disabling code generation at *MibCompiler*.
    """

    def genCode(self, ast, symbolTable, **kwargs):
        debug.logger & debug.flagCodegen and debug.logger('%s invoked' % self.__class__.__name__)
        return MibInfo(oid=None, name='', imported=[]), ''

    def genIndex(self, mibsMap, **kwargs):
        return ''


text:
package kieker.test.common.junit.configuration;

import java.io.File;

import org.junit.Assert;
import org.junit.Test;

import kieker.common.configuration.Configuration;

import kieker.test.common.junit.AbstractKiekerTest;

/**
 * @author Jan Waller
 *
 * @since 1.6
 */
public class TestConfigurationPath extends AbstractKiekerTest {

	private static String[] paths = {
		".", "",
		"a", "a",
		"./x", "x",
		"../x\\y\\.././x", "../x/x",
		"C:\\Temp\\x.txt", "C:/Temp/x.txt",
		"out/containerDependencyGraph.dot", "out/containerDependencyGraph.dot",
		"out" + File.separator + File.separator + "containerDependencyGraph.dot", "out/containerDependencyGraph.dot",
		"out/", "out/",
		"/", "/",
		"././", "",
	};

	/**
	 * Default constructor.
	 */
	public TestConfigurationPath() {
		// empty default constructor
	}

	@Test
	public void testPath() {
		Assert.assertTrue((paths.length % 2) == 0);
		for (int i = 0; i < paths.length; i += 2) {
			Assert.assertEquals(paths[i + 1], Configuration.convertToPath(paths[i]));
		}
	}

}


text:
require 'rails_admin/config/fields'
require 'rails_admin/config/fields/types'
require 'rails_admin/config/fields/types/belongs_to_association'

RailsAdmin::Config::Fields.register_factory do |parent, properties, fields|
  if association = parent.abstract_model.associations.find {|a| a[:foreign_key] == properties[:name] && [:belongs_to, :has_and_belongs_to_many].include?(a[:type]) }
    field = RailsAdmin::Config::Fields::Types.load("#{association[:polymorphic] ? :polymorphic : association[:type]}_association").new(parent, association[:name], association)
    fields << field

    child_columns = []
    possible_field_names =
      if association[:polymorphic]
        [:foreign_key, :foreign_type, :foreign_inverse_of]
      else
        [:foreign_key]
      end.map{|k| association[k] }.compact

    parent.abstract_model.properties.select{|p| possible_field_names.include? p[:name] }.each do |column|
      unless child_field = fields.find{|f| f.name.to_s == column[:name].to_s }
        child_field = RailsAdmin::Config::Fields.default_factory.call(parent, column, fields)
      end
      child_columns << child_field
    end

    child_columns.each do |child_column|
      child_column.hide
      child_column.filterable(false)
    end

    field.children_fields child_columns.map(&:name)
  end
end


text:
compiler-toolbox
================

A Haskell library containing miscellaneous components useful for building compilers.


text:
Facter.add(:psql_user) do
  setcode do
    case Facter.value(:kernel)
      when 'OpenBSD'
        '_postgresql'
      else
        'postgres'
    end
  end
end

Facter.add(:have_psql) do
  setcode do
    confine :kernel => %w{Linux OpenBSD SunOS}
    psql_user = Facter.value(:psql_user)
    if Facter::Util::Resolution.exec(Facter.value('ps')).match(/^#{psql_user}/)
        "true"
    else
        "false"
    end
  end
end

Facter.add(:pgusers_array) do
  confine :have_psql => "true"
  setcode do
    psql_user = Facter.value(:psql_user)
    pgusers_array = Facter::Util::Resolution.exec("psql -qAtX -U #{psql_user} -d postgres -c 'SELECT usename from pg_shadow where passwd is not null order by 1'").split("\n")
    pgusers_array
  end
end

Facter.add(:pgusers_hash) do
  confine :have_psql => "true"
  setcode do
    pgusers_array = Facter.value(:pgusers_array)
    psql_user = Facter.value(:psql_user)
    pgusers_hash = {}

    pgusers_array.each do |user|
      passwd = Facter::Util::Resolution.exec("psql -qAtX -U #{psql_user} -d postgres -c \"SELECT passwd from pg_shadow where usename='#{user}'\"")
      if passwd
        pgusers_hash[user] = {'password' => passwd, 'username' => user}
      end
    end

    pgusers_hash
  end
end


text:
void
CXFont::
setPrototype()
{
  CFontPtr font(new CXFont("courier", CFONT_STYLE_NORMAL, 12));

  CFontMgrInst->setPrototype(font);
}

CXFont::
CXFont(const std::string &family, CFontStyle style, double size, double angle,
       double char_angle, int x_res, int y_res) :
 CFont(family, style, size, angle, char_angle, x_res, y_res),
 screen_(*CXMachineInst->getCXScreen(0)),
 font_family_(CFontFamily::lookup(family))
{
  init();
}

CXFont::
CXFont(CXScreen &screen, const std::string &family, CFontStyle style, double size, double angle,
       double char_angle, int x_res, int y_res) :
 CFont(family, style, size, angle, char_angle, x_res, y_res), screen_(screen),
 font_family_(CFontFamily::lookup(family))
{
  init();
}

CXFont::
CXFont(const std::string &full_name) :
 CFont(full_name), screen_(*CXMachineInst->getCXScreen(0)),
 font_family_(CFontFamily::lookup(getFamily()))
{
  init();
}

CXFont::
CXFont(CXScreen &screen, const std::string &full_name) :
 CFont(full_name), screen_(screen), font_family_(CFontFamily::lookup(getFamily()))
{
  init();
}

CXFont::
CXFont(XFontStruct *fs, uint angle) :
 CFont("", CFONT_STYLE_NORMAL, CFONT_DEF_SIZE, angle),
 screen_(*CXMachineInst->getCXScreen(0)), font_family_(CFontFamily::lookup(""))
{
  init(fs);
}

CXFont::
CXFont(CXScreen &screen, XFontStruct *fs, uint angle) :
 CFont("", CFONT_STYLE_NORMAL, CFONT_DEF_SIZE, angle),
 screen_(screen), font_family_(CFontFamily::lookup(""))
{
  init(fs);
}

CXFont::
CXFont(const CXFont &font) :
 CFont(font), screen_(font.screen_), font_family_(font.font_family_),
 font_width_(font.font_width_), font_ascent_(font.font_ascent_), font_descent_(font.font_descent_),
 proportional_(font.proportional_), font_aspect_(font.font_aspect_)
{
  xrt_font_ = new CXrtFont(*font.xrt_font_);
}

CXFont::
CXFont(const CFont &font) :
 CFont(font), screen_(*CXMachineInst->getCXScreen(0)),
 font_family_(CFontFamily::lookup(font.getFamily()))
{
  init();
}

CXFont::
~CXFont()
{
  delete xrt_font_;
}

CXFont &
CXFont::
operator=(const CXFont &font)
{
  screen_       = font.screen_;
  font_family_  = font.font_family_;
  font_width_   = font.font_width_;
  font_ascent_  = font.font_ascent_;
  font_descent_ = font.font_descent_;
  proportional_ = font.proportional_;
  font_aspect_  = font.font_aspect_;

  xrt_font_ = new CXrtFont(*font.xrt_font_);

  return *this;
}

CFontPtr
CXFont::
dup(const std::string &family, CFontStyle style, double size,
    double angle, double char_angle, int x_res, int y_res) const
{
  CXFont *font =
    new CXFont(family, style, size, angle, char_angle, x_res, y_res);

  return CFontPtr(font);
}

void
CXFont::
init()
{
  std::string x_font_name = getXFontName();

  Display *display = screen_.getDisplay();
  Window   root    = screen_.getRoot();

  xrt_font_ = new CXrtFont(display, root, x_font_name, getIAngle());

  int font_width, font_ascent, font_descent;

  xrt_font_->getExtents(&font_width, &font_ascent, &font_descent);

  font_width_   = uint(font_width);
  font_ascent_  = uint(font_ascent);
  font_descent_ = uint(font_descent);

  proportional_ = xrt_font_->isProportional();

  font_aspect_ = 1.2;
}

void
CXFont::
init(XFontStruct *fs)
{
  Display *display = screen_.getDisplay();
  Window   root    = screen_.getRoot();

  xrt_font_ = new CXrtFont(display, root, fs, getIAngle());

  int font_width, font_ascent, font_descent;

  xrt_font_->getExtents(&font_width, &font_ascent, &font_descent);

  font_width_   = uint(font_width);
  font_ascent_  = uint(font_ascent);
  font_descent_ = uint(font_descent);

  setSize(font_ascent_ + font_descent_);

  proportional_ = xrt_font_->isProportional();

  font_aspect_ = 1.2;
}

uint
CXFont::
getIStringWidth(const std::string &str) const
{
  int width;

  xrt_font_->textExtents(str, &width, nullptr, nullptr);

  return uint(width);
}

CImagePtr
CXFont::
getStringImage(const std::string &str)
{
  uint w = getIStringWidth(str);
  uint h = getICharHeight();

  std::string fileName = "app://getStringImage";

  CImageFileSrc src(fileName);

  image_ = CImageMgrInst->createImage(src);

  image_->setDataSize(int(w), int(h));

  image_->setRGBAData(CRGBA(0, 0, 0, 0));

  CXImage *ximage = image_.cast<CXImage>();

  Pixmap pixmap = ximage->getXPixmap();

  GC gc = CXMachineInst->createGC(pixmap, 0, 0);

  CXMachineInst->setForeground(gc, 0);

  xrt_font_->draw(pixmap, gc, 0, 0, str);

  CXMachineInst->freeGC(gc);

  return image_;
}

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

#define ALL_FONTS "-*-*-*-*-*-*-*-*-*-*-*-*-*-*"

void
CXFont::
loadFontDatabase()
{
  CXFontList font_list;

  uint num_fonts = font_list.getNumFonts();

  std::string family;
  CFontStyle  style;
  uint        size, x_res, y_res;

  for (uint i = 0; i < num_fonts; i++) {
    const char *font_name = font_list.getFont(i);

    if (! decodeXFontName(font_name, family, style, size, x_res, y_res))
      continue;

    CFontFamily &font_family = CFontFamily::lookup(family);

    CFontDef &font = font_family.lookupFontDef(style, size);

    if (x_res > font.x_res || y_res > font.y_res) {
      font.x_res = x_res;
      font.y_res = y_res;
    }
  }
}


text:
navigator.geolocation.getCurrentPosition(function(position) {
    console.log(position.coords.latitude, position.coords.longitude);
});


text: FROM golang:1.6-onbuild


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

/**
This is meant to contain useful utilities for IO related work in ReparsePoints
 - MountVolume
 - Encryption
**/
#define TRACE
#define DEBUG

using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
public static class MountHelper
{
    [DllImport("api-ms-win-core-file-l1-2-0.dll", EntryPoint = "GetVolumeNameForVolumeMountPointW", CharSet = CharSet.Unicode, BestFitMapping = false, SetLastError = true)]
    private static extern bool GetVolumeNameForVolumeMountPoint(String volumeName, StringBuilder uniqueVolumeName, int uniqueNameBufferCapacity);
    // unique volume name must be "\\?\Volume{GUID}\"
    [DllImport("api-ms-win-core-kernel32-legacy-l1-1-1.dll", EntryPoint = "SetVolumeMountPointW", CharSet = CharSet.Unicode, BestFitMapping = false, SetLastError = true)]
    private static extern bool SetVolumeMountPoint(String mountPoint, String uniqueVolumeName);
    [DllImport("api-ms-win-core-file-l1-1-0.dll", EntryPoint = "DeleteVolumeMountPointW", CharSet = CharSet.Unicode, BestFitMapping = false, SetLastError = true)]
    private static extern bool DeleteVolumeMountPoint(String mountPoint);

    public static void Mount(String volumeName, String mountPoint)
    {

        if (volumeName[volumeName.Length - 1] != Path.DirectorySeparatorChar)
            volumeName += Path.DirectorySeparatorChar;
        if (mountPoint[mountPoint.Length - 1] != Path.DirectorySeparatorChar)
            mountPoint += Path.DirectorySeparatorChar;

        Console.WriteLine(String.Format("Mounting volume {0} at {1}", volumeName, mountPoint));
        bool r;
        StringBuilder sb = new StringBuilder(1024);
        r = GetVolumeNameForVolumeMountPoint(volumeName, sb, sb.Capacity);
        if (!r)
            throw new Exception(String.Format("Win32 error: {0}", Marshal.GetLastWin32Error()));

        String uniqueName = sb.ToString();
        Console.WriteLine(String.Format("uniqueName: <{0}>", uniqueName));
        r = SetVolumeMountPoint(mountPoint, uniqueName);
        if (!r)
            throw new Exception(String.Format("Win32 error: {0}", Marshal.GetLastWin32Error()));
        Task.Delay(100).Wait(); // adding sleep for the file system to settle down so that reparse point mounting works
    }

    public static void Unmount(String mountPoint)
    {
        if (mountPoint[mountPoint.Length - 1] != Path.DirectorySeparatorChar)
            mountPoint += Path.DirectorySeparatorChar;
        Console.WriteLine(String.Format("Unmounting the volume at {0}", mountPoint));

        bool r = DeleteVolumeMountPoint(mountPoint);
        if (!r)
            throw new Exception(String.Format("Win32 error: {0}", Marshal.GetLastWin32Error()));
    }

    /// For standalone debugging help. Change Main0 to Main
     public static void Main0(String[] args)
    {
	 	try
        {
			if(args[0]=="-m")
				Mount(args[1], args[2]);
			if(args[0]=="-u")
				Unmount(args[1]);
 		}
        catch(Exception ex)
        {
	 		Console.WriteLine(ex);
		}
    }

}


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

package org.chromium.chrome.test.util.browser;

import android.text.TextUtils;

import junit.framework.Assert;

import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.chrome.browser.tab.EmptyTabObserver;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.LoadUrlParams;

import java.util.Locale;

/**
 * Monitors that a Tab starts loading and stops loading a URL.
 */
public class TabLoadObserver extends EmptyTabObserver {
    private static final float FLOAT_EPSILON = 0.001f;

    private final CallbackHelper mTabLoadStartedCallback = new CallbackHelper();
    private final CallbackHelper mTabLoadFinishedCallback = new CallbackHelper();

    private final Tab mTab;
    private final String mExpectedTitle;
    private final Float mExpectedScale;

    public TabLoadObserver(Tab tab) {
        this(tab, null, null);
    }

    public TabLoadObserver(Tab tab, String expectedTitle, Float expectedScale) {
        mTab = tab;
        mTab.addObserver(this);
        mExpectedTitle = expectedTitle;
        mExpectedScale = expectedScale;
    }

    @Override
    public void onLoadStarted(Tab tab, boolean toDifferentDocument) {
        mTabLoadStartedCallback.notifyCalled();
    }

    @Override
    public void onPageLoadFinished(Tab tab) {
        mTabLoadFinishedCallback.notifyCalled();
    }

    @Override
    public void onCrash(Tab tab, boolean sadTabShown) {
        Assert.fail("Tab crashed; test results will be invalid.  Failing.");
    }

    /**
     * Loads the given URL and waits for it to complete.
     *
     * @param url URL to load and wait for.
     */
    public void fullyLoadUrl(final String url) throws Exception {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTab.loadUrl(new LoadUrlParams(url));
            }
        });
        assertLoaded();
    }

    /**
     * Asserts the page has loaded.
     */
    public void assertLoaded() throws Exception {
        mTabLoadStartedCallback.waitForCallback(0, 1);
        mTabLoadFinishedCallback.waitForCallback(0, 1);

        CriteriaHelper.pollUiThread(new Criteria() {
            @Override
            public boolean isSatisfied() {
                if (!mTab.isLoadingAndRenderingDone()) {
                    updateFailureReason("load and rendering never completed");
                    return false;
                }

                String title = mTab.getTitle();
                if (mExpectedTitle != null && !TextUtils.equals(mExpectedTitle, title)) {
                    updateFailureReason(String.format(
                            Locale.ENGLISH,
                            "title did not match -- expected: \"%s\", actual \"%s\"",
                            mExpectedTitle, title));
                    return false;
                }

                if (mExpectedScale != null) {
                    if (mTab.getContentViewCore() == null) {
                        updateFailureReason("tab has no content view core");
                        return false;
                    }

                    float scale = mTab.getContentViewCore().getScale();
                    if (Math.abs(mExpectedScale - scale) >= FLOAT_EPSILON) {
                        updateFailureReason(String.format(
                                Locale.ENGLISH,
                                "scale did not match with allowed epsilon -- "
                                + "expected: \"%f\", actual \"%f\"", mExpectedScale, scale));
                        return false;
                    }
                }
                updateFailureReason(null);
                return true;
            }
        });
    }
}


text:
from __future__ import print_function
import os
import re
import optparse
import getpass
import sys
import ConfigParser
from multiprocessing import Pool, current_process
from shardgather.renderers import RENDERERS, DEFAULT_RENDERER
from shardgather.db import query, get_shard_databases, get_connection

DEFAULT_POOLSIZE = 5

def print(s, out=sys.stderr):
    out.write(s)
    out.write('\n')

def render(s):
    sys.stdout.write(s)
    sys.stdout.write('\n')

def highlight(sql):
    from pygments import highlight as pygments_highlight
    from pygments.lexers import SqlLexer
    from pygments.formatters import TerminalFormatter

    return pygments_highlight(sql, SqlLexer(), TerminalFormatter())

CONNECTIONS = {}

def collect((sql, hostname, username, password, db_name)):
    print("Running on %s" % db_name)
    current_process_name = current_process().name
    if current_process_name not in CONNECTIONS:
        print("Creating a new connection for worker %s" % current_process_name)
        CONNECTIONS[current_process_name] = get_connection(
            hostname, username, password)
    conn = CONNECTIONS[current_process_name]
    query(conn, "USE %s" % db_name)
    collected = query(conn, sql.format(db_name=db_name))
    print("%d rows returned for %s" % (len(collected), db_name))
    return db_name, collected

def aggregate(current_aggregated, next):
    db_name, collected = next
    current_aggregated[db_name] = collected
    return current_aggregated

def configure():
    parser = optparse.OptionParser()
    parser.add_option(
        '-c', '--config', dest='config_file_name',
        help='Config file', metavar='PATH_TO_CONFIG_FILE')
    parser.add_option(
        '-p', '--pwdfile', dest='pwdfile',
        help='File containing database password', metavar='PATH_TO_PWD_FILE')
    parser.add_option(
        '-i', '--interactive', action='store_true',
        help=(
            'Drop into an interactive shell instead of rendering'
            'the result.'))
    parser.add_option(
        '-g', '--mkcfg', action='store_true',
        help='Generate sample config')
    return parser.parse_args()

def get_password(options):
    if options.pwdfile:
        with open(options.pwdfile) as f:
            return f.read().rstrip()

    return getpass.getpass()

def main():
    options, args = configure()

    if options.mkcfg:
        config_file = os.path.join(
            os.path.dirname(__file__), 'config.ini.sample')
        with open(config_file) as f:
            print(f.read(), out=sys.stdout)
        sys.exit(0)

    password = None
    if options.pwdfile:
        with open(options.pwdfile) as f:
            password = f.read().rstrip()

    if len(args) != 1:
        raise RuntimeError('sql file needed')

    if args[0] == '-':
        sql_file = sys.stdin
    else:
        sql_file = open(args[0], 'r')

    sql = sql_file.read()
    sql_file.close()

    config_parser = ConfigParser.ConfigParser()
    config_parser.read([options.config_file_name])
    hostname = config_parser.get('database', 'hostname')
    username = config_parser.get('database', 'username')
    pool_size = int(config_parser.get(
        'executor', 'pool_size', DEFAULT_POOLSIZE))
    renderer = RENDERERS[config_parser.get(
        'renderer', 'renderer', DEFAULT_RENDERER)]
    shard_name_pattern = config_parser.get('database', 'shard_name_pattern')

    is_shard_db = re.compile(shard_name_pattern).search

    print("Host: %s" % hostname)
    print("Username: %s" % username)
    print("Renderer: %s" % renderer.__name__)
    print("Executor Pool Size: %s" % pool_size)
    print("Interactive mode: %s" % options.interactive)
    print("SQL to be executed for each database:\n\n%s" % highlight(sql))

    password = get_password(options)

    shard_databases = get_shard_databases(
        hostname, username, password, is_shard_db)

    if not shard_databases:
        raise RuntimeError('Cannot get shard databases given the pattern: %s'
                           % shard_name_pattern)

    pool = Pool(pool_size)

    try:
        collected = reduce(
            aggregate,
            pool.map(
                collect,
                [(sql, hostname, username, password, live)
                 for live in shard_databases]),
            {}
        )

        if options.interactive:
            print("Available variables:")
            print("  collected - the collected data")
            import IPython
            IPython.embed()

        render(renderer(collected))
    finally:
        for _, conn in CONNECTIONS.iteritems():
            conn.close()


text:
layout: research
title: Information Visualizations for Household Energy Usage
date: 2017-12-13
excerpt: "Research Member"
project: true
tags: [HCI, human computer interaction, AR, augmented reality, energy usage, visualization]
comments: true
---

## Research Partner

Designing a way for individuals to visualize household energy use.

<object data="" type="/assets/img/research/eu.pdf" width="700px" height="700px">
    <embed src="/assets/img/research/eu.pdf">
        This browser does not support PDFs. Please download the PDF to view it: Download PDF.

    </embed>
</object>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="hello">Hello World, Click Me!</string>
	<string name="app_name">HighEnergy.TreeView.Demo.Android</string>
</resources>


text:
<?php
namespace Riskio\SpecificationTest;

use PHPUnit\Framework\TestCase;
use Riskio\Specification\AndSpecification;
use Riskio\SpecificationTest\Fixtures\NotSatisfiedSpecification;
use Riskio\SpecificationTest\Fixtures\SatisfiedSpecification;

class AndSpecificationTest extends TestCase
{
    /**
     * @test
     */
    public function isSatisfiedBy_GivenBothSpecificationsSatisfied_ShouldReturnTrue(): void
    {
        $spec = new AndSpecification(
            new SatisfiedSpecification(),
            new SatisfiedSpecification()
        );

        $isSatisfied = $spec->isSatisfiedBy('foo');

        $this->assertThat($isSatisfied, $this->equalTo(true));
    }

    /**
     * @test
     */
    public function isSatisfiedBy_GivenOneSpecificationNotSatisfied_ShouldReturnFalse(): void
    {
        $spec = new AndSpecification(
            new SatisfiedSpecification(),
            new NotSatisfiedSpecification(),
            new SatisfiedSpecification()
        );

        $isSatisfied = $spec->isSatisfiedBy('foo');

        $this->assertThat($isSatisfied, $this->equalTo(false));
    }

    /**
     * @test
     */
    public function isSatisfiedBy_GivenBothSpecificationsNotSatisfied_ShouldReturnFalse(): void
    {
        $spec = new AndSpecification(
            new NotSatisfiedSpecification(),
            new NotSatisfiedSpecification()
        );

        $isSatisfied = $spec->isSatisfiedBy('foo');

        $this->assertThat($isSatisfied, $this->equalTo(false));
    }
}


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

<jalopy>
    <general>
        <compliance>
            <version>14</version>
        </compliance>

    </general>
    <inspector>
        <enable>false</enable>
        <tips>
            <adhereToNamingConvention>false</adhereToNamingConvention>
            <alwaysOverrideHashCode>false</alwaysOverrideHashCode>
            <avoidThreadGroups>false</avoidThreadGroups>
            <declareCollectionComment>false</declareCollectionComment>
            <dontIgnoreExceptions>false</dontIgnoreExceptions>
            <dontSubstituteObjectEquals>false</dontSubstituteObjectEquals>
            <neverDeclareException>false</neverDeclareException>
            <neverDeclareThrowable>false</neverDeclareThrowable>
            <neverInvokeWaitOutsideLoop>false</neverInvokeWaitOutsideLoop>
            <neverReturnZeroArrays>false</neverReturnZeroArrays>
            <neverUseEmptyFinally>false</neverUseEmptyFinally>
            <obeyContractEquals>false</obeyContractEquals>
            <overrideToString>false</overrideToString>
            <referToObjectsByInterface>false</referToObjectsByInterface>
            <replaceStructureWithClass>false</replaceStructureWithClass>
            <stringLiterallI18n>false</stringLiterallI18n>
            <useInterfaceOnlyForTypes>false</useInterfaceOnlyForTypes>
            <wrongCollectionComment>false</wrongCollectionComment>
        </tips>
    </inspector>
    <internal>
        <version>6</version>
    </internal>
    <messages>
        <priority>
            <general>30000</general>
            <parser>30000</parser>
            <parserJavadoc>30000</parserJavadoc>
            <printer>30000</printer>
            <printerJavadoc>30000</printerJavadoc>
            <transform>30000</transform>
        </priority>
        <showErrorStackTrace>true</showErrorStackTrace>
    </messages>
    <misc>
        <threadCount>1</threadCount>
    </misc>
    <printer>
        <backup>
            <directory>bak</directory>
            <level>0</level>
        </backup>
        <blanklines>
            <after>
                0
            </after>
            <before>
                0
            </before>
        </blanklines>
        <braces>
            <empty>
                <cuddle>false</cuddle>
                <insertStatement>false</insertStatement>
            </empty>
            <insert>
                <dowhile>false</dowhile>
                <for>false</for>
                <ifelse>true</ifelse>
                <while>false</while>
            </insert>
            <remove>
                <block>true</block>
                <dowhile>false</dowhile>
                <for>false</for>
                <ifelse>false</ifelse>
                <while>false</while>
            </remove>
            <treatDifferent>
                <methodClass>false</methodClass>
                <methodClassIfWrapped>false</methodClassIfWrapped>
            </treatDifferent>
        </braces>
        <comments>
            <format>
                <multiline>true</multiline>
            </format>
            <javadoc>
                <check>
                    <innerclass>false</innerclass>
                    <tags>true</tags>
                    <throwsTags>true</throwsTags>
                </check>
                <fieldsShort>true</fieldsShort>
                <generate>
                    <class>1</class>
                    <constructor>1</constructor>
                    <field>1</field>
                    <method>1</method>
                </generate>
                <parseComments>true</parseComments>
                <tags>
                    <in-line />
                    <standard />
                </tags>
                <templates>
                    <class>/**| * | *| * @author CODEGEN| * @version $Id: codegen_convention.xml,v 1.1 2007-12-17 22:22:07 sahnih Exp $| */</class>
                    <constructor>
                        <bottom> */</bottom>
                        <exception> * @throws $exceptionType$ DOCUMENT ME!</exception>
                        <param> * @param $paramType$ DOCUMENT ME!</param>
                        <top>/**| * Creates a new $objectType$ object.</top>
                    </constructor>
                    <interface>/**| * | *| * @author CODEGEN| * @version $Id: codegen_convention.xml,v 1.1 2007-12-17 22:22:07 sahnih Exp $| */</interface>
                    <method>
                        <bottom> */</bottom>
                        <exception> * @throws $exceptionType$ DOCUMENT ME!</exception>
                        <param> * @param $paramType$ DOCUMENT ME!</param>
                        <return> * @return DOCUMENT ME!</return>
                        <top>/**| * DOCUMENT ME!</top>
                    </method>
                    <variable>/**| * DOCUMENT ME!| */</variable>
                </templates>
            </javadoc>
            <remove>
                <javadoc>false</javadoc>
                <multiline>false</multiline>
                <singleline>false</singleline>
            </remove>
        </comments>

            <keys />
            <smartMode>0</smartMode>
            <text>/*| */</text>
            <use>false</use>

        <history>
            <policy>disabled</policy>
        </history>
        <imports>
            <grouping>
                <defaultDepth>3</defaultDepth>
                <packages>*:0|gnu:2|java:2|javax:2</packages>
            </grouping>
            <policy>disabled</policy>
            <sort>true</sort>
        </imports>
        <indentation>
            <sizes>
                <braceCuddled>1</braceCuddled>
                <braceLeft>1</braceLeft>
                <braceRight>0</braceRight>
                <braceRightAfter>1</braceRightAfter>
                <deep>55</deep>
            </sizes>
        </indentation>
        <misc>
            <arrayBracketsAfterIdent>false</arrayBracketsAfterIdent>
            <forceFormatting>false</forceFormatting>
            <insertExpressionParentheses>true</insertExpressionParentheses>
            <insertLoggingConditional>false</insertLoggingConditional>
            <insertTrailingNewline>true</insertTrailingNewline>
            <insertUID>false</insertUID>
        </misc>
        <wrapping>
            <always>
                <after>
                    <arrayElement>0</arrayElement>
                    <braceRight>false</braceRight>
                    <extendsTypes>false</extendsTypes>
                    <implementsTypes>false</implementsTypes>
                    true
                    <methodCallChained>false</methodCallChained>
                    <ternaryOperator>
                        <first>false</first>
                        <second>false</second>
                    </ternaryOperator>
                    <throwsTypes>false</throwsTypes>
                </after>
                <before>
                    <braceLeft>false</braceLeft>
                    <extends>false</extends>
                    <implements>false</implements>
                    <throws>false</throws>
                </before>
                <parameter>
                    <methodCall>false</methodCall>
                    <methodCallNested>false</methodCallNested>
                    <methodDeclaration>false</methodDeclaration>
                </parameter>
            </always>
            <general>
                <beforeOperator>false</beforeOperator>
                <enable>true</enable>
                <lineLength>80</lineLength>
            </general>
            <ondemand>
                <after>
                    <assignment>false</assignment>
                    <leftParenthesis>false</leftParenthesis>
                    <parameter>false</parameter>
                    <types>
                        <extends>false</extends>
                        <implements>false</implements>
                        <throws>false</throws>
                    </types>
                </after>
                <before>
                    <rightParenthesis>false</rightParenthesis>
                </before>
                <groupingParentheses>false</groupingParentheses>
            </ondemand>
        </wrapping>
    </printer>
</jalopy>


text:
/**
 *
 */
package com.happy3w.autobuy.action.strc;

/**
 * 操作单元格所需参数。
 * @version 2016年10月25日上午10:06:30
 * @author happy3w
 */
public class CellStruct extends ActStruct {
	private String table;
	private String row;
	private int startRw;
	private int endRw;
	private String filter;
	private String conditionName;

	public String getTable() {
		return table;
	}

	public void setTable(String table) {
		this.table = table;
	}

	public String getRow() {
		return row;
	}

	public void setRow(String row) {
		this.row = row;
	}

	public int getStartRw() {
		return startRw;
	}

	public void setStartRw(int startRw) {
		this.startRw = startRw;
	}

	public int getEndRw() {
		return endRw;
	}

	public void setEndRw(int endRw) {
		this.endRw = endRw;
	}

	public String getConditionName() {
		return conditionName;
	}

	public String getFilter() {
		return filter;
	}

	public void setCondition(String filter) {
		this.filter = filter;
	}

	public void setConditionName(String conditionName) {
		this.conditionName = conditionName;
	}

	public CellStruct(String operation,String className, String paramName, String table, int startRw, int endRw,String target,String filter,
			String conditionName,String condition ,String returnName) {
		super(operation, className, target, paramName, returnName, condition);
		this.table = table;
		this.row = "tr";
		this.startRw = startRw;
		this.endRw = endRw;
		this.filter = filter;
		this.conditionName = conditionName;
	}
}


text:
#ifndef FASTRL_BEHAVIOR_SINGLEAGENT_LEARNING_TDMETHODS_SARSA_LAM_HPP
#define FASTRL_BEHAVIOR_SINGLEAGENT_LEARNING_TDMETHODS_SARSA_LAM_HPP

#include <queue>
#include "../../../../include/classes.h"
#include "Q_learning.h"
#include "../../options/option.h"

class SarsaLamEligibilityTrace {
public:
    double eligibility;
    State * s;
    QValue * q;
    double initialQ;

    SarsaLamEligibilityTrace(State * s_, QValue * q_, double eligibility_)
    : s(s_), q(q_), eligibility(eligibility_), initialQ(q->q) { }
};

class SarsaLam : public QLearning {
public:
    double lambda = 0.7;
    SarsaLam(SADomain * domain, double gamma, double qInit, double learningRate, double lambda)
    : QLearning(domain, gamma, qInit, learningRate) {
        sarsalamInit(lambda);
    }

    SarsaLam(SADomain * domain, double gamma, double qInit,
            double learningRate, int maxEpisodeSize, double lambda)
        : QLearning(domain, gamma, qInit, learningRate, maxEpisodeSize) {
        sarsalamInit(lambda);
    }

    SarsaLam(SADomain * domain, double gamma, double qInit, double learningRate,
            Policy * learningPolicy, int maxEpisodeSize, double lambda)
        : QLearning(domain, gamma, qInit, learningRate, learningPolicy, maxEpisodeSize) {
        sarsalamInit(lambda);
    }

    SarsaLam(SADomain * domain, double gamma, QFunction * qInit, double learningRate,
            Policy * learningPolicy, int maxEpisodeSize, double lambda)
        : QLearning(domain, gamma, qInit, learningRate, learningPolicy, maxEpisodeSize) {
        sarsalamInit(lambda);
    }

    void sarsalamInit(double l) {
        lambda = l;
    }

    Episode * runLearningEpisode(Environment * env, int maxIter) override {
        // todo double check details of how traces are added to vector, order of perusal etcetera
        State * initialState = env->currentObservation();
        auto * ea = new Episode(initialState);
        maxQChangeInMostRecentEpisode = 0.;
        State * curState = initialState;
        episodeIterationCounter = 0;
        vector<SarsaLamEligibilityTrace *> traces = vector<SarsaLamEligibilityTrace *>();
        Action * action = learningPolicy->action(curState);
        QValue * curQ = getQ(curState, action);
        while(!env->isInTerminalState() && (episodeIterationCounter < maxIter || maxIter == -1)){
            EnvironmentOutcome * eo;
            if (dynamic_cast<Option *>(action) == nullptr) {
                eo = env->act(action);
            } else {
                eo = dynamic_cast<Option *>(action)->control(env, gamma);
            }
            State * nextState = eo->o_prime;
            Action * nextAction = learningPolicy->action(nextState);
            QValue * nextQ = getQ(nextState, nextAction);
            double nextQV = nextQ->q;
            if(env->isInTerminalState()){
                nextQV = 0.;
            }
            //manage option specifics
            double r = eo->reward;
            double discount = dynamic_cast<EnvironmentOptionOutcome *>(eo) != nullptr ?
                    dynamic_cast<EnvironmentOptionOutcome *>(eo)->discount : gamma;
            long inc = dynamic_cast<EnvironmentOptionOutcome *>(eo) != nullptr ?
                    dynamic_cast<EnvironmentOptionOutcome *>(eo)->nIterations() : 1;
            episodeIterationCounter += inc;
            if (dynamic_cast<Option *>(action) == nullptr || !shouldDecomposeOptions){
                ea->transition(action, nextState, r);
            } else {
                ea->appendThenMergeEpisode(dynamic_cast<EnvironmentOptionOutcome *>(eo)->episode);
            }
            //delta
            double delta = r + (discount * nextQV) - curQ->q;
            //update all
            bool foundCurrentQTrace = false;
            for (SarsaLamEligibilityTrace * et : traces) {
                if (et->s == curState) {
                    if(et->q->a == action) {
                        foundCurrentQTrace = true;
                        et->eligibility = 1.; //replacing traces
                    } else {
                        et->eligibility = 0.; //replacing traces
                    }
                }
                double learning_rate = learningRate->pollLearningRate(agentIterationCounter, et->s, et->q->a);
                et->q->q = et->q->q + (learning_rate * et->eligibility * delta);
                et->eligibility = et->eligibility * lambda * discount;
                double deltaQ = abs(et->initialQ - et->q->q);
                if (deltaQ > maxQChangeInMostRecentEpisode){
                    maxQChangeInMostRecentEpisode = deltaQ;
                }
            }
            if (!foundCurrentQTrace) {
                //then update and add it
                double learning_rate = learningRate->pollLearningRate(agentIterationCounter, curQ->s, curQ->a);
                curQ->q = curQ->q + (learning_rate * delta);
                auto * et = new SarsaLamEligibilityTrace(curState, curQ, lambda * discount);
                traces.push_back(et);
                double deltaQ = abs(et->initialQ - et->q->q);
                if(deltaQ > maxQChangeInMostRecentEpisode){
                    maxQChangeInMostRecentEpisode = deltaQ;
                }
            }
            //move on
            curState = nextState;
            action = nextAction;
            curQ = nextQ;
            agentIterationCounter++;
        }
        return ea;
    }
};

#endif //FASTRL_BEHAVIOR_SINGLEAGENT_LEARNING_TDMETHODS_SARSA_LAM_HPP


text:
import { installHook } from '@back/hook'
import { isFirefox } from '@utils/env'

// inject the hook
if (document instanceof HTMLDocument) {
  const source = ';(' + installHook.toString() + ')(window)'

  if (isFirefox) {
    // eslint-disable-next-line no-eval
    window.eval(source) // in Firefox, this evaluates on the content window
  } else {
    const script = document.createElement('script')
    script.textContent = source
    document.documentElement.appendChild(script)
    script.parentNode.removeChild(script)
  }
}


text:
=begin

Initialize the instance variable first
define sides method
sides method should count the number of elements in the array and return that number
define method roll, which returns random value in array

=end

# Initial Solution

class Die
  def initialize(labels)
  	@labels = labels
  	if labels.length < 1
    	raise ArgumentError.new("I need more sides!")
    end
  end

  def sides
  	p @labels.length
  end

  def roll
  	random_num = rand(0..(@labels.length - 1))
  	p @labels[random_num]
  end
end

d = Die.new(["hello", 2, "my", "name", 3])
d.sides
d.roll

# Reflection
=begin

What were the main differences between this die class and the last one you created in terms of implementation?
 Did you need to change much logic to get this to work?

The main logic is still there, it's just taking the rand operator to a new level.

What does this exercise teach you about making code that is easily changeable or modifiable?

I think this code teaches us that code should be clear, concise, and the variables/method names should
represent exactly what it is.

What new methods did you learn when working on this challenge, if any?

I didn't exactly learn any new methods in this challenge.

What concepts about classes were you able to solidify in this challenge?

I was able to solidify the concept of initializing my class before doing anything in order to set the
instance variables needed.

=end


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <com.jeff.ttxs.cameracustomdemo.CameraSurfaceView
        android:id="@+id/custom_surfaceview"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="match_parent"/>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/exchange_camera"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:src="@drawable/ic_change_camera"/>
        <ImageView
            android:id="@+id/take_picture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:src="@drawable/take_picture"
            android:layout_marginBottom="15dp"/>
    </RelativeLayout>

</FrameLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">

   <!--Activa o uso de Annotation-->
    <mvc:annotation-driven />
    <!-- Activates scanning of @Autowired -->
    <context:annotation-config />
    <!-- Activates scanning of @Repository and @Service -->
    <context:component-scan base-package="pt.ulht.es.cookbook"/>

    <!-- Serve pedidos HTTP GET para /static/** de forma eficiente para recursos estáticos na pasta webapp/resources -->
    <mvc:resources mapping="/resources/**" location="/resources/" />

     <!--propertyConfigurer bean - Este bean é usado para carregar jdbc.properties
     banco de dados de arquivos de propriedade. Os detalhes de conexão de banco
     de dados são armazenados neste arquivo que é usado em configurações de conexão de hibernação.-->

    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/jdbc.properties" />

    <!--dataSource bean - Esta é a fonte de dados usada java para conectar-se em
    contato com banco de dados gerente. Nós fornecemos driver JDBC classe, nome
    de usuário, etc senha, na configuração.-->

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

    <!--
    sessionFactory bean - Este é o Hibernate configuração onde podemos definir
    diferentes configurações de hibernação. hibernate.cfg.xml é definir um arquivo
    de configuração que contém mapeamentos de classe de entidade
    -->

    <bean id="sessionFactory"

        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <!--
        viewResolver bean - Este bean definido ver resolvedor para Spring MVC.
        Para este bean também definir prefixo como "/ WEB-INF/jsp /" eo sufixo
        como ". Jsp". Assim primavera resolve automaticamente o JSP de WEB-INF/jsp
        pasta e sufixo atribuído. Jsp para ele.
    -->

    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--O namespace tx: é responsável por tratar as nossas transações de banco de dados.
    Usando o elemento tx:annotation-driven, estamos a dizer ao Spring para olhar o bean
    anotados com @Transactional  e tratá-los de acordo com os parâmetros definidos nessas anotações.  -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--transactionManager bean - Usamos hibernate gerenciador de transações para
    gerenciar as transações de nosso aplicativo gerenciador de studantes.-->

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#ifndef NATIVE_EXTENSION_VTK_VTKIMAGEITEMWRAP_H
#define NATIVE_EXTENSION_VTK_VTKIMAGEITEMWRAP_H

#include <nan.h>

#include <vtkSmartPointer.h>
#include <vtkImageItem.h>

#include "vtkContextItemWrap.h"
#include "../../plus/plus.h"

class VtkImageItemWrap : public VtkContextItemWrap
{
	public:
		using Nan::ObjectWrap::Wrap;
		static void Init(v8::Local<v8::Object> exports);
		static void InitPtpl();
		static void ConstructorGetter(
			v8::Local<v8::String> property,
			const Nan::PropertyCallbackInfo<v8::Value>& info);

		VtkImageItemWrap(vtkSmartPointer<vtkImageItem>);
		VtkImageItemWrap();
		~VtkImageItemWrap( );
		static Nan::Persistent<v8::FunctionTemplate> ptpl;

	private:
		static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);

		static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetImage(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetPosition(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void Paint(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetImage(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetPosition(const Nan::FunctionCallbackInfo<v8::Value>& info);

#ifdef VTK_NODE_PLUS_VTKIMAGEITEMWRAP_CLASSDEF
		VTK_NODE_PLUS_VTKIMAGEITEMWRAP_CLASSDEF
#endif
};

#endif


text:
typedef void(^tb_serviceOnCompletion)(BOOL status, NSError * _Nullable error);

@interface TBService (Demo)

#pragma mark - Demo
- (void)demoAPIOnSuccess:(tb_serviceOnSuccess _Nullable)success
                 failure:(tb_serviceOnFailure _Nullable)failure;

@end


text:
package work3;

/**
 * Created by Jason Song(wolfogre@outlook.com) on 12/24/2015.
 */
public class Rectangle extends Geometry {
	double side1;
	double side2;

	public Rectangle(double side1, double side2){
		this.side1 = side1;
		this.side2 = side2;
	}

	@Override
	double getArea() {
		return side1 * side2;
	}
}


text:
.class Lcom/android/server/enterprise/restriction/RestrictionPolicy$5;
.super Landroid/os/Handler;
.source "RestrictionPolicy.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/enterprise/restriction/RestrictionPolicy;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/enterprise/restriction/RestrictionPolicy;

# direct methods
.method constructor <init>(Lcom/android/server/enterprise/restriction/RestrictionPolicy;)V
    .locals 0

    iput-object p1, p0, Lcom/android/server/enterprise/restriction/RestrictionPolicy$5;->this$0:Lcom/android/server/enterprise/restriction/RestrictionPolicy;

    invoke-direct {p0}, Landroid/os/Handler;-><init>()V

    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 4

    iget v2, p1, Landroid/os/Message;->what:I

    packed-switch v2, :pswitch_data_0

    :goto_0
    return-void

    :pswitch_0
    new-instance v0, Landroid/content/ComponentName;

    const-string/jumbo v2, "com.sec.android.app.voicerecorder.service"

    const-string/jumbo v3, "com.sec.android.app.voicerecorder.service.VoiceRecorderService"

    invoke-direct {v0, v2, v3}, Landroid/content/ComponentName;-><init>(Ljava/lang/String;Ljava/lang/String;)V

    new-instance v2, Landroid/content/Intent;

    const-string/jumbo v3, "com.android.voicerecorder.HIDENOTIFICATION"

    invoke-direct {v2, v3}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    invoke-virtual {v2, v0}, Landroid/content/Intent;->setComponent(Landroid/content/ComponentName;)Landroid/content/Intent;

    move-result-object v1

    iget-object v2, p0, Lcom/android/server/enterprise/restriction/RestrictionPolicy$5;->this$0:Lcom/android/server/enterprise/restriction/RestrictionPolicy;

    invoke-static {v2}, Lcom/android/server/enterprise/restriction/RestrictionPolicy;->-get0(Lcom/android/server/enterprise/restriction/RestrictionPolicy;)Landroid/content/Context;

    move-result-object v2

    invoke-virtual {v2, v1}, Landroid/content/Context;->startService(Landroid/content/Intent;)Landroid/content/ComponentName;

    goto :goto_0

    nop

    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_0
    .end packed-switch
.end method