text:
/** \file
 * Helper functions for domain initialization -- header file.
 */

#ifndef SWIG_MULTI_BLOCK_INFO_2D_HH
#define SWIG_MULTI_BLOCK_INFO_2D_HH

#include "plbWrapper/block/multiBlockInfo2D.h"

namespace plb {

template<typename T>
MultiNTensorInfo2D<T>::MultiNTensorInfo2D(MultiNTensorField2D<T> const& multiBlock)
    : nx(),
      ny(),
      numBlocks(),
      numAllocatedCells()
{
    getMultiBlockInfo(multiBlock, nx, ny, numBlocks,
                      smallest, largest, numAllocatedCells);
}

template<typename T>
plint MultiNTensorInfo2D<T>::getNx() const {
    return nx;
}

template<typename T>
plint MultiNTensorInfo2D<T>::getNy() const {
    return ny;
}

template<typename T>
plint MultiNTensorInfo2D<T>::getNumBlocks() const {
    return numBlocks;
}

template<typename T>
plint MultiNTensorInfo2D<T>::getNumAllocatedCells() const {
    return numAllocatedCells;
}

template<typename T>
Box2D MultiNTensorInfo2D<T>::getSmallestBlock() const {
    return smallest;
}

template<typename T>
Box2D MultiNTensorInfo2D<T>::getLargestBlock() const {
    return largest;
}

}  // namespace plb

#endif  // SWIG_MULTI_BLOCK_INFO_2D_HH

redpajama_set_name: RedPajamaGithub


text:
package org.onosproject.ospf.protocol.lsa.tlvtypes;

import com.google.common.base.MoreObjects;
import com.google.common.primitives.Bytes;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onlab.packet.Ip4Address;
import org.onosproject.ospf.exceptions.OspfErrorType;
import org.onosproject.ospf.exceptions.OspfParseException;
import org.onosproject.ospf.protocol.lsa.TlvHeader;
import org.onosproject.ospf.protocol.lsa.types.TopLevelTlv;
import org.onosproject.ospf.protocol.util.OspfUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Representation of an OSPF Opaque router tlv.
 */
public class RouterTlv extends TlvHeader implements TopLevelTlv {

    private static final Logger log =
            LoggerFactory.getLogger(RouterTlv.class);
    private Ip4Address routerAddress;

    /**
     * Creates an instance of Opaque router tlv.
     *
     * @param header tlv header
     */
    public RouterTlv(TlvHeader header) {
        this.setTlvType(header.tlvType());
        this.setTlvLength(header.tlvLength());
    }

    /**
     * Gets router address.
     *
     * @return router address
     */
    public Ip4Address routerAddress() {
        return routerAddress;
    }

    /**
     * Sets router address.
     *
     * @param routerAddress router address.
     */
    public void setRouterAddress(Ip4Address routerAddress) {
        this.routerAddress = routerAddress;
    }

    /**
     * Reads bytes from channel buffer .
     *
     * @param channelBuffer channel buffer instance
     * @throws Exception might throws exception while parsing buffer
     */
    public void readFrom(ChannelBuffer channelBuffer) throws Exception {
        try {
            byte[] tempByteArray = new byte[OspfUtil.FOUR_BYTES];
            channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
            this.setRouterAddress(Ip4Address.valueOf(tempByteArray));
        } catch (Exception e) {
            log.debug("Error::RouterTLV:: {}", e.getMessage());
            throw new OspfParseException(OspfErrorType.OSPF_MESSAGE_ERROR,
                                         OspfErrorType.BAD_MESSAGE);
        }
    }

    /**
     * Gets router tlv as byte array.
     *
     * @return router tlv as byte array
     */
    public byte[] asBytes() {
        byte[] lsaMessage = null;

        byte[] tlvHeader = getTlvHeaderAsByteArray();
        byte[] tlvBody = getTlvBodyAsByteArray();
        lsaMessage = Bytes.concat(tlvHeader, tlvBody);

        return lsaMessage;
    }

    /**
     * Gets tlv body as byte array.
     *
     * @return tlv body as byte array
     */
    public byte[] getTlvBodyAsByteArray() {
        List<Byte> bodyLst = new ArrayList<>();
        bodyLst.addAll(Bytes.asList(this.routerAddress().toOctets()));

        return Bytes.toArray(bodyLst);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(getClass())
                .omitNullValues()
                .add("routerAddress", routerAddress)
                .toString();
    }
}


text:
module Pina
  module Utils
    module Pagination
      def next_page
        paginate(_meta['pagination']['next'])
      end

      def first_page
        resource.all
      end

      def previous_page
        paginate(_meta['pagination']['previous'])
      end

      def last_page
        paginate(_meta['pagination']['last'])
      end

      def paginate(page_url)
        params = extract_params(page_url)
        return unless params&.fetch('page')

        resource.all(params)
      end

      def collect_items
        resource = self

        [].tap do |collection|
          loop do
            collection.push(*resource.items)
            resource = resource.next_page

            break unless resource
          end
        end
      end

      private

      def resource
        Object.const_get("Pina::#{self.class.to_s.split('::').last}")
      end

      def extract_params(url)
        return unless url

        index = url.index('?')
        return unless index

        params_to_hash(url[index + 1..-1])
      end

      def params_to_hash(params)
        {}.tap do |params_hash|
          params.split('&').each do |element|
            param = element.split('=')
            params_hash[param.first] = param.last
          end
        end
      end
    end
  end
end


text:
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using Trainer.Domain;

namespace Code.Service.ContentProviders
{
    public class AzureContentProvider : CloudProvider, IContentProvider<Presentation>
    {
        private readonly DocumentClient _client;
        private const string _databaseId = "Trainer";
        private const string _collectionId = "Presentations";

        public AzureContentProvider()
        {
            try
            {
                _client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["azureServiceEndpoint"]), ConfigurationManager.AppSettings["azureAuthKey"]);
            } catch(Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
        }

        public async Task<IEnumerable<Presentation>> GetAllContent(string path, string pattern)
        {
            var list = new List<Presentation>();
            if (null == _client) return list;

            var db = _client.CreateDatabaseQuery()
                .Where(x => x.Id.Equals(_databaseId))
                .AsEnumerable()
                .FirstOrDefault();
            if(null == db)
            {
                //db does not exist, create it
                db = await _client.CreateDatabaseAsync(new Database { Id = _databaseId });
            }

            var collection = _client.CreateDocumentCollectionQuery(db.SelfLink)
                .Where(x => x.Id.Equals(_collectionId))
                .AsEnumerable()
                .FirstOrDefault();
            if(null == collection)
            {
                //docs collection does not exist, create it
                collection = await _client.CreateDocumentCollectionAsync(db.SelfLink, new DocumentCollection { Id = _collectionId });
            }

            var query = from p in _client.CreateDocumentQuery<Presentation>(collection.SelfLink)
                        select p;
            if(!query.AsEnumerable().Any())
            {
                var contents = GetAllLocalContent(ConfigurationManager.AppSettings["path"], ConfigurationManager.AppSettings["pattern"]);
                foreach (var presentation in contents)
                {
                    await _client.CreateDocumentAsync(collection.SelfLink, presentation);
                }

                query = contents.AsQueryable();
            }

            return query.AsEnumerable();
        }

        public Task<Presentation> GetContentById(object id)
        {
            throw new NotImplementedException();
        }

        public void UpdateContent(Presentation item)
        {
            throw new NotImplementedException();
        }

        public void DeleteContent(object id)
        {
            throw new NotImplementedException();
        }
    }
}


text:
package org.cidrz.webapp.dynasite.struts.action.admin;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.cidrz.webapp.dynasite.exception.ObjectNotFoundException;
import org.cidrz.webapp.dynasite.exception.PersistenceException;
import org.cidrz.webapp.dynasite.exception.PopulationException;
import org.cidrz.webapp.dynasite.logic.PersistenceManagerFactory;
import org.cidrz.webapp.dynasite.session.SessionUtil;
import org.cidrz.webapp.dynasite.struts.action.generic.SaveObjectAction;
import org.cidrz.webapp.dynasite.utils.BeanPopulator;
import org.cidrz.webapp.dynasite.valueobject.FormChanges;
import org.cidrz.webapp.dynasite.valueobject.Identifiable;
import org.cidrz.webapp.dynasite.valueobject.Site;
import org.cidrz.webapp.dynasite.valueobject.Form;
import org.cidrz.webapp.dynasite.dao.FormDAO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.security.Principal;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: ckelley
 * Date: Dec 1, 2004
 * Time: 5:19:28 PM
 */
public class SaveFormAction extends SaveObjectAction {

    protected Identifiable getSubject(Class clazz, Long id) throws PersistenceException, ObjectNotFoundException {
        Identifiable subject = PersistenceManagerFactory.getInstance(clazz).getOneForm(id);
        return subject;
    }

    protected void handlePersistence(ActionMapping mapping, DynaActionForm dynaForm, Identifiable subject, Class clazz, HttpServletRequest request) throws PopulationException, PersistenceException, SessionUtil.AttributeNotFoundException, ObjectNotFoundException, SQLException, ServletException {
        HttpSession session = request.getSession();
        Site site = SessionUtil.getInstance(session).getClientSettings().getSite();
        request.setAttribute(SUBJECT_KEY, subject);
        BeanPopulator.populate(dynaForm, subject);
        /*try {
            BeanUtils.copyProperties(dynaForm, subject);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }*/
        Principal user = request.getUserPrincipal();
        String userName = user.getName();
        try {
            Long formId = FormDAO.saveNewForm((Form) subject, userName, site.getId());
            // Now add this form to the FormChanges list.
            FormChanges.makeDirty(formId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*PersistenceManagerFactory.getInstance(clazz).save(subject, request.getUserPrincipal(), site);
        log.debug("*** Using PersistenceManagerFactory ***");*/
    }
}


text:
package org.jeo.filter;

import org.jeo.util.Convert;
import org.jeo.util.Optional;

/**
 * Filter that applies a binary comparison operator to two expression operands.
 *
 * @author Justin Deoliveira, OpenGeo
 */
public class Comparison extends Filter {

    /**
     * Comparison operator type.
     */
    public static enum Type {
        EQUAL("="), NOT_EQUAL("!="), LESS("<"), LESS_OR_EQUAL("<="), GREATER(">"),
        GREATER_OR_EQUAL(">=");

        String op;

        Type(String op) {
            this.op = op;
        }

        @Override
        public String toString() {
            return op;
        }
    }

    Type type;
    Expression left, right;

    public Comparison(Type type, Expression left, Expression right) {
        this.type = type;
        this.left = left;
        this.right = right;

        if (left == null || right == null) {
            throw new NullPointerException("operands must not be null");
        }
    }

    public Type getType() {
        return type;
    }

    public Expression getLeft() {
        return left;
    }

    public Expression getRight() {
        return right;
    }

    @Override
    public boolean apply(Object obj) {
        Object o1 = left.evaluate(obj);
        Object o2 = right.evaluate(obj);

        return compare(o1, o2);
    }

    protected boolean compare(Object o1, Object o2) {
        if (o1 != null && !o1.getClass().isInstance(o2)) {
            //attempt to convert
            Optional<?> converted = Convert.to(o2, o1.getClass());
            if (converted.has()) {
                o2 = converted.get();
            }
        }

        if (type == Type.EQUAL) {
            return o1 != null ? o1.equals(o2) : o2 == null;
        }
        if (type == Type.NOT_EQUAL) {
            return o1 != null ? !o1.equals(o2) : o2 != null;
        }

        if (o1 == null || o2 == null) {
            throw new IllegalArgumentException("Unable to perform comparison on null operand(s)");
        }

        Comparable<Object> c1 = toComparable(o1);
        Comparable<Object> c2 = toComparable(o2);
        int compare = c1.compareTo(c2);

        switch(type) {
        case LESS:
            return compare < 0;
        case LESS_OR_EQUAL:
            return compare <= 0;
        case GREATER:
            return compare > 0;
        case GREATER_OR_EQUAL:
            return compare >= 0;
        default:
            throw new IllegalStateException();
        }
    }

    @SuppressWarnings("unchecked")
    protected Comparable<Object> toComparable(Object o) {
        if (o instanceof Comparable) {
            return (Comparable<Object>) o;
        }
        throw new IllegalArgumentException("Unable to convert " + o + " to comparable");
    }

    @Override
    public Object accept(FilterVisitor v, Object obj) {
        return v.visit(this, obj);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((left == null) ? 0 : left.hashCode());
        result = prime * result + ((right == null) ? 0 : right.hashCode());
        result = prime * result + ((type == null) ? 0 : type.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Comparison other = (Comparison) obj;
        if (left == null) {
            if (other.left != null)
                return false;
        } else if (!left.equals(other.left))
            return false;
        if (right == null) {
            if (other.right != null)
                return false;
        } else if (!right.equals(other.right))
            return false;
        if (type != other.type)
            return false;
        return true;
    }

    @Override
    public String toString() {
        return new StringBuilder().append(left).append(" ").append(type).append(" ").append(right)
            .toString();
    }
}


text:
    © Copyright {{ site.time | date: '%Y' }} {{ site.name }}.
    Powered by Jekyll with al-folio theme. Hosted by GitHub Pages.


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zoranbogdanovski.searchmoviesapp" >

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".core.App"
        android:allowBackup="true"
        android:debuggable="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ui.SplashScreenActivity"
            android:noHistory="true"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ui.MovieSearchActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".ui.MovieDetailActivity"
            android:label="@string/title_activity_movie_detail"
            android:screenOrientation="portrait"
            android:parentActivityName=".ui.MovieSearchActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.zoranbogdanovski.searchmoviesapp.ui.MovieSearchActivity" />
        </activity>
    </application>

</manifest>


text:
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing;
using ChDCStatMenusLibrary;
using Microsoft.VisualBasic.Devices;

namespace ChDCStatMenus
{
    public partial class FrmInfo : FrmPanel
    {
        System.Timers.Timer timer = new System.Timers.Timer();

        public FrmInfo()
        {
            InitializeComponent();
        }

        private void lblMemory_MouseHover(object sender, EventArgs e)
        {
            this.ShowChild(new FrmMemory(), sender as Control);
        }

        private void lblNetwork_MouseHover(object sender, EventArgs e)
        {
            this.ShowChild(new FrmNetwork(), (sender as Control).Parent);
        }

        private void FrmInfo_Load(object sender, EventArgs e)
        {
            timer.Interval = 1000;
            timer.Elapsed += (s, e1) => this.BeginInvoke(new Action(Timer_Elapsed));

            TotalNetworkSpeed networkSpeed = new TotalNetworkSpeed(timer);
            networkSpeed.Start();
            networkSpeed.NotityInfoEvent += NetworkSpeed_NotityInfoEvent;

            Timer_Elapsed();
            lblTime.Text = DateTime.Now.ToString("D") + " " + DateTime.Now.ToString("dddd");
            lblLunisolar.Text = TimeInfo.GetChineseDateTime(DateTime.Now);
        }

        //PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        //float cpuUsage = 0;

        private void Timer_Elapsed()
        {
            ComputerInfo ci = new ComputerInfo();
            PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes", true);
            // 内存使用比例
            float totalMB = ci.TotalPhysicalMemory / 1024 / 1024;
            float usedMB = totalMB - ramCounter.NextValue();
            float memoryUsage = usedMB / totalMB;

            //picMemory.dr

            //cpuUsage = cpuCounter.NextValue() - cpuUsage;
            //MessageBox.Show(cpuUsage + "%");
            drawMemoryUsage(memoryUsage);
            lblMemory.Text = String.Format("{0:G2}GB/{1:G2}GB", usedMB / 1024, totalMB/1024);
        }

        private void drawMemoryUsage(float value)
        {

            Control control = lblMemory;
            Bitmap b = new Bitmap(control.Width, control.Height);
            Graphics g = Graphics.FromImage(b);

            //draw background
            g.FillRectangle(new SolidBrush(Color.FromArgb(28, 28, 29)), 0, 0, control.Width, control.Height);

            // draw usage rect
            int width = (int)(control.Width * value);
            Rectangle rect = new Rectangle(0, 0, width, control.Height);

            //LinearGradientBrush brush = new LinearGradientBrush(control.ClientRectangle, Color.FromArgb(17, 160, 255), Color.FromArgb(23,174,254), LinearGradientMode.Vertical);
            //brush.SetSigmaBellShape(0.5f);
            //g.FillRectangle(brush, rect);
            g.FillRectangle(new SolidBrush(Color.FromArgb(0, 186, 255)), rect);

            // border
            g.DrawRectangle(new Pen(Color.FromArgb(28, 28, 29), 3), 0, 0, control.Width-2, control.Height-2);

            g.Dispose();
            control.BackgroundImage = b;
        }

        private void NetworkSpeed_NotityInfoEvent(object sender, NetworkSpeedInfo e)
        {
            this.BeginInvoke(new Action(() => {

                lblDownloadSpeed.Text = e.BytesReceivedSpeedString;
                lblUploadSpeed.Text = e.BytesSentSpeedString;
            }));
        }

    }
}


text:
f = open("sectionmatrix.csv", "rU")

count = 0

ts =[]
t_oids=[]

sections = {}
templates={}

templates_constraints=[]

for line in f:
	line=line.strip()

	#list of templates
	if count == 4:
		ts = line.split(",")[1:]

	#list of templates oids
	if count == 6:
		t_oids = line.split(",")[1:]

		#compile list of templates
		for i, item in enumerate(ts):
			templates[item]=t_oids[i]

	#sections constraints
	if count >6:
		section = line.split(",")[0]
		oid = section.split("(")[1].split(")")[0]
		section  = section.split("(")[0]

		sections[section]=oid

		constraints = line.split(",")[1:]

		#extract all constraints into separata list
		for i, item in enumerate(constraints):
			if len(item)>0:
				#print item, templates[i], section
				print item, ts[i], section
				templates_constraints.append([item, ts[i], section])

	#print line.strip()
	count=count+1

#print ts
#print t_oids

print "\n"
print templates
print sections

f2 = open("clinicalstatementmatrix.csv", "rU")
count = 0

ts =[]
t_oids=[]

sections = {}
templates={}

statements = {}

sections_constraints=[]

print "======"

count=0
for line in f2:
	#list of templates
	if count == 4:
		ts = line.strip().split(",")[1:]
	#list of templates oids
	if count == 6:
		t_oids = line.strip().split(",")[1:]

	#clinical statements constraints
	if count >6:
		statement = line.strip().split(",")[0]
		oid = statement.split("(")[1].split(")")[0]
		statement  = statement.split("(")[0]

		statements[statement]=oid

		constraints = line.split(",")[1:]

		#print constraints

		#extract all constraints into separata list
		for i, item in enumerate(constraints):
			if len(item.strip())>0:
				item=item.strip()
				#print item, templates[i], section
				print ">>> ",item, ts[i], statement
				sections_constraints.append([item, ts[i], statement])

	#print line.strip()
	count=count+1

print "\n"
print statements

#print len(statements)

print "\n"
print templates_constraints
print "\n"
print sections_constraints

tc={}

for item in templates_constraints:
	c, template, section = item
	const = c.split(" ")[0]
	if const == "O": const = "may"
	if const == "R": const = "shall"
	if const == "R2": const = "should"
	num = c.split(":")[1][:-1]
	print const, num, template, section

	if template not in tc.keys():
		tc[template]={}

	if const not in tc[template].keys():
		tc[template][const]={}

	tc[template][const][section]=num

	if "full" not in tc[template].keys():
		tc[template]["full"]={}

	tc[template]["full"][section]={"constraint":const,"id":num}

sc={}
for item in sections_constraints:
	#print item
	c, section, statement = item
	const = c.split(" ")[0]
	if const == "O": const = "may"
	if const == "R": const = "shall"
	if const == "R2": const = "should"
	if len(c.split(":"))==2:
		num = c.split(":")[1][:-1]
		num2=""
	else:
		num= c.split(":")[1].split("CONF")[0]
		num2= c.split(":")[2][:-1]
	print const, num, num2, section, statement

	if section not in sc.keys():
		sc[section]={}

	if const not in sc[section].keys():
		sc[section][const]={}

	if num2=="": sc[section][const][statement]=[num]
	else: sc[section][const][statement]=[num, num2]

	if "full" not in sc[section].keys():
		sc[section]["full"]={}

	if num2=="": sc[section]["full"][statement]={"constraint":const,"id":[num]}
	else: sc[section]["full"][statement]={"constraint":const,"id":[num, num2]}

print "\n"
print tc
print "\n"
print sc


text:
from django.conf.urls import patterns, url

from webapp import views

urlpatterns = patterns('',
    url(r'^(home/)?$', views.home, name="home"),
    url(r'^tracker/$', views.tracker, name="nutritionTracker"),
    url(r'^about/(?P<item>[A-Za-z]+)?$', views.about, name="about"),
    url(r'^contact/$', views.contact, name="contact")
)


text:
<html>
<head>
<script src="../../../http/tests/inspector/inspector-test.js"></script>
<script src="../../../http/tests/inspector/console-test.js"></script>
<script src="../../../http/tests/inspector/debugger-test.js"></script>
<script>

var globalVar = { b: 1 };

function slave(x)
{
    var y = 20;
    debugger;
}

function testFunction()
{
    var localObject = { a: 300 };
    slave(4000);
}

var test = function()
{
    InspectorTest.startDebuggerTest(step1);

    function step1()
    {
        InspectorTest.runTestFunctionAndWaitUntilPaused(step2);
    }

    function step2(callFrames)
    {
        InspectorTest.evaluateInConsole("x + y + globalVar.b", step3.bind(null, callFrames));
    }

    function step3(callFrames, result)
    {
        InspectorTest.addResult("Evaluated script on the top frame: " + result);
        var pane = WebInspector.panels.sources.sidebarPanes.callstack;
        pane._callFrameSelected(pane.callFrames[1]);
        InspectorTest.deprecatedRunAfterPendingDispatches(step4);
    }

    function step4()
    {
        InspectorTest.evaluateInConsole("localObject.a + globalVar.b", step5);
    }

    function step5(result)
    {
        InspectorTest.addResult("Evaluated script on the calling frame: " + result);
        InspectorTest.completeDebuggerTest();
    }
}

</script>
</head>

<body onload="runTest()">
<p>
Tests that evaluation in console works fine when script is paused. It also checks that
stack and global variables are accessible from the console.
</p>

</body>
</html>


text:
neuromancy
==========

Neural Network implementation using Python (Numpy and theano).

This package includes wrapper classes for neural networks constructed using the theano package.

The classes can be used for quickly generating neural networks, but the code is more useful for
understanding how to build networks using theano.

See mnist_nnet_demos.py for demonstrations that show how to build and train neural networks to classify digits from
the MNIST data set.

neural_net.py provides implementations for three classes of neural networks: logistic regressions, multi-layer
perceptrons, and the LeNet classifier.

sgd_trainer.py provides a class used for training networks by stochastic gradient descent.


text:
void drafter_ctest_fail(const char* expr, const char* file, size_t line);

#define REQUIRE(expr) drafter_ctest_assert(expr != 0, #expr, __FILE__, __LINE__)
void drafter_ctest_assert(int a, const char* expr, const char* file, size_t line);

#define REQUIRE_INCLUDES(searched, actual) drafter_ctest_includes(searched, actual, __FILE__, __LINE__)
void drafter_ctest_includes(const char* expected, const char* actual, const char* file, size_t line);

#define REQUIRE_EXCLUDES(searched, actual) drafter_ctest_excludes(searched, actual, __FILE__, __LINE__)
void drafter_ctest_excludes(const char* expected, const char* actual, const char* file, size_t line);

#endif


text:
namespace blink {

namespace worker_pool {

void PostTask(const base::Location& location, CrossThreadOnceClosure closure) {
  PostTask(location, {base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
           std::move(closure));
}

void PostTask(const base::Location& location,
              const base::TaskTraits& traits,
              CrossThreadOnceClosure closure) {
  base::ThreadPool::PostTask(location, traits,
                             ConvertToBaseOnceCallback(std::move(closure)));
}

}  // namespace worker_pool

}  // namespace blink


text:
var uuid = require('uuid');

export class Alert {
  public title: string;
  public service: string = "";
  public serviceInError: string = "";
  public correlationId: string;
  public timeUID: string;
  public businessImpact: string = "";
  public technicalImpact: string = "";
  public severity: string = "";
  public timeStampUTC: Date;
  public host: string = "";
  public additionalInformation: string = "";
  public owner: string = "";
  public status: string = "";
  public modifiedUTC: Date;

  constructor(title: string, correlationId: string = null) {
    this.title = title;
    this.timeStampUTC = new Date();
    this.modifiedUTC = new Date();
    this.timeUID = uuid.v1();
    this.correlationId = correlationId || this.timeUID;
  }

  public static create(alert_base: any): Alert {
    let alert: Alert = new Alert(this.selectRandom(alert_base.title));
    alert.service = this.selectRandom(alert_base.service);
    alert.serviceInError = this.selectRandom(alert_base.serviceInError);
    alert.businessImpact = this.selectRandom(alert_base.businessImpact);
    alert.technicalImpact = this.selectRandom(alert_base.technicalImpact);
    alert.severity = this.selectRandom(alert_base.severity);
    alert.host = this.selectRandom(alert_base.host);
    alert.additionalInformation = this.selectRandom(alert_base.additionalInformation);
    return alert;
  }

  private static selectRandom(array: any): string {
    return array[Math.floor(Math.random() * array.length)];
  }
}


text:
import 'mocha';

import { expect, ifExitCodeIsOtherThan, logOutput, PickEvent, when } from '@integration/testing-tools';
import { InteractionFinished, InteractionStarts, SceneFinished, SceneFinishes, SceneStarts, SceneTagged, TaskFinished, TaskStarts } from '@serenity-js/core/lib/events';
import { ExecutionSuccessful, FeatureTag, Name } from '@serenity-js/core/lib/model';

import { cucumber, cucumberVersion } from '../src';

describe(`@serenity-js/cucumber with Cucumber ${ cucumberVersion() }`, () => {

    when(7 <= cucumberVersion().major())
        .it('recognises Screenplay activities in any part of a Cucumber scenario', () =>

            cucumber('features/hooks.feature', 'hooks.steps.ts')
            .then(ifExitCodeIsOtherThan(0, logOutput))
            .then(result => {
                expect(result.exitCode).to.equal(0);

                PickEvent.from(result.events)
                    // before all
                    .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Helen performs in BeforeAll')))
                    .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Helen performs in BeforeAll')))

                    // first scenario
                    .next(SceneStarts,         event => expect(event.details.name).to.equal(new Name('First screenplay scenario')))
                    .next(SceneTagged,         event => expect(event.tag).to.equal(new FeatureTag('Serenity/JS recognises Cucumber hooks')))

                    // Before
                    .next(TaskStarts,          event => expect(event.details.name).to.equal(new Name('Before')))
                    .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Helen performs in Before')))
                    .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Helen performs in Before')))
                    .next(TaskFinished,        event => expect(event.details.name).to.equal(new Name('Before')))

                    // Given
                    .next(TaskStarts,          event => expect(event.details.name).to.equal(new Name('Given Amanda fulfills a task')))

                        // BeforeStep
                        .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Helen performs in BeforeStep')))
                        .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Helen performs in BeforeStep')))

                        // ... actual Given
                        .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Amanda performs in Given')))
                        .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Amanda performs in Given')))

                        // AfterStep
                        .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Helen performs in AfterStep')))
                        .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Helen performs in AfterStep')))

                    .next(TaskFinished,         event => expect(event.details.name).to.equal(new Name('Given Amanda fulfills a task')))

                    // after
                    .next(TaskStarts,          event => expect(event.details.name).to.equal(new Name('After')))
                    .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Helen performs in After')))
                    .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Helen performs in After')))
                    .next(TaskFinished,        event => expect(event.details.name).to.equal(new Name('After')))

                    .next(SceneFinishes,       event => expect(event.outcome).to.equal(new ExecutionSuccessful()))
                    .next(SceneFinished,       event => expect(event.outcome).to.equal(new ExecutionSuccessful()))

                    // second scenario
                    .next(SceneStarts,         event => expect(event.details.name).to.equal(new Name('Second screenplay scenario')))
                    .next(SceneTagged,         event => expect(event.tag).to.equal(new FeatureTag('Serenity/JS recognises Cucumber hooks')))

                    // Before
                    .next(TaskStarts,          event => expect(event.details.name).to.equal(new Name('Before')))
                    .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Helen performs in Before')))
                    .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Helen performs in Before')))
                    .next(TaskFinished,        event => expect(event.details.name).to.equal(new Name('Before')))

                    // Given
                    .next(TaskStarts,          event => expect(event.details.name).to.equal(new Name('Given Beth fulfills a task')))

                        // BeforeStep
                        .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Helen performs in BeforeStep')))
                        .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Helen performs in BeforeStep')))

                        // ... actual Given
                        .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Beth performs in Given')))
                        .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Beth performs in Given')))

                        // AfterStep
                        .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Helen performs in AfterStep')))
                        .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Helen performs in AfterStep')))

                    .next(TaskFinished,         event => expect(event.details.name).to.equal(new Name('Given Beth fulfills a task')))

                    // after
                    .next(TaskStarts,          event => expect(event.details.name).to.equal(new Name('After')))
                    .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Helen performs in After')))
                    .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Helen performs in After')))
                    .next(TaskFinished,        event => expect(event.details.name).to.equal(new Name('After')))

                    .next(SceneFinishes,       event => expect(event.outcome).to.equal(new ExecutionSuccessful()))
                    .next(SceneFinished,       event => expect(event.outcome).to.equal(new ExecutionSuccessful()))

                    // after all
                    .next(InteractionStarts,   event => expect(event.details.name).to.equal(new Name('Helen performs in AfterAll')))
                    .next(InteractionFinished, event => expect(event.details.name).to.equal(new Name('Helen performs in AfterAll')))
                ;
            }));
});


text:
"""
AUTO-GENERATED BY `scripts/generate_protocol.py` using `data/browser_protocol.json`
and `data/js_protocol.json` as inputs! Please do not modify this file.
"""

import logging
from typing import Any, Optional, Union

from chromewhip.helpers import PayloadMixin, BaseEvent, ChromeTypeBase

log = logging.getLogger(__name__)

# StreamHandle: This is either obtained from another method or specifed as `blob:<uuid>` where`<uuid&gt` is an UUID of a Blob.
StreamHandle = str

class IO(PayloadMixin):
    """ Input/Output operations for streams produced by DevTools.
    """
    @classmethod
    def close(cls,
              handle: Union['StreamHandle'],
              ):
        """Close the stream, discard any temporary backing storage.
        :param handle: Handle of the stream to close.
        :type handle: StreamHandle
        """
        return (
            cls.build_send_payload("close", {
                "handle": handle,
            }),
            None
        )

    @classmethod
    def read(cls,
             handle: Union['StreamHandle'],
             offset: Optional['int'] = None,
             size: Optional['int'] = None,
             ):
        """Read a chunk of the stream
        :param handle: Handle of the stream to read.
        :type handle: StreamHandle
        :param offset: Seek to the specified offset before reading (if not specificed, proceed with offset
following the last read). Some types of streams may only support sequential reads.
        :type offset: int
        :param size: Maximum number of bytes to read (left upon the agent discretion if not specified).
        :type size: int
        """
        return (
            cls.build_send_payload("read", {
                "handle": handle,
                "offset": offset,
                "size": size,
            }),
            cls.convert_payload({
                "base64Encoded": {
                    "class": bool,
                    "optional": True
                },
                "data": {
                    "class": str,
                    "optional": False
                },
                "eof": {
                    "class": bool,
                    "optional": False
                },
            })
        )

    @classmethod
    def resolveBlob(cls,
                    objectId: Union['Runtime.RemoteObjectId'],
                    ):
        """Return UUID of Blob object specified by a remote object id.
        :param objectId: Object id of a Blob object wrapper.
        :type objectId: Runtime.RemoteObjectId
        """
        return (
            cls.build_send_payload("resolveBlob", {
                "objectId": objectId,
            }),
            cls.convert_payload({
                "uuid": {
                    "class": str,
                    "optional": False
                },
            })
        )


text:
/****
 *
 * This script is called from Node.js to process a SVG floorplan into:
 * 1) a high-res PNG that will be used as a background image
 * 2) a new SVG that will contain only overlay/interactive features:
 *      a) interior spaces
 *      b) labels
 *
 * It uses D3.js to process the SVG DOM and PhantomJS to render PNGs
 *
 * In the future it can be parameterized and turned into a web service
 * in order to dynamically change the background image.
 * We may also look into using something like Mapnik or TileStache to
 * split the high-res into tiles for improved performance
 *
 *
 * Note: I had to pull down this fork of the phantomjs-node module
 * https://github.com/sebv/phantomjs-node
 *
 */

'use strict';

var PNGPath = '/app/media/png/',
	SVGPath = '/app/media/svg/';

var ConvertSVG = function (filename) {
	this.filename = filename;
};

ConvertSVG.prototype = {
	filename: null,

	/**
	 * Create PNG
	 * @param fileSource
	 * @param fileTarget
	 * @param width
	 * @param height
	 * @param resolutionMultiplier
 * @param tileTarget
	 */
	createPNG: function (fileSource, fileTarget, tileTarget, width, height, resolutionMultiplier) {
		//setup phantomJS to render PNG
		var phantom = require('phantom');
		phantom.create(function (ph) {
			return ph.createPage(function (page) {
				//set page dimensions
				var pageWidth = width * resolutionMultiplier,
					pageHeight = height * resolutionMultiplier;
				page.set('viewportSize', {width: pageWidth, height: pageHeight});
				console.log("PNG Dimensions Width:" + pageWidth + " Height:" + pageHeight);

				return page.open(fileSource, function (status) {
					if (status !== 'success') {
						console.log('Unable to load: ' + fileSource);
						ph.exit();
					} else {
						page.render(fileTarget);
						console.log('Render Complete!');
						ph.exit();

						var gm = require('gm'),
							fs = require('fs'),

							cropHeight =   pageHeight / 2,
							cropWidth =   pageWidth / 2;

						//upperLeft
						gm(fileTarget).crop(cropWidth, cropHeight, 0, 0)
							.background('white')
							.flatten()
							.matteColor('white')
							.write(tileTarget + "-bg-ul.jpg", function (err) {
								if (!err) {
									console.log(' Saved ul tile ');
								} else {
									console.log(err);
								}
							});

						//lowerLeft
						gm(fileTarget).crop(cropWidth, cropHeight, 0, cropHeight)
							.background('white')
							.flatten()
							.matteColor('white')
							.write(tileTarget + "-bg-ll.jpg", function (err) {
								if (!err) {
									console.log(' Saved ll tile ');
								} else {
									console.log(err);
								}
							});

						//upperRight
						gm(fileTarget).crop(cropWidth, cropHeight, cropWidth, 0)
							.background('white')
							.flatten()
							.matteColor('white')
							.write(tileTarget + "-bg-ur.jpg", function (err) {
								if (!err) {
									console.log(' Saved ur tile ');
								} else {
									console.log(err);
								}
							});

						//lowerRight
						gm(fileTarget).crop(cropWidth, cropHeight, cropWidth, cropHeight)
							.background('white')
							.flatten()
							.matteColor('white')
							.write(tileTarget + "-bg-lr.jpg", function (err) {
								if (!err) {
									console.log(' Saved lr tile ');
								} else {
									console.log(err);
								}
							});

					}
				});
			});
		});
	},

	/**
	 * Write data to file
	 * @param data
	 * @param fileTarget
	 */
	writeFile: function (data, fileTarget) {
		var fs = require('fs');
		//write  to file
		fs.writeFileSync(fileTarget, data);

	},

	//Not using any of this stuff for now
	/*mapValue: function (value, minTo, maxTo, minFrom, maxFrom) {
		return minTo + (maxTo - minTo) * ((value - minFrom) / (maxFrom - minFrom));
	},

	projectCADToLatLng: function (latlng, minX, minY, maxX, maxY) {
		var targetMinX = -10.0,
			targetMinY = -5.0,
			targetMaxX = 10.0,
			targetMaxY = 5.0,

			mappedLat = this.mapValue(latlng.lat, targetMinY, targetMaxY, minY, maxY),
			mappedLng = this.mapValue(latlng.lng, targetMinX, targetMaxX, minX, maxX);

		return {lat: mappedLat, lng: mappedLng};

	},

	createGDALTranslateCall: function (viewBox, target) {
		//gdal_translate -of GTiff -a_ullr ullat ullon lrlat lelon  -a_srs EPSG:4269 input.tif output.tif
									//       ulx uly lrx lry
		var ullaty =  Number(viewBox.yMin) + Number(viewBox.height),
			ullonx = viewBox.xMin,
			lrlaty = viewBox.yMin,
			lrlonx = Number(viewBox.xMin) + Number(viewBox.width),

			ul = this.projectCADToLatLng({lat: ullaty, lng: ullonx}, ullonx, lrlaty, lrlonx, ullaty),
			lr = this.projectCADToLatLng({lat: lrlaty, lng: lrlonx}, ullonx, lrlaty, lrlonx, ullaty),

			output = "gdal_translate -of GTiff -a_ullr " +
				ul.lng.toString() + " " + ul.lat.toString() + " " + lr.lng.toString() + " " + lr.lat.toString() +
				" -a_srs EPSG:4326 " + target + " " + target;

		return output;

	},*/

	/**
	 * Convert
	 */
	convert: function () {

		global.document = require("jsdom").jsdom("");
		global.window = global.document.createWindow();

		var fs = require('fs'),
			ofp = require('openfloorplan'),

			source =  __dirname + SVGPath + this.filename + '.svg',
			backgroundTarget =  __dirname + PNGPath + this.filename + '-bg.png',
			tileTarget =  __dirname + PNGPath + this.filename,
			overlayTarget =  __dirname + SVGPath + this.filename + '-ol.svg',
			resolutionMultiplier =  15,
			convertSVG = this; //need a local scope reference;

		console.log("File: " + backgroundTarget);

		/////////////
		//Overlay
		/////////////
		fs.readFile(source, function (err, data) {
			if (err) {
				throw err;
			}

			var fp, viewBox;

			console.log("loaded SVG file");

			//set body as the SVG data
			global.document.body.innerHTML = data;
			//get the floorplan
			fp = new ofp.FloorPlan(global.document.body);

			//flag everything for removal
			fp.svg.selectAll('g [type=level]').classed('tmp-removed', true);
			//un-flag the stuff we want to keep
			fp.spaces.layer.classed('tmp-removed', false);
			fp.dimensionAnnotations.layer.classed('tmp-removed', false);

			//remove everything else
			fp.svg.selectAll('.tmp-removed').remove();

			convertSVG.writeFile(fp.exportSVG(), overlayTarget);

		});

		//////////////////
		//Background
		/////////////////
		//read the source SVG file
		fs.readFile(source, function (err, data) {
			if (err) {
				throw err;
			}

			var fp, viewBox;

			console.log("loaded SVG file");

			//set body as the SVG data
			global.document.body.innerHTML = data;
			//get the floorplan
			fp = new ofp.FloorPlan(global.document.body);

			viewBox = fp.getViewBox();

			fp.dimensionAnnotations.remove();

			convertSVG.writeFile(fp.exportSVG(), "temp.svg");

			convertSVG.createPNG("temp.svg", backgroundTarget, tileTarget, viewBox.width, viewBox.height, resolutionMultiplier);

		});

	}

};

//run it
new ConvertSVG("fs-hi200-01").convert();