text:
<?php
namespace Dala00\Upload\Test\TestCase\Model\Behavior;

use ArrayObject;
use Cake\Event\Event;
use Cake\TestSuite\TestCase;
use Dala00\Upload\File\DebugFileSystem;
use Dala00\Upload\Model\Behavior\UploadBehavior;

/**
 * Upload\Model\Behavior\UploadBehavior Test Case
 */
class UploadBehaviorTest extends TestCase
{

    /**
     * Test subject
     *
     * @var \Upload\Model\Behavior\UploadBehavior
     */
    public $Upload;
    public $Table;

    /**
     * setUp method
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();
        $this->schema = $this->getMockBuilder('Schema')
            ->disableOriginalConstructor()
            ->setMethods(['columnType'])
            ->getMock();
        $methods = get_class_methods('Cake\ORM\Table');
        $this->Table = $this->getMockBuilder('Cake\ORM\Table')
            ->disableOriginalConstructor()
            ->setMethods($methods)
            ->getMock();
        $this->Table->expects($this->any())
            ->method('schema')
            ->will($this->returnValue($this->schema));
        $this->defaultConfig = [
            'fields' => [
                'test' => ['path' => 'webroot{DS}files{DS}{primaryKey}{DS}{field}{DS}'],
            ],
        ];
        $this->Upload = new UploadBehavior($this->Table, $this->defaultConfig);
        $this->Upload->fileSystem(new DebugFileSystem);

        $this->dataOk = [
            'field' => [
                'tmp_name' => 'path/to/file',
                'name' => 'derp',
                'error' => UPLOAD_ERR_OK,
                'size' => 1,
                'type' => 'text',
            ]
        ];
        $this->dataError = [
            'field' => [
                'tmp_name' => 'path/to/file',
                'name' => 'derp',
                'error' => UPLOAD_ERR_NO_FILE,
                'size' => 0,
                'type' => '',
            ]
        ];
        $this->settings = ['fields' => ['field' => []]];
        $this->behaviorMethods = get_class_methods('Dala00\Upload\Model\Behavior\UploadBehavior');
    }

    /**
     * tearDown method
     *
     * @return void
     */
    public function tearDown()
    {
        unset($this->Upload);
        unset($this->Table);

        parent::tearDown();
    }

    public function testBeforeMarshalOk()
    {
        $validator = $this->getMockBuilder('Cake\Validation\Validator')
            ->disableOriginalConstructor()
            ->setMethods(['isEmptyAllowed'])
            ->getMock();
        $validator->expects($this->once())
            ->method('isEmptyAllowed')
            ->will($this->returnValue(true));

        $table = $this->getMockBuilder('Cake\ORM\Table')
            ->disableOriginalConstructor()
            ->setMethods(['validator'])
            ->getMock();
        $table->expects($this->once())
            ->method('validator')
            ->will($this->returnValue($validator));

        $methods = array_diff($this->behaviorMethods, ['beforeMarshal']);
        $behavior = $this->getMockBuilder('Dala00\Upload\Model\Behavior\UploadBehavior')
            ->setConstructorArgs([$table, $this->settings])
            ->setMethods($methods)
            ->getMock();
        $behavior->expects($this->any())
            ->method('config')
            ->will($this->returnValue($this->settings));

        $data = new ArrayObject($this->dataOk);
        $behavior->beforeMarshal(new Event('fake.event'), $data, new ArrayObject);
        $this->assertEquals(new ArrayObject($this->dataOk), $data);
    }

    public function testBeforeMarshalError()
    {
        $validator = $this->getMockBuilder('Cake\Validation\Validator')
            ->disableOriginalConstructor()
            ->setMethods(['isEmptyAllowed'])
            ->getMock();
        $validator->expects($this->once())
            ->method('isEmptyAllowed')
            ->will($this->returnValue(true));

        $table = $this->getMockBuilder('Cake\ORM\Table')
            ->disableOriginalConstructor()
            ->setMethods(['validator'])
            ->getMock();
        $table->expects($this->once())
            ->method('validator')
            ->will($this->returnValue($validator));

        $methods = array_diff($this->behaviorMethods, ['beforeMarshal']);
        $behavior = $this->getMockBuilder('Dala00\Upload\Model\Behavior\UploadBehavior')
            ->setConstructorArgs([$table, $this->settings])
            ->setMethods($methods)
            ->getMock();
        $behavior->expects($this->any())
            ->method('config')
            ->will($this->returnValue($this->settings));

        $data = new ArrayObject($this->dataError);
        $behavior->beforeMarshal(new Event('fake.event'), $data, new ArrayObject);
        $this->assertEquals(new ArrayObject, $data);
    }

    public function testBeforeMarshalEmptyAllowed()
    {
        $validator = $this->getMockBuilder('Cake\Validation\Validator')
            ->disableOriginalConstructor()
            ->setMethods(['isEmptyAllowed'])
            ->getMock();
        $validator->expects($this->once())
            ->method('isEmptyAllowed')
            ->will($this->returnValue(false));

        $table = $this->getMockBuilder('Cake\ORM\Table')
            ->disableOriginalConstructor()
            ->setMethods(['validator'])
            ->getMock();
        $table->expects($this->once())
            ->method('validator')
            ->will($this->returnValue($validator));

        $methods = array_diff($this->behaviorMethods, ['beforeMarshal']);
        $behavior = $this->getMockBuilder('Dala00\Upload\Model\Behavior\UploadBehavior')
            ->setConstructorArgs([$table, $this->settings])
            ->setMethods($methods)
            ->getMock();
        $behavior->expects($this->any())
            ->method('config')
            ->will($this->returnValue($this->settings));

        $data = new ArrayObject($this->dataError);
        $behavior->beforeMarshal(new Event('fake.event'), $data, new ArrayObject);
        $this->assertEquals(new ArrayObject($this->dataError), $data);
    }

    public function testSave()
    {
        $event = new Event('testevent');
        $options = new ArrayObject;
        $entity = $this->getMockBuilder('Cake\ORM\Entity')
            ->disableOriginalConstructor()
            ->setMethods(['get', 'set'])
            ->getMock();
        $defaultValue = [
            'name' => 'filename',
            'tmp_name' => 'tmp_name',
            'size' => 5,
            'error' => UPLOAD_ERR_OK,
        ];
        $entity->expects($this->any())
            ->method('get')
            ->will($this->onConsecutiveCalls(
                $defaultValue,
                $defaultValue,
                $defaultValue,
                5
            ));
        $fileSystem = $this->Upload->fileSystem();
        $fileSystem->addFiles($defaultValue['tmp_name']);
        $files = $fileSystem->getFiles();
        $this->Upload->beforeSave($event, $entity, $options);
        $this->Upload->afterSave($event, $entity, $options);
        $newfiles = $fileSystem->getFiles();
        $this->assertEquals(count($files) + 1, count($newfiles));
        $this->assertEquals(true, in_array($defaultValue['tmp_name'], $newfiles));
    }

    public function testSaveForConfirm()
    {
        $event = new Event('testevent');
        $options = new ArrayObject;
        $entity = $this->getMockBuilder('Cake\ORM\Entity')
            ->disableOriginalConstructor()
            ->setMethods(['get', 'set'])
            ->getMock();
        $defaultValue = [
            'name' => 'filename',
            'tmp_name' => 'tmp_name',
            'size' => 5,
            'error' => UPLOAD_ERR_OK,
        ];
        $cachedValue = $defaultValue;
        $cachedValue['cache'] = 'aiueawefijoa';
        $entity->expects($this->any())
            ->method('get')
            ->will($this->onConsecutiveCalls(
                $defaultValue,
                $defaultValue,
                $defaultValue,
                $defaultValue,
                $defaultValue,
                5
            ));
        $fileSystem = $this->Upload->fileSystem();
        $fileSystem->addFiles($defaultValue['tmp_name']);
        $files = $fileSystem->getFiles();
        $this->Upload->uploadTmpFile($entity);
        $this->Upload->beforeSave($event, $entity, $options);
        $this->Upload->afterSave($event, $entity, $options);
        $newfiles = $fileSystem->getFiles();
        $this->assertEquals(count($files) + 2, count($newfiles));
        $this->assertEquals(false, in_array($cachedValue['cache'], $newfiles));
    }

    public function testUploadTmpFile()
    {
        $entity = $this->getMockBuilder('Cake\ORM\Entity')
            ->disableOriginalConstructor()
            ->setMethods(['get', 'set'])
            ->getMock();
        $tmpName = 'tmpname';
        $entity->expects($this->any())
            ->method('get')
            ->will($this->returnValue([
                'name' => 'filename',
                'tmp_name' => $tmpName,
                'size' => 5,
                'error' => UPLOAD_ERR_OK,
            ]));

        $fileSystem = $this->Upload->fileSystem();
        $fileSystem->addFiles($tmpName);
        $oldfiles = $fileSystem->getFiles();
        $this->Upload->uploadTmpFile($entity);
        $this->assertEquals(count($oldfiles) + 1, count($fileSystem->getFiles()));
    }

    public function testGetUploadFolder()
    {
        $id = '5';

        $this->Table->expects($this->once())
            ->method('alias')
            ->will($this->returnValue('tablename'));
        $this->Table->expects($this->once())
            ->method('primaryKey')
            ->will($this->returnValue('id'));

        $entity = $this->getMockBuilder('Cake\ORM\Entity')
            ->disableOriginalConstructor()
            ->setMethods(['get'])
            ->getMock();
        $entity->expects($this->once())
            ->method('get')
            ->will($this->returnValue($id));

        $folder = $this->Upload->getUploadFolder($entity, 'test');
        $this->assertContains($id, $folder);
    }
}


text:
xcode-demos
===========

Demo projects for XCode course

redpajama_set_name: RedPajamaGithub


text:
{% extends "page.html" %}

{% block content %}

Page not found

{% endblock %}


text:
using System;
using CondenserDotNet.Client.DataContracts;

namespace CondenserDotNet.Client
{
    public class HealthConfiguration
    {
        public bool IgnoreTls { get; set; } = true;
        public string Url { get; set; }
        public int IntervalInSeconds { get; set; } = 30;

        public HealthCheck Build(IServiceManager manager)
        {
            if (Url == null) return null;
            if (!Uri.TryCreate(Url, UriKind.Absolute, out Uri uri))
            {
                var scheme = manager.ProtocolSchemeTag ?? "http";
                var builder = new UriBuilder(scheme, manager.ServiceAddress, manager.ServicePort, Url);
                uri = builder.Uri;
            }

            var check = new HealthCheck
            {
                HTTP = uri.ToString(),
                Interval = $"{IntervalInSeconds}s",
                Name = $"{manager.ServiceId}:HttpCheck",
                tls_skip_verify = IgnoreTls
            };

            return check;
        }
    }
}


text:
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver

from ..models import Commit, UTopic, send_mail
from .related.delete import (
    delete_related_bookmark, delete_related_views, delete_related_vote
)

@receiver(pre_delete, sender=Commit)
def when_commit_delete(sender, instance, **kwargs):
    delete_related_bookmark(sender, instance.id)
    delete_related_vote(sender, instance.id)
    delete_related_views(sender, instance.id)

@receiver(post_save, sender=Commit)
def when_commit_create(sender, instance, created, **kwargs):
    if created:
        if instance.status == "waiting":
            # when someone contribute a content
            utopic = UTopic.objects.get(id=instance.utopic.id)
            utopic.open_contribution += 1
            utopic.save()

            send_mail(
                subject=f"{ instance.user } contributed your article | coogger",
                template_name="email/contribute.html",
                context=dict(get_absolute_url=instance.get_absolute_url),
                to=[instance.content.user],
            )

        # NOTE previous commit is set
        instance.previous_commit = instance.get_previous_commit
        instance.save(update_fields=["previous_commit"])


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

using Eventualize.Domain.MetaModel;
using Eventualize.Interfaces.BaseTypes;

using FluentAssertions;

using Xunit;

namespace Eventualize.Test.Domain.MetaModel
{
    public class BoundedContextMetaModelTest
    {
        [Fact]
        public void BoundedContextMetaModelStoresAggregatesAndEventsByName()
        {
            var boundedContextName = new BoundedContextName("alsdkjsd");
            var eventTypeName1= new EventTypeName("sdklfdgjhsfkfdfsg");
            var eventTypeName2 = new EventTypeName("öäldfgpödortz");
            var aggregateTypeName1 = new AggregateTypeName("kldjoiödrfgh");
            var aggregateTypeName2 = new AggregateTypeName("äölfkdöoktz");

            var boundedContextMetaModel = new BoundedContextMetaModel(boundedContextName,
                new[]
                {
                    new AggregateMetaModel(boundedContextName, aggregateTypeName1, null, null),
                    new AggregateMetaModel(boundedContextName, aggregateTypeName2, null, null)
                },
                 new[]
                {
                    new EventMetaModel(boundedContextName, eventTypeName1, null),
                    new EventMetaModel(boundedContextName, eventTypeName2, null)
                }
                );

            boundedContextMetaModel.BoundedContextName.Should().Be(boundedContextName);
            boundedContextMetaModel.AggregateTypes.Count().Should().Be(2);
            boundedContextMetaModel.EventTypes.Count().Should().Be(2);

            boundedContextMetaModel.GetAggregateType(aggregateTypeName1).TypeName.Should().Be(aggregateTypeName1);
            boundedContextMetaModel.GetAggregateType(aggregateTypeName2).TypeName.Should().Be(aggregateTypeName2);
            boundedContextMetaModel.GetAggregateType(new AggregateTypeName("sdlökjlödfghh")).Should().BeNull();

            boundedContextMetaModel.GetEventType(eventTypeName1).TypeName.Should().Be(eventTypeName1);
            boundedContextMetaModel.GetEventType(eventTypeName2).TypeName.Should().Be(eventTypeName2);
            boundedContextMetaModel.GetEventType(new EventTypeName("s.dkfjdflghöös")).Should().BeNull();
        }
    }
}


text:
// Provides control sap.ui.core.Message.
sap.ui.define(['./Element', './library', "sap/base/Log", "sap/ui/core/Configuration"],
	function(Element, library, Log, Configuration) {
	"use strict";

	// shortcut
	var MessageType = library.MessageType;

	/**
	 * Constructor for a new Message.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * This element is used to provide messages.
	 *
	 * Rendering must be done within the control that uses this kind of element. Its default level is none.
	 * @extends sap.ui.core.Element
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @public
	 * @alias sap.ui.core.Message
	 */
	var Message = Element.extend("sap.ui.core.Message", /** @lends sap.ui.core.Message.prototype */ { metadata : {

		library : "sap.ui.core",
		properties : {

			/**
			 * Message text
			 */
			text : {type : "string", group : "Misc", defaultValue : null},

			/**
			 * Message's timestamp. It is just a simple String that will be used without any transformation. So the application that uses messages needs to format the timestamp to its own needs.
			 */
			timestamp : {type : "string", group : "Misc", defaultValue : null},

			/**
			 * A possible icon URI of the message
			 */
			icon : {type : "sap.ui.core.URI", group : "Misc", defaultValue : null},

			/**
			 * Setting the message's level.
			 */
			level : {type : "sap.ui.core.MessageType", group : "Misc", defaultValue : MessageType.None},

			/**
			 * Determines whether the message should be read only. This helps the application to handle a message a different way if the application differentiates between read-only and common messages.
			 * @since 1.19.0
			 */
			readOnly : {type : "boolean", group : "Misc", defaultValue : false}
		}
	}});

	/**
	 * Returns the icon's default URI depending on given size.
	 *
	 * @param {string} [sSize="16x16"] Only the values "16x16" or "32x32" are allowed. Otherwise the default value is used.
	 * @return {sap.ui.core.URI} URI of the default icon.
	 * @public
	 */
	Message.prototype.getDefaultIcon = function(sSize) {
		var sModulePath = sap.ui.require.toUrl("sap/ui/core/themes/" + Configuration.getTheme());

		var sImagesPath = sModulePath + "/img/message/";
		if (sSize && sSize == "32x32") {
			sImagesPath += "32x32/";
		} else {
			sImagesPath += "16x16/";
		}
		var sUrl = "";

		switch (this.getProperty("level")) {
		case MessageType.Error:
			sUrl = sImagesPath + "Message_Icon_Error.png";
			break;

		case MessageType.Information:
			sUrl = sImagesPath
					+ "Message_Icon_Information.png";
			break;

		case MessageType.Warning:
			sUrl = sImagesPath + "Message_Icon_Warning.png";
			break;

		case MessageType.Success:
			sUrl = sImagesPath + "Message_Icon_Success.png";
			break;

		case MessageType.None:
		default:
			sUrl = this.getProperty("icon");
			break;
		}

		return sUrl;
	};

	/**
	 * Compares the given message with this message. The types of
	 * {@link sap.ui.core.MessageType} are ordered from "Error" > "Warning" > "Success" >
	 * "Information" > "None".
	 *
	 * See  {@link sap.ui.core.Message.compareByType}
	 *
	 * @param {sap.ui.core.Message} oOther message to compare with this one
	 * @return {int} returns 0 if both messages are at
	 *         the same level. -1 if this
	 *         message has a lower level. 1 if this
	 *         message has a higher level.
	 * @public
	 */
	Message.prototype.compareByType = function(oOther) {
		return Message.compareByType(this, oOther);
	};

	/**
	 * Compares two given messages with each other.
	 *
	 * The types of {@link sap.ui.core.MessageType} are ordered from "Error" > "Warning" > "Success" >
	 * "Information" > "None".
	 *
	 * @param {sap.ui.core.Message} oMessage1 first message to compare
	 * @param {sap.ui.core.Message} oMessage2 second message to compare
	 * @return {int} returns 0 if both messages are at
	 *         the same level. -1 if this
	 *         message has a lower level. 1 if this
	 *         message has a higher level.
	 * @static
	 * @public
	 */
	Message.compareByType = function(oMessage1, oMessage2) {
		if (!oMessage1 && !oMessage2) {
			return 0;
		}
		if (oMessage1 && !oMessage2) {
			return 1;
		}
		if (!oMessage1 && oMessage2) {
			return -1;
		}

		var sLvl1 = oMessage1.getLevel();
		var sLvl2 = oMessage2.getLevel();

		if (sLvl1 === sLvl2) {
			return 0;
		}

		switch (sLvl1) {
		case MessageType.Error:
			return 1;

		case MessageType.Warning:
			return sLvl2 === MessageType.Error ? -1 : 1;

		case MessageType.Success:
			return sLvl2 === MessageType.Error || sLvl2 === MessageType.Warning ? -1 : 1;

		case MessageType.Information:
			return sLvl2 === MessageType.None ? 1 : -1;

		case MessageType.None:
			return -1;

		default:
			Log.error("Comparison error", this);
			return 0;
		}
	};

	return Message;

});


text:
using System.Collections.Generic;
using System.Linq;
using Opserver.Data.Elastic;

namespace Opserver
{
    public class ElasticSettings : ModuleSettings
    {
        public override bool Enabled => Clusters?.Any() ?? false;
        public override string AdminRole => ElasticRoles.Admin;
        public override string ViewRole => ElasticRoles.Viewer;

        /// <summary>
        /// elastic search clusters to monitor
        /// </summary>
        public List<Cluster> Clusters { get; set; } = new List<Cluster>();

        public class Cluster : ISettingsCollectionItem
        {
            /// <summary>
            /// Nodes in this cluster
            /// </summary>
            public List<string> Nodes { get; set; } = new List<string>();

            /// <summary>
            /// The machine name for this SQL cluster
            /// </summary>
            public string Name { get; set; }

            public string Description { get; set; }

            /// <summary>
            /// The authorization header, if any, to send on requests.
            /// </summary>
            public string AuthorizationHeader { get; set; }

            /// <summary>
            /// How many seconds before polling this cluster for status again
            /// </summary>
            public int RefreshIntervalSeconds { get; set; } = 120;

            /// <summary>
            /// How many seconds before polling this cluster for status again, if the cluster status is not green
            /// </summary>
            public int DownRefreshIntervalSeconds { get; set; } = 10;
        }
    }
}


text:
---
id: 58a7a6ebf9a6318348e2d5aa
title: Modify Fill Mode of an Animation
challengeType: 0
videoUrl: 'https://scrimba.com/c/cVJDmcE'
forumTopicId: 301064
---

## Description

That's great, but it doesn't work right yet. Notice how the animation resets after 500ms has passed, causing the button to revert back to the original color. You want the button to stay highlighted.
This can be done by setting the animation-fill-mode property to forwards. The animation-fill-mode specifies the style applied to an element when the animation has finished. You can set it like so:
animation-fill-mode: forwards;

## Instructions

Set the animation-fill-mode property of button:hover to forwards so the button stays highlighted when a user hovers over it.

## Tests

```yml
tests:
  - text: <code>button:hover</code> should have a <code>animation-fill-mode</code> property with a value of <code>forwards</code>.
    testString: assert(code.match(/button\s*?:\s*?hover\s*?{[\s\S]*animation-fill-mode\s*?:\s*?forwards\s*?;[\s\S]*}/gi) && code.match(/button\s*?:\s*?hover\s*?{[\s\S]*animation-name\s*?:\s*?background-color\s*?;[\s\S]*}/gi) && code.match(/button\s*?:\s*?hover\s*?{[\s\S]*animation-duration\s*?:\s*?500ms\s*?;[\s\S]*}/gi));

```

## Challenge Seed

```html
<style>
  button {
    border-radius: 5px;
    color: white;
    background-color: #0F5897;
    padding: 5px 10px 8px 10px;
  }
  button:hover {
    animation-name: background-color;
    animation-duration: 500ms;
    /* add your code below this line */

    /* add your code above this line */
  }
  @keyframes background-color {
    100% {
      background-color: #4791d0;
    }
  }
</style>
<button>Register</button>
```

## Solution

```html
<style>
  button {
    border-radius: 5px;
    color: white;
    background-color: #0F5897;
    padding: 5px 10px 8px 10px;
  }
  button:hover {
    animation-name: background-color;
    animation-duration: 500ms;
    animation-fill-mode: forwards;
  }
  @keyframes background-color {
    100% {
      background-color: #4791d0;
    }
  }
</style>
<button>Register</button>
```


text:
namespace mojo {
namespace internal {

template <typename MaybeConstUserType>
struct Serializer<StringDataView, MaybeConstUserType> {
  using UserType = typename std::remove_const<MaybeConstUserType>::type;
  using Traits = StringTraits<UserType>;

  static void Serialize(MaybeConstUserType& input,
                        MessageFragment<String_Data>& fragment) {
    if (CallIsNullIfExists<Traits>(input))
      return;

    auto r = Traits::GetUTF8(input);
    fragment.AllocateArrayData(r.size());
    memcpy(fragment->storage(), r.data(), r.size());
  }

  static bool Deserialize(String_Data* input,
                          UserType* output,
                          Message* message) {
    if (!input)
      return CallSetToNullIfExists<Traits>(output);
    bool ok = Traits::Read(StringDataView(input, message), output);
    if (ok && !Traits::IsValidUTF8(*output)) {
      RecordInvalidStringDeserialization();
    }
    return ok;
  }
};

}  // namespace internal
}  // namespace mojo

#endif  // MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_


text:
package com.gogaworm.easyjlpt.db;

import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;

import java.util.List;

@Dao
public interface ExamDao {
    @Insert
    long insert(Exam exam);

    @Query("select * from Exam where lessonId=:lessonId")
    List<Exam> getExamForLesson(int lessonId);
}


text:
Simple PWA leveraging the new 💷 Payment Request API 💷

https://coffee-zanonnicola.surge.sh/

![Demo](http://noce.london/imgs/coffee.jpg)

## Introducing Payment Request API

Payment Request is a new API for the open web that makes checkout flows easier, faster and consistent on shopping sites.

* Provides a native user interface for users to select or add a payment method, a shipping address and a shipping option in an easy, fast and consistent way.
* Provides standardized imperative APIs for developers to obtain user's payment preferences in a consistent format.

[Find out More](https://developers.google.com/web/updates/2016/07/payment-request)

## How to use it

If you are using an Android device you can try it out using a test card:

```
VISA

4005519200000004
07/19
890
```
## Browser support

http://caniuse.com/#feat=payment-request

Note: Can be enabled via the "Experimental Web Platform features" flag in _Chrome_


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>NativeMmap</title>
<meta name="date" content="2014-08-20">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bulldog.linux.jni

Class NativeMmap

java.lang.Object

org.bulldog.linux.jni.NativeMmap

public class NativeMmap
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

static int
EXEC

static int
NONE

static int
PRIVATE

static int
READ

static int
SHARED

static int
WRITE

Constructor Summary

Constructors

Constructor and Description

NativeMmap()

Method Summary

Methods

Modifier and Type
Method and Description

static long
createMap(long address,
         long length,
         int protection,
         int flags,
         int fileDescriptor,
         long offset)

static int
deleteMap(long address,
         long length)

static byte
getByteValueAt(long address)

static int
getIntValueAt(long address)

static long
getLongValueAt(long address)

static short
getShortValueAt(long address)

static void
setByteValueAt(long address,
              byte value)

static void
setIntValueAt(long address,
             int value)

static void
setLongValueAt(long address,
              long value)

static void
setShortValueAt(long address,
               short value)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

NONE

public static final int NONE

See Also:

Constant Field Values

READ

public static final int READ

See Also:

Constant Field Values

WRITE

public static final int WRITE

See Also:

Constant Field Values

EXEC

public static final int EXEC

See Also:

Constant Field Values

SHARED

public static final int SHARED

See Also:

Constant Field Values

PRIVATE

public static final int PRIVATE

See Also:

Constant Field Values

Constructor Detail

NativeMmap

public NativeMmap()

Method Detail

createMap

public static long createMap(long address,
             long length,
             int protection,
             int flags,
             int fileDescriptor,
             long offset)

deleteMap

public static int deleteMap(long address,
            long length)

setLongValueAt

public static void setLongValueAt(long address,
                  long value)

getLongValueAt

public static long getLongValueAt(long address)

setIntValueAt

public static void setIntValueAt(long address,
                 int value)

getIntValueAt

public static int getIntValueAt(long address)

setShortValueAt

public static void setShortValueAt(long address,
                   short value)

getShortValueAt

public static short getShortValueAt(long address)

setByteValueAt

public static void setByteValueAt(long address,
                  byte value)

getByteValueAt

public static byte getByteValueAt(long address)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.apache.shindig.gadgets;

import org.apache.shindig.common.util.OpenSocialVersion;
import org.apache.shindig.gadgets.features.FeatureRegistry;
import org.apache.shindig.gadgets.preload.PreloadedData;
import org.apache.shindig.gadgets.spec.Feature;
import org.apache.shindig.gadgets.spec.GadgetSpec;
import org.apache.shindig.gadgets.spec.LocaleSpec;
import org.apache.shindig.gadgets.spec.View;
import org.apache.shindig.gadgets.uri.UriCommon;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * Intermediary representation of all state associated with processing
 * of a single gadget request.
 */
public class Gadget {
  private FeatureRegistry featureRegistry;
  private GadgetContext context;
  private GadgetSpec spec;
  private Collection<PreloadedData> preloads;
  private View currentView;
  private Set<String> directFeatureDeps;

  /**
   * @param context The request that the gadget is being processed for.
   */
  public Gadget setContext(GadgetContext context) {
    this.context = context;
    directFeatureDeps = null;  //New context means View may have changed
    allGadgetFeatures = null;
    return this;
  }

  public GadgetContext getContext() {
    return context;
  }

  /**
   * @param registry The gadget feature registry to use to find dependent
   *                 features.
   */
  public synchronized Gadget setGadgetFeatureRegistry(FeatureRegistry registry) {
    this.featureRegistry = registry;
    return this;
  }

  /**
   * @param spec The spec for the gadget that is being processed.
   */
  public Gadget setSpec(GadgetSpec spec) {
    this.spec = spec;
    return this;
  }

  public GadgetSpec getSpec() {
    return spec;
  }

  /**
   * Returns open social specification version for this Gadget
   * @return Version for this Gadget
   */
  public OpenSocialVersion getSpecificationVersion(){
    if(spec != null){
      return spec.getSpecificationVersion();
    }
    return null;
  }

  /**
   * Returns if the doctype attribute is set to quirksmode.
   * Needed to override default OpenSocial 2.0 behavior which is to render in standards mode,
   * may not be possible to honor this attribute when inlining (caja)
   *
   * @return TRUE if this Gadget should be rendered in browser quirks mode
   */
  public boolean useQuirksMode(){
    if(spec != null){
      return GadgetSpec.DOCTYPE_QUIRKSMODE.equals(spec.getModulePrefs().getDoctype());
    }
    return false;
  }

  /**
   * @param preloads The preloads for the gadget that is being processed.
   */
  public Gadget setPreloads(Collection<PreloadedData> preloads) {
    this.preloads = preloads;
    return this;
  }

  public Collection<PreloadedData> getPreloads() {
    return preloads;
  }

  /**
   * List of all features this spec depends on (including all transitive
   * dependencies).
   */
  private List<String> allGadgetFeatures;
  public synchronized List<String> getAllFeatures() {
    if (allGadgetFeatures == null) {
      Preconditions.checkState(featureRegistry != null, "setGadgetFeatureRegistry must be called before Gadget.getAllFeatures()");
      allGadgetFeatures = featureRegistry.getFeatures(Lists.newArrayList(getDirectFeatureDeps()));
    }
    return allGadgetFeatures;
  }

  public Gadget setCurrentView(View currentView) {
    this.currentView = currentView;
    return this;
  }

  /**
   * @return The View applicable for the current request.
   */
  public View getCurrentView() {
    return currentView;
  }

  /**
   * Convenience function for getting the locale spec for the current context.
   *
   * Identical to:
   * Locale locale = gadget.getContext().getLocale();
   * gadget.getSpec().getModulePrefs().getLocale(locale);
   */
  public LocaleSpec getLocale() {
    View view = getCurrentView();
    String viewName = (view == null) ? GadgetSpec.DEFAULT_VIEW : view.getName();
    return spec.getModulePrefs().getLocale(context.getLocale(), viewName);
  }

  private void initializeFeatureDeps() {
    if (directFeatureDeps == null) {
      directFeatureDeps = Sets.newHashSet();
      // If we have context, lets generate the correct set of views.
      if (context != null) {
        directFeatureDeps.addAll(spec.getModulePrefs()
            .getViewFeatures(context.getView()).keySet());
      } else {
        directFeatureDeps.addAll(spec.getModulePrefs().getFeatures().keySet());
      }
    }
  }

  public void addFeature(String name) {
    initializeFeatureDeps();
    directFeatureDeps.add(name);
  }

  public void removeFeature(String name) {
    initializeFeatureDeps();
    directFeatureDeps.remove(name);
  }

  public Set<String> getDirectFeatureDeps() {
    initializeFeatureDeps();
    return Collections.unmodifiableSet(directFeatureDeps);
  }

  /**
   * Convenience method that returns Map of features to load for gadget's current view
   *
   * @return a map of ModuleSpec/Require and ModuleSpec/Optional elements to Feature
   */
  public Map<String, Feature> getViewFeatures() {
    View view = getCurrentView();
    String name = (view == null) ? GadgetSpec.DEFAULT_VIEW : view.getName();

    return spec.getModulePrefs().getViewFeatures(name);
  }

  /**
   * Should the gadget content be sanitized on output
   * @return
   */
  public boolean sanitizeOutput() {
    return (getCurrentView() != null &&
        getCurrentView().getType() == View.ContentType.HTML_SANITIZED) ||
        "1".equals(getContext().getParameter(UriCommon.Param.SANITIZE.getKey()));
  }

  /**
   * True if the gadget opts into caja or the container forces caja
   */
  public boolean requiresCaja() {
    if ("1".equals(
        getContext().getParameter(UriCommon.Param.CAJOLE.getKey()))) {
      return true;
    }
    if (featureRegistry != null) {
      return getAllFeatures().contains("caja");
    } else {
      return getViewFeatures().containsKey("caja");
    }
  }
}


text:
package com.intellij.android.designer.model.layout.relative;

import com.intellij.android.designer.designSurface.RootView;
import com.intellij.android.designer.designSurface.graphics.DesignerGraphics;
import com.intellij.android.designer.designSurface.graphics.DrawingStyle;
import com.intellij.android.designer.model.RadViewComponent;
import com.intellij.designer.model.RadComponent;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.intellij.android.designer.designSurface.graphics.DrawingStyle.*;
import static com.intellij.android.designer.model.layout.relative.DependencyGraph.Constraint;

/**
 * The {@link GuidelinePainter} is responsible for painting guidelines during an operation
 * which uses a {@link GuidelineHandler} such as a resize operation.
 */
public final class GuidelinePainter extends JComponent {
  private static final AlphaComposite ALPHA_COMPOSITE = AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f);

  @NotNull private final GuidelineHandler myState;

  public GuidelinePainter(@NotNull GuidelineHandler state) {
    myState = state;
  }

  @Override
  protected void paintComponent(Graphics graphics) {
    super.paintComponent(graphics);

    DesignerGraphics g = new DesignerGraphics(graphics, this);
    paint(g);
  }

  private void paint(@NotNull DesignerGraphics g) {
    g.useStyle(DRAGGED);
    for (RadViewComponent dragged : myState.myDraggedNodes) {
      Rectangle bounds = dragged.getBounds(g.getTarget());
      if (!bounds.isEmpty()) {
        g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
      }
    }

    Set<RadViewComponent> horizontalDeps = myState.myHorizontalDeps;
    Set<RadViewComponent> verticalDeps = myState.myVerticalDeps;
    Set<RadViewComponent> deps = new HashSet<RadViewComponent>(horizontalDeps.size() + verticalDeps.size());
    deps.addAll(horizontalDeps);
    deps.addAll(verticalDeps);
    if (deps.size() > 0) {
      g.useStyle(DEPENDENCY);
      for (RadViewComponent n : deps) {
        // Don't highlight the selected nodes themselves
        if (myState.myDraggedNodes.contains(n)) {
          continue;
        }
        Rectangle bounds = n.getBounds(g.getTarget());
        g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
      }
    }

    // If the layout has padding applied, draw the padding bounds to make it obvious what the boundaries are
    if (!myState.layout.getPadding().isEmpty() || !myState.layout.getMargins().isEmpty()) {
      g.useStyle(DrawingStyle.PADDING_BOUNDS);
      JComponent target = myState.myContext.getArea().getFeedbackLayer();
      Rectangle bounds = myState.layout.getPaddedBounds(target);
      g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);
    }

    if (myState.myBounds != null) {
      Rectangle bounds = myState.myBounds;
      if (myState instanceof MoveHandler) {
        List<RadComponent> myComponents = myState.getContext().getComponents();
        if (myComponents.size() == 1) {
          RadComponent component = myComponents.get(0);
          final Rectangle targetBounds = component.getBounds(g.getTarget());
          RootView nativeComponent = (RootView)((RadViewComponent)component.getRoot()).getNativeComponent();
          if (nativeComponent != null) {
            final BufferedImage image = nativeComponent.getImage();
            final Rectangle sourceBounds = component.getBounds();
            Graphics2D g2d = (Graphics2D)g.getGraphics();
            Composite prevComposite = g2d.getComposite();
            try {
              if (image != null) {
                g2d.setComposite(ALPHA_COMPOSITE);
                g2d.drawImage(image, bounds.x, bounds.y, bounds.x + targetBounds.width, bounds.y + targetBounds.height, sourceBounds.x,
                              sourceBounds.y, sourceBounds.x + sourceBounds.width, sourceBounds.y + sourceBounds.height, null);
              }
            } finally {
              g2d.setComposite(prevComposite);
            }
          }
        }

        g.useStyle(DROP_PREVIEW);
      }
      else {
        // Resizing
        if (myState.haveSuggestions()) {
          g.useStyle(RESIZE_PREVIEW);
        }
        else {
          g.useStyle(RESIZE_FAIL);
        }
      }
      g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);

      // Draw baseline preview too
      // TODO: Implement when we have drag information from palette drag previews
      //if (myFeedback.dragBaseline != -1) {
      //  int y = myState.myBounds.y + myFeedback.dragBaseline;
      //  g.drawLine(myState.myBounds.x, y, myState.myBounds.x + myState.myBounds.width, y);
      //}
    }

    showMatch(g, myState.getCurrentLeftMatch(), myState);
    showMatch(g, myState.getCurrentRightMatch(), myState);
    showMatch(g, myState.getCurrentTopMatch(), myState);
    showMatch(g, myState.getCurrentBottomMatch(), myState);

    if (myState.myHorizontalCycle != null) {
      paintCycle(g, myState.myHorizontalCycle);
    }
    if (myState.myVerticalCycle != null) {
      paintCycle(g, myState.myVerticalCycle);
    }
  }

  /**
   * Paints a particular match constraint
   */
  private static void showMatch(DesignerGraphics g, Match m, GuidelineHandler state) {
    if (m == null) {
      return;
    }
    ConstraintPainter.paintConstraint(g, state, m);
  }

  private static Point center(Rectangle rectangle) {
    return new Point(rectangle.x + rectangle.width / 2, rectangle.y + rectangle.height / 2);
  }

  /**
   * Paints a constraint cycle
   */
  void paintCycle(DesignerGraphics g, List<Constraint> cycle) {
    assert cycle.size() > 0;

    RadViewComponent from = cycle.get(0).from.node;
    assert from != null;
    Rectangle fromBounds = from.getBounds(g.getTarget());
    if (myState.myDraggedNodes.contains(from)) {
      fromBounds = myState.myBounds;
    }
    Point fromCenter = center(fromBounds);
    List<Point> points = new ArrayList<Point>();
    points.add(fromCenter);

    for (Constraint constraint : cycle) {
      assert constraint.from.node == from;
      RadViewComponent to = constraint.to.node;
      assert to != null;

      Point toCenter = center(to.getBounds(g.getTarget()));
      points.add(toCenter);

      // Also go through the dragged node bounds
      boolean isDragged = myState.myDraggedNodes.contains(to);
      if (isDragged) {
        toCenter = center(myState.myBounds);
        points.add(toCenter);
      }

      from = to;
      fromCenter = toCenter;
    }

    points.add(fromCenter);
    points.add(points.get(0));

    g.useStyle(CYCLE);
    for (int i = 1, n = points.size(); i < n; i++) {
      Point a = points.get(i - 1);
      Point b = points.get(i);
      g.drawLine(a.x, a.y, b.x, b.y);
    }
  }
}


text:
Imports BVSoftware.Bvc5.Core
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.IO

Partial Class BVModules_Themes_Foundation4_Responsive_Controls_ContentColumnControl
    Inherits System.Web.UI.UserControl

    Private _ColumnID As String = String.Empty
    Private _ColumnName As String = String.Empty

    Public Property ColumnID() As String
        Get
            Return _ColumnID
        End Get
        Set(ByVal value As String)
            _ColumnID = value
        End Set
    End Property
    Public Property ColumnName() As String
        Get
            Return _ColumnName
        End Get
        Set(ByVal value As String)
            _ColumnName = value
        End Set
    End Property

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        LoadColumn()
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Public Sub LoadColumn()
        Me.phColumn.Controls.Clear()

        Dim c As New Content.ContentColumn

        If _ColumnID <> String.Empty Then
            c = Content.ContentColumn.FindByBvin(_ColumnID)
        Else
            c = Content.ContentColumn.FindByDisplayName(_ColumnName)
        End If

        If c IsNot Nothing Then
            If c.Blocks.Count > 0 Then
                For i As Integer = 0 To c.Blocks.Count - 1
                    LoadContentBlock(c.Blocks(i))
                Next
                Me.Visible = True

                ' edit link
                Dim userId = SessionManager.GetCurrentUserId()
                If Not String.IsNullOrEmpty(userId) AndAlso Membership.UserAccount.DoesUserHaveAllPermissions(userId, New Collection(Of String)(New String() {Membership.SystemPermissions.ContentView})) Then
                    Dim lnkEdit As New HyperLink()
                    lnkEdit.Text = "Edit"
                    lnkEdit.ToolTip = c.DisplayName
                    lnkEdit.NavigateUrl = "~/BVAdmin/Content/Columns_Edit.aspx?id=" + c.Bvin
                    lnkEdit.CssClass = "customButton"
                    lnkEdit.Target = If(WebAppSettings.StoreAdminLinksInNewWindow, "_blank", "")
                    Me.phColumn.Controls.Add(lnkEdit)
                End If
            Else
                Me.Visible = False  ' hide empty Content Columns
            End If
        End If
    End Sub

    Private Sub LoadContentBlock(ByVal b As Content.ContentBlock)
        Dim plugin As System.Web.UI.Control = Content.ModuleController.LoadContentBlock(b.ControlName, Me.Page)
        If plugin IsNot Nothing Then
            If TypeOf plugin Is Content.BVModule Then
                CType(plugin, Content.BVModule).BlockId = b.Bvin
                Me.phColumn.Controls.Add(plugin)
            End If
        End If
    End Sub

End Class


text:
/*
 * Webpack dev configuration
 */
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = require('./webpack.config.base')({
  devtool: 'cheap-module-eval-source-map',
  entry: [
    path.resolve('src/index.js'),
  ],
  output: {
    filename: 'app.js',
  },
  cssLoaders: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]!postcss'),
  plugins: [
    new ExtractTextPlugin('app.css', {
      allChunks: true,
    }),
  ],
  babelQuery: {
    cacheDirectory: true,
  },
});


text:
package codes.rusty.jagar.net.packets.out;

import codes.rusty.jagar.net.packets.PacketOut;
import com.google.common.io.LittleEndianDataOutputStream;
import java.io.IOException;

public class PacketOutClearNodes extends PacketOut {

    public PacketOutClearNodes() {}

    @Override
    protected void write(LittleEndianDataOutputStream output) throws IOException {}

}


text:
//
//  CSHTTPRequestWork.m
//  文件上传的封装(工具类)基本POST请求
//
//  Created by 姚彦兆 on 15/10/18.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

#define kBoundary @"boundary"

#import "CSHTTPRequestWork.h"

@implementation CSHTTPRequestWork

/**
 *  上传多个文件并且附带普通文字参数的方法
 *
 *  @param requestURLString      请求的服务器的URL地址字符串
 *  @param fileMessageDictionary 待上传的文件信息字典,其中Key为服务器存储的文件名称,value为文件路径
 *  @param fileKey               服务器接收文件存储的关键字,由后台设置
 *  @param paramterDictionary    普通参数的信息字典,其中Key为服务器接受参数的关键字,value为参数内容
 *  @param completeQueue         完成后回调Block执行的线程
 *  @param uploadSuccess         上传请求成功后的回调Block
 *  @param uploadFailed          上传请求失败后的回调Block
 */
-(void)uploadMoreFilePOSTRequestWithURLString:(nonnull NSString *)requestURLString
                     andFileMessageDictionary:(nonnull NSDictionary *)fileMessageDictionary
                                   andFileKey:(nonnull NSString *)fileKey
                  andNormalParamterDictionary:(nonnull NSDictionary *)paramterDictionary
                             andCompleteQueue:(nonnull dispatch_queue_t)completeQueue
                              andSuccessBlock:(nonnull uploadMSuccessed)uploadSuccess
                                 andFailBlock:(nonnull failedBlock)uploadFailed{

    NSURL * requestURL = [NSURL URLWithString:requestURLString];

    //设置可变网络请求
    NSMutableURLRequest * customRequest = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:0 timeoutInterval:15];

    //设置请求头信息
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",kBoundary];

    [customRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];

    customRequest.HTTPMethod = @"POST";

    //设置二进制Body信息
    NSData * httpBody = [self getHTTPBodyWithFileMessageDictionary:fileMessageDictionary andNormalParamaterDictionary:paramterDictionary andFilekey:fileKey] ;

    customRequest.HTTPBody = httpBody ;

    //向服务器发送请求
    [[[NSURLSession sharedSession] uploadTaskWithRequest:customRequest fromData:httpBody completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            if (data && !error) {

                NSLog(@"上传成功...");

                if (uploadSuccess) {

                    id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

                    uploadSuccess(result , response);

                }

            }else{

                NSLog(@"上传失败...");

                if (uploadFailed) {

                    uploadFailed(error);

                }

            }

    }] resume];

}

/**
 *  自定义上传单文件的方法
 *
 *  @param requestURLString 上传文件请求的URL地址
 *  @param filePath         文件的路径(在本地需要上传的文件的路径)
 *  @param fileKey          服务器接受文件存储信息的Key值(存储文件类型 , 文件名称 , 文件大小 , 错误信息等)
 *  @param fileName         上传后保存在服务期端的文件名
 *  @param completeQueue    完成后的回调方法运行的线程
 *  @param successBlock     完成后回调(成功)
 *  @param failedBlock      完成后回调(失败)
 */
-(void)uploadFilePOSTRequestWithURLString:(nonnull NSString *)requestURLString
                            andFilePath:(nonnull NSString*)filePath
                             andFileKey:(nonnull NSString *)fileKey
                            andFileName:(NSString * _Nullable)fileName
                       andCompleteQueue:(nonnull dispatch_queue_t)completeQueue
                        andSuccessBlock:(nonnull successBlcok)successBlock
                           andFailBlock:(nonnull failedBlock)failedBlock{

    NSURL * requestURL = [NSURL URLWithString:requestURLString];

    NSMutableURLRequest * customRequest = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:0 timeoutInterval:15];

    //设置请求头信息,告诉服务器我发送的请求
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",kBoundary];
    [customRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];

    customRequest.HTTPMethod = @"POST";

    //自定义方法返回HTTPBody
    NSData * httpBody = [self getHTTPBodyWithFilePath:filePath andServersFileKey:fileKey andFileNameToSaveOnServers:fileName];

    customRequest.HTTPBody = httpBody ;

    //使用Session的Upload方法对文件进行上传
    [[[NSURLSession sharedSession] uploadTaskWithRequest:customRequest fromData:httpBody completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        dispatch_async(completeQueue, ^{

            if (data && !error) {

                if (successBlock) {
                    //成功后(网页有响应)的返回Block
                    successBlock(data,response);
                }
            }else
            {
                if (failedBlock) {
                    //服务器无响应的Block
                    failedBlock(error);
                }
            }

        });

    }] resume];

//    [NSURLConnection sendAsynchronousRequest:customRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//
//
//    }];

}

/**
 *  发送普通POST请求 传递HTML的参数
 *
 *  @param requestURL    请求的URL
 *  @param paramaterDic  传给服务器的参数
 *  @param completeQueue 完成后回调的Block执行的线程
 *  @param successBlock  完成后Block(成功)
 *  @param failedBlock   完成后Block(失败)
 */

-(void)sendPOSTRequestWithURLString:(nonnull NSString *)requestURLString
                       andParamater:(NSDictionary* _Nullable)paramaterDic
                   andCompleteQueue:(nonnull dispatch_queue_t)completeQueue
                    andSuccessBlock:(nonnull successBlcok)successBlock
                       andFailBlock:(nonnull failedBlock)failedBlock{

    //根据传入的字符串处理得到URL与请求(line)[32 , 34]
    NSURL * requestURL = [NSURL URLWithString:requestURLString];

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    //设置请求方式为POST
    request.HTTPMethod = @"POST" ;

    if (paramaterDic) {

    //设置参数的容器
    __block NSMutableString * requestSTR = [NSMutableString stringWithFormat:@""];

    //遍历字典取出参数
    [paramaterDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {

        NSString * seversKey = key;

        NSString * seversValue = obj;

        //拼接参数
        [requestSTR appendString:[NSString stringWithFormat:@"%@=%@&" , seversKey , seversValue]];

    }];

    //格式化参数
    requestSTR = (NSMutableString *)[requestSTR substringToIndex:(requestSTR.length - 1)] ;

    /**
     *  格式化参数方法2
     */
    //requestSTR = (NSMutableString *)[requestSTR stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"&"]];
    //二进制化字符串设置请求体
    NSData * parameterData = [requestSTR dataUsingEncoding:NSUTF8StringEncoding];

    request.HTTPBody = parameterData ;
    }
    //发送请求
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        dispatch_async(completeQueue, ^{

            if (data) {

                //请求成功有返回值
                if (successBlock) {

                    //给自定义回调Block传递参数
                    successBlock(data , response) ;

//                    NSLog(@"%@" , [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);

                }

            }else{

                //请求失败,网络连接问题
                if (failedBlock) {

                    //给自定义回调Block传递参数
                    failedBlock(error);

                }

            }

        });

    }] resume];

}

/**
 *  获得HTTPBody内容(多文件内容&参数)
 *
 *  @param fileMessageDictionary 文件信息字典,其中Key值为文件在服务器中存储的名称,value为文件在本地存储的路径,用来获取文件的二进制数据写入请求体
 *  @param paramaterDictionary   普通参数字典,其中的Key值为服务器接受文件的关键字,由后台管理;value值式是传入的内容
 *  @param fileKey               服务器接受上传文件的关键字,由后台管理
 */
-(nonnull NSData * )getHTTPBodyWithFileMessageDictionary:(nonnull NSDictionary *)fileMessageDictionary
                    andNormalParamaterDictionary:(nonnull NSDictionary *)paramaterDictionary
                                      andFilekey:(nonnull NSString *)fileKey{

    //设置二进制容器存储请求体信息
    NSMutableData * messageData = [NSMutableData data];

    //遍历文件信息字典获取文件的请求体信息
    [fileMessageDictionary enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {

        //文件字典Key值:文件在服务器被保存的名称
        NSString * fileName = key;

        //文件字典Value值:文件在本地的存储路径
        NSString * filePath = obj;

        //封装请求头信息
        NSMutableString * headSTR = [NSMutableString stringWithFormat:@"\r\n--%@\r\n" , kBoundary];

        [headSTR appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename=%@\r\n" , fileKey , fileName]];

        NSURLResponse * response = [self getFileTypeWithFilePath:filePath];

        NSString * fileType = response.MIMEType;

        [headSTR appendString:[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n" , fileType]];

        //将请求头信息放入二进制容器中
        [messageData appendData:[headSTR dataUsingEncoding:NSUTF8StringEncoding]];

        //将文件二进制数据放入二进制容器中
        [messageData appendData:[NSData dataWithContentsOfFile:filePath]];

    }];

    //遍历普通参数字典获取字符串的请求体信息

    [paramaterDictionary enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {

        //普通参数字典Key值:表示服务器接受文本的Key值(由后台提供)
        NSString * seversKey = key;

        //普通参数字典Value值:表示上传的文本内容参数(由用户提供)
        NSString * userInput = obj;

//        -----------------------------199683830321344068521409122076 Content-Disposition: form-data; name="username"

        //格式化封装请求头信息
        NSMutableString * headSTRText = [NSMutableString stringWithFormat:@"\r\n--%@\r\n" , kBoundary];

        [headSTRText appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@\r\n\r\n" , seversKey]];

        //追加容器内容
        [messageData appendData:[headSTRText dataUsingEncoding:NSUTF8StringEncoding]];

        [messageData appendData:[userInput dataUsingEncoding:NSUTF8StringEncoding]];

    }];

    //添加下边界,只需添加一次
    NSMutableString *footerStrM = [NSMutableString stringWithFormat:@"\r\n--%@--\r\n",kBoundary];

    [messageData appendData:[footerStrM dataUsingEncoding:NSUTF8StringEncoding]];

    return messageData;

}

/**
 *  获得HTTPBody内容
 *
 *  @param filePath 本地文件的路径,用于获得本地文件的二进制数据
 *  @param fileKey  服务器(后台人员)提供的
 *  @param fileName 上传后的文件存储的名字
 *
 *  @return 返回待上传文件的HTTPBody
 */

-(NSData *)getHTTPBodyWithFilePath:(nonnull NSString *)filePath
                 andServersFileKey:(nonnull NSString *)fileKey
        andFileNameToSaveOnServers:(NSString * _Nullable )fileName{

    //获得动态的文件类型来设置Content-Type
    NSURLResponse * response = [self getFileTypeWithFilePath:filePath];

    NSLog(@"%@ , %lld" , response.MIMEType , response.expectedContentLength);

    NSString * fileType = response.MIMEType;

    if (!fileName) {

        fileName = response.suggestedFilename;

    }

    //定义可变的二进制数据用来存储待上传文件的数据
    NSMutableData * data = [NSMutableData data];

#pragma mark ----拼接请求头字符串

    //请求头标准格式
    NSMutableString * headSTR = [NSMutableString stringWithFormat:@"\r\n--%@\r\n" , kBoundary];

    //请求体中的数据,fileKey由服务器提供,fileName由用户(程序员)[前端]决定 可为空
    [headSTR appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename=%@\r\n" , fileKey , fileName]];

    //根据自定义方法返回的文件信息设置文件格式
    [headSTR appendString:[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n" , fileType]] ;

    NSLog(@"headSTR : %@" , headSTR);

#pragma mark ----拼接二进制数据

    //获得等待上传文件的二进制数据
    [data appendData:[headSTR dataUsingEncoding:NSUTF8StringEncoding]];

    NSData * fileData = [NSData dataWithContentsOfFile:filePath];

    //拼接二进制数据
    [data appendData:fileData];

#pragma mark ----拼接请求尾字符串

    //请求尾标准格式
    NSString * tailSTR = [NSString stringWithFormat:@"\r\n--%@--" , kBoundary];

    NSLog(@"tailSTR : %@" , tailSTR);

    [data appendData:[tailSTR dataUsingEncoding:NSUTF8StringEncoding]];

    return data ;

}

/**
 *  根据[用户或者程序员]传入的文件路径来动态获取文件类型
 *
 *  @param filePath 传入的需要获得类型的文件路径
 *
 *  @return 返回一个NSURLResponse对象,里面包含着系统返回的文件信息
 */
-(NSURLResponse *)getFileTypeWithFilePath:(nonnull NSString *)filePath{

    //定义文件的返回值
    __block NSURLResponse * fileResponse = nil;

    //获取文件字符串--本地
    NSString * fileSTR = [NSString stringWithFormat:@"file://%@" , filePath];

    NSURL * fileURL = [NSURL URLWithString:fileSTR];

    //设置请求--请求本地文件数据
    NSMutableURLRequest * customRequest = [NSMutableURLRequest requestWithURL:fileURL cachePolicy:0 timeoutInterval:15];

    /**
     *   过期的同步方法
     */
    [NSURLConnection sendSynchronousRequest:customRequest returningResponse:&fileResponse error:NULL];

      //设置同步

//    dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
//
//    dispatch_sync(serialQueue, ^{
//
//        customRequest.HTTPMethod = @"POST";
//
//        [[[NSURLSession sharedSession] dataTaskWithRequest:customRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//
//            NSLog(@"%@",[NSThread currentThread]);
//
//            NSLog(@"response %@ " , response.MIMEType);
//
//            fileResponse = response ;
//
//            NSLog(@"file %@" , fileResponse.MIMEType);
//
//        }] resume];
//
//    });

    return fileResponse ;

}

+(instancetype)sharedCSHTTPRequestWork{

    __block id _instance ;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        _instance = [[CSHTTPRequestWork alloc]init];

    });

    return _instance ;

}

@end


text:
import warnings

from django import forms
from django.contrib.admin.sites import site
from django.contrib.admin.widgets import ForeignKeyRawIdWidget
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.core.urlresolvers import reverse
from django.db import models
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe

from filer.models import Folder
from filer.utils.compatibility import truncate_words
from filer.utils.model_label import get_model_label

class AdminFolderWidget(ForeignKeyRawIdWidget):
    choices = None
    input_type = 'hidden'
    is_hidden = False

    def render(self, name, value, attrs=None):
        obj = self.obj_for_value(value)
        css_id = attrs.get('id')
        css_id_folder = "%s_folder" % css_id
        css_id_description_txt = "%s_description_txt" % css_id
        if attrs is None:
            attrs = {}
        related_url = None
        if value:
            try:
                folder = Folder.objects.get(pk=value)
                related_url = folder.get_admin_directory_listing_url_path()
            except Exception:
                pass
        if not related_url:
            related_url = reverse('admin:filer-directory_listing-last')
        params = self.url_parameters()
        params['select_folder'] = 1
        if params:
            url = '?' + '&'.join(['%s=%s' % (k, v) for k, v in list(params.items())])
        else:
            url = ''
        if 'class' not in attrs:
            # The JavaScript looks for this hook.
            attrs['class'] = 'vForeignKeyRawIdAdminField'
        super_attrs = attrs.copy()
        hidden_input = super(ForeignKeyRawIdWidget, self).render(name, value, super_attrs)

        # TODO: "id_" is hard-coded here. This should instead use the correct
        # API to determine the ID dynamically.
        context = {
            'hidden_input': hidden_input,
            'lookup_url': '%s%s' % (related_url, url),
            'lookup_name': name,
            'span_id': css_id_description_txt,
            'object': obj,
            'clear_id': '%s_clear' % css_id,
            'descid': css_id_description_txt,
            'noimg': 'filer/icons/nofile_32x32.png',
            'foldid': css_id_folder,
            'id': css_id,
        }
        html = render_to_string('admin/filer/widgets/admin_folder.html', context)
        return mark_safe(html)

    def label_for_value(self, value):
        obj = self.obj_for_value(value)
        return ' <strong>%s</strong>' % truncate_words(obj, 14)

    def obj_for_value(self, value):
        try:
            key = self.rel.get_related_field().name
            obj = self.rel.to._default_manager.get(**{key: value})
        except:
            obj = None
        return obj

    class Media:
        js = (static('filer/js/popup_handling.js'), )

class AdminFolderFormField(forms.ModelChoiceField):
    widget = AdminFolderWidget

    def __init__(self, rel, queryset, to_field_name, *args, **kwargs):
        self.rel = rel
        self.queryset = queryset
        self.limit_choices_to = kwargs.pop('limit_choices_to', None)
        self.to_field_name = to_field_name
        self.max_value = None
        self.min_value = None
        kwargs.pop('widget', None)
        forms.Field.__init__(self, widget=self.widget(rel, site), *args, **kwargs)

    def widget_attrs(self, widget):
        widget.required = self.required
        return {}

class FilerFolderField(models.ForeignKey):
    default_form_class = AdminFolderFormField
    default_model_class = Folder

    def __init__(self, **kwargs):
        # We hard-code the `to` argument for ForeignKey.__init__
        dfl = get_model_label(self.default_model_class)
        if "to" in kwargs.keys():  # pragma: no cover
            old_to = get_model_label(kwargs.pop("to"))
            if old_to != dfl:
                msg = "%s can only be a ForeignKey to %s; %s passed" % (
                    self.__class__.__name__, dfl, old_to
                )
                warnings.warn(msg, SyntaxWarning)
        kwargs['to'] = dfl
        super(FilerFolderField, self).__init__(**kwargs)

    def formfield(self, **kwargs):
        # This is a fairly standard way to set up some defaults
        # while letting the caller override them.
        defaults = {
            'form_class': self.default_form_class,
            'rel': self.rel,
        }
        defaults.update(kwargs)
        return super(FilerFolderField, self).formfield(**defaults)

    def south_field_triple(self):
        "Returns a suitable description of this field for South."
        # We'll just introspect ourselves, since we inherit.
        from south.modelsinspector import introspector
        field_class = "django.db.models.fields.related.ForeignKey"
        args, kwargs = introspector(self)
        # That's our definition!
        return (field_class, args, kwargs)


text: function error = direct_method_compute_error(z,auxdata)


text:
package com.hazelcast.nio;

import com.hazelcast.config.Config;
import com.hazelcast.config.ConfigXmlGenerator;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.QueueConfig;
import com.hazelcast.nio.PipedZipBufferFactory.DeflatingPipedBuffer;
import com.hazelcast.nio.PipedZipBufferFactory.InflatingPipedBuffer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.Arrays;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

@RunWith(com.hazelcast.util.RandomBlockJUnit4ClassRunner.class)
public class PipedZipBufferTest {

    // config xml data
    private final byte[] data;
    private final int compressedDataLength;

    {
        final Config config = new Config();
        for (int i = 0; i < 1111; i++) {
            config.addMapConfig(new MapConfig("map:" + i));
            config.addQueueConfig(new QueueConfig().setName("queue:" + i));
        }
        data = new ConfigXmlGenerator(true).generate(config).getBytes();
        compressedDataLength = data.length / 9;
    }

    @Test
    public void deflatingBufferTest() throws Exception {
        DeflatingPipedBuffer defBuffer = PipedZipBufferFactory.createDeflatingBuffer(compressedDataLength);
        defBuffer.getOutputStream().write(data);
        int k = defBuffer.deflate();
        Assert.assertTrue("Compressed data should be smaller than actual data!", k < data.length);
        Inflater inf = new Inflater();
        inf.setInput(defBuffer.getOutputBuffer().array(), 0, k);
        byte[] data2 = new byte[data.length];
        int k2 = inf.inflate(data2);
        Assert.assertEquals("Inflated data length should be equal to actual data length!", data.length, k2);
        Assert.assertTrue("Inflated data should be equal to actual data!", Arrays.equals(data, data2));
    }

    @Test
    public void deflatingBufferTest2() throws Exception {
        DeflatingPipedBuffer defBuffer = PipedZipBufferFactory.createDeflatingBuffer(compressedDataLength);
        defBuffer.getInputBuffer().put(data);
        int k = defBuffer.deflate();
        Inflater inf = new Inflater();
        inf.setInput(defBuffer.getOutputBuffer().array(), 0, k);
        byte[] data2 = new byte[data.length];
        inf.inflate(data2);
        Assert.assertTrue(Arrays.equals(data, data2));
    }

    @Test
    public void inflatingBufferTest() throws Exception {
        Deflater def = new Deflater();
        def.setInput(data);
        def.finish();
        InflatingPipedBuffer infBuffer = PipedZipBufferFactory.createInflatingBuffer(compressedDataLength);
        int k = def.deflate(infBuffer.getInputBuffer().array());
        int k2 = infBuffer.inflate(k);
        Assert.assertEquals("Inflated data length should be equal to actual data length!", data.length, k2);
        byte[] data2 = new byte[data.length];
        System.arraycopy(infBuffer.getOutputBuffer().array(), 0, data2, 0, k2);
        Assert.assertTrue("Inflated data should be equal to actual data!", Arrays.equals(data, data2));
    }

    @Test
    public void pipedZipBufferTest() throws Exception {
        DeflatingPipedBuffer defBuffer = PipedZipBufferFactory.createDeflatingBuffer(compressedDataLength);
        defBuffer.getInputBuffer().put(data);
        int k = defBuffer.deflate();
        InflatingPipedBuffer infBuffer = PipedZipBufferFactory.createInflatingBuffer(compressedDataLength);
        infBuffer.getInputBuffer().put(defBuffer.getOutputBuffer());
        int k2 = infBuffer.inflate(k);
        Assert.assertEquals("Inflated data length should be equal to actual data length!", data.length, k2);
        byte[] data2 = new byte[data.length];
        System.arraycopy(infBuffer.getOutputBuffer().array(), 0, data2, 0, k2);
        Assert.assertTrue("Inflated data should be equal to actual data!", Arrays.equals(data, data2));
    }

    @Test
    public void invalidDataTest() throws Exception {
        DeflatingPipedBuffer defBuffer = PipedZipBufferFactory.createDeflatingBuffer(data.length);
        defBuffer.getInputBuffer().put(data);
        final int compressedDataLength = defBuffer.deflate();
        final byte[] compressedData = defBuffer.getOutputBuffer().array();
        InflatingPipedBuffer infBuffer = PipedZipBufferFactory.createInflatingBuffer(data.length);
        for (int i = 0; i < 13; i++) {
            infBuffer.reset();
            if (i % 2 == 0) {
                infBuffer.getInputBuffer().put(compressedData);
            } else {
                infBuffer.getInputBuffer().put(data);
            }
            try {
                int k2 = infBuffer.inflate(compressedDataLength);
                if (i % 2 == 0) {
                    Assert.assertEquals(data.length, k2);
                } else {
                    Assert.fail("Should fail here !!!");
                }
            } catch (Exception e) {
                if (i % 2 == 0) {
                    throw e;
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;

namespace SharpKit.Compiler
{
    class Console
    {
        public bool AutoFlush { get; set; }
        public ConcurrentQueue<string> Items = new ConcurrentQueue<string>();
        public void WriteLine(object p)
        {
            Items.Enqueue(p.ToString());
            DoAutoFlush();
        }

        private void DoAutoFlush()
        {
            if (!AutoFlush)
                return;
            Flush();
        }

        public void Flush()
        {
            while (Items.Count > 0)
            {
                string item;
                if (Items.TryDequeue(out item))
                {
                    System.Console.WriteLine(item);
                }
            }
        }
        public void WriteLine(string msg)
        {
            Items.Enqueue(msg);
            DoAutoFlush();
        }
        public void FormatLine(string msg, params object[] args)
        {
            Items.Enqueue(String.Format(msg, args));
            DoAutoFlush();
        }
    }
}


text:
import gc
from ilastik.gui.ribbons.ilastikTabBase import IlastikTabBase, TabButton
from PyQt4 import QtGui, QtCore
from ilastik.gui.iconMgr import ilastikIcons

import ilastik.gui
from projectDialog import ProjectDlg, ProjectSettingsDlg
from ilastik.core import projectClass
from ilastik.gui.overlayWidget import OverlayWidget
from ilastik.gui import volumeeditor as ve

#*******************************************************************************
# P r o j e c t T a b                                                          *
#*******************************************************************************

class ProjectTab(IlastikTabBase, QtGui.QWidget):
    name = 'Project'
    position = 0
    moduleName = "Project"

    def __init__(self, parent=None):
        IlastikTabBase.__init__(self, parent)
        QtGui.QWidget.__init__(self, parent)
        self._initContent()
        self._initConnects()

    def on_activation(self):
        if self.ilastik.project is None:
            self.ilastik.setTabBusy(True)
            return
        ovs = self.ilastik._activeImage.module[self.__class__.moduleName].getOverlayRefs()
        if len(ovs) == 0:
            raw = self.ilastik._activeImage.overlayMgr["Raw Data"]
            if raw is not None:
                ovs.append(raw.getRef())

        self.ilastik.labelWidget._history.volumeEditor = self.ilastik.labelWidget

        overlayWidget = OverlayWidget(self.ilastik.labelWidget, self.ilastik.project.dataMgr)
        overlayWidget.setVisible(False)

        self.ilastik.labelWidget.setOverlayWidget(overlayWidget)

        self.ilastik.labelWidget.setLabelWidget(ve.DummyLabelWidget())

    def on_deActivation(self):
        pass

    def _initContent(self):
        tl = QtGui.QHBoxLayout()
        tl.setMargin(0)

        self.btnNew     = TabButton('New', ilastikIcons.New, 'Create new project')
        self.btnOpen    = TabButton('Open', ilastikIcons.Open, 'Open existing project')
        self.btnSave    = TabButton('Save', ilastikIcons.Save, 'Save current project to file')
        self.btnEdit    = TabButton('Edit', ilastikIcons.Edit, 'Edit current project')
        self.btnOptions = TabButton('Options', ilastikIcons.Edit, 'Edit ilastik options')

        tl.addWidget(self.btnNew)
        tl.addWidget(self.btnOpen)
        tl.addWidget(self.btnSave)
        tl.addWidget(self.btnEdit)
        tl.addStretch()
        tl.addWidget(self.btnOptions)

        self.btnSave.setEnabled(False)
        self.btnEdit.setEnabled(False)
        self.btnOptions.setEnabled(False)

        self.setLayout(tl)

    def _initConnects(self):
        self.connect(self.btnNew, QtCore.SIGNAL('clicked()'), self.on_btnNew_clicked)
        self.connect(self.btnOpen, QtCore.SIGNAL('clicked()'), self.on_btnOpen_clicked)
        self.connect(self.btnSave, QtCore.SIGNAL('clicked()'), self.on_btnSave_clicked)
        self.connect(self.btnEdit, QtCore.SIGNAL('clicked()'), self.on_btnEdit_clicked)
        self.connect(self.btnOptions, QtCore.SIGNAL('clicked()'), self.on_btnOptions_clicked)

    # Custom Callbacks
    def on_btnNew_clicked(self):
        self.parent.projectDlg = ProjectDlg(self.parent)
        if self.parent.projectDlg.exec_() == QtGui.QDialog.Accepted:
            self.btnSave.setEnabled(True)
            self.btnEdit.setEnabled(True)
            self.btnOptions.setEnabled(True)
            self.parent.updateFileSelector()
            self.parent._activeImageNumber = 0
            self.ilastik.setTabBusy(False)

    def on_btnSave_clicked(self):
        self.parent.saveProject()

    def openProject(self, fileName):
        labelWidget = None
        self.parent.project = projectClass.Project.loadFromDisk(str(fileName), self.parent.featureCache)
        self.btnSave.setEnabled(True)
        self.btnEdit.setEnabled(True)
        self.btnOptions.setEnabled(True)
        self.parent.updateFileSelector()
        self.parent.on_otherProject()
        self.ilastik.setTabBusy(False)
        ilastik.gui.LAST_DIRECTORY = QtCore.QFileInfo(fileName).path()
        gc.collect()
        if labelWidget is not None:
            if labelWidget() is not None:
                refs =  gc.get_referrers(labelWidget())
                for i,r in enumerate(refs):
                    print type(r)
                    print "##################################################################"
                    print r

    def on_btnOpen_clicked(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self, "Open Project", ilastik.gui.LAST_DIRECTORY, "Project Files (*.ilp)")
        if str(fileName) != "":
            self.openProject(fileName)

    def on_btnEdit_clicked(self):
        self.parent.projectDlg = ProjectDlg(self.parent, False)
        self.parent.projectDlg.updateDlg(self.parent.project)
        self.parent.projectModified()

    def on_btnOptions_clicked(self):
        tmp = ProjectSettingsDlg(self.ilastik, self.ilastik.project)
        tmp.exec_()


text:
class ValidationsController < ApplicationController
  load_and_authorize_resource

  def new
  end

  def create
    @validation.scan = params[:validation][:scan]
    respond_to do |format|
      if @validation.save
        format.html { redirect_to projects_path, notice: t('.success') }
      else
        flash[:error] = @validation.errors.full_messages.first
        format.html { render :new }
      end
    end
  end

  private
    def validation_params
      params.require(:validation).permit(:number, :first_name, :last_name, :scan,
                                         :expiration_date, :city, :country, :index,
                                         :scan_cache, :address).merge({
          user_id: current_user.id
        })
    end
end


text:
/**
 * @file accumulateProduct.cpp
 * @brief mex interface for cv::accumulateProduct
 * @ingroup imgproc
 * @author Amro
 * @date 2015
 */
#include "mexopencv.hpp"
using namespace std;
using namespace cv;

/**
 * Main entry called from Matlab
 * @param nlhs number of left-hand-side arguments
 * @param plhs pointers to mxArrays in the left-hand-side
 * @param nrhs number of right-hand-side arguments
 * @param prhs pointers to mxArrays in the right-hand-side
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Check the number of arguments
    nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1);

    // Argument vector
    vector<MxArray> rhs(prhs, prhs+nrhs);

    // Option processing
    Mat mask;
    for (int i=3; i<nrhs; i+=2) {
        string key(rhs[i].toString());
        if (key == "Mask")
            mask = rhs[i+1].toMat(CV_8U);
        else
            mexErrMsgIdAndTxt("mexopencv:error",
                "Unrecognized option %s", key.c_str());
    }

    // Process
    Mat src1(rhs[0].toMat(rhs[0].isUint8() ? CV_8U : CV_32F)),
        src2(rhs[1].toMat(rhs[1].isUint8() ? CV_8U : CV_32F)),
        dst(rhs[2].toMat(rhs[2].isSingle() ? CV_32F : CV_64F));
    accumulateProduct(src1, src2, dst, mask);
    plhs[0] = MxArray(dst);
}


text:
local CSubTable, parent = torch.class('nn.CSubTable', 'nn.Module')

function CSubTable:__init()
   parent.__init(self)
   self.gradInput = {}
end

function CSubTable:updateOutput(input)
   self.output:resizeAs(input[1]):copy(input[1])
   self.output:add(-1,input[2])
   return self.output
end

function CSubTable:updateGradInput(input, gradOutput)
   self.gradInput[1] = self.gradInput[1] or input[1].new()
   self.gradInput[2] = self.gradInput[2] or input[1].new()
   self.gradInput[1]:resizeAs(input[1]):copy(gradOutput)
   self.gradInput[2]:resizeAs(input[2]):copy(gradOutput):mul(-1)
   return self.gradInput
end


text:
import chai, { expect } from 'chai'
import chaiChange from 'chai-change'
import Queue from '../src/queue'

chai.use(chaiChange)

describe('Queue', () => {
  'use strict'

  it('is a function', () => {
    expect(Queue).to.be.a('function')
  })

  context('enqueue()', () => {
    it('adds an element to the back of the stack.', () => {
      const myQueue = new Queue()
      myQueue.enqueue('first')
      myQueue.enqueue('second')

      expect(() => myQueue.enqueue('foo')).to.alter(() => myQueue.length(), { from: 2, to: 3 })
    })
  })

  context('dequeue()', () => {
    it('removes and returns the front element in the queue', () => {
      const myQueue = new Queue()

      myQueue.enqueue('first')
      myQueue.enqueue('second')
      myQueue.enqueue('third')

      expect(() => myQueue.dequeue()).to.alter(() => myQueue.length(), { from: 3, to: 2 })
      // expect()
    })

    it('reassigns front node', () => {
      const myQueue = new Queue()

      myQueue.enqueue('first')
      myQueue.enqueue('second')
      myQueue.enqueue('third')
      myQueue.dequeue()

      expect(myQueue.frontNode.data).to.equal('second')
    })

    it('returns null if the stack is empty', () => {
      const myQueue = new Queue()

      expect(myQueue.dequeue()).to.be.null
    })
  })

  context('isEmpty()', () => {
    it('returns true when stack is empty.', () => {
      const myQueue = new Queue()

      expect(myQueue.isEmpty()).to.true
    })

    it('returns false when stack is loaded.', () => {
      const myQueue = new Queue()

      myQueue.enqueue('Car')

      expect(myQueue.isEmpty()).to.false
    })
  })

  context('length()', () => {
    it('returns the number of elements in the stack.', () => {
      const myQueue = new Queue()

      myQueue.enqueue('Car')
      myQueue.enqueue('MacBook')

      expect(myQueue.length()).to.equal(2)
    })
  })

  context('front()', () => {
    it('returns the front element of the queue or null if empty', () => {
      const myQueue = new Queue()

      myQueue.enqueue('front')
      myQueue.enqueue('back')

      expect(myQueue.front()).to.equal('front')
    })

    it('returns null if the stack is empty', () => {
      const myQueue = new Queue()

      expect(myQueue.front()).to.be.null
    })
  })

  context('back()', () => {
    it('returns the back element of the queue or null if empty', () => {
      const myQueue = new Queue()

      myQueue.enqueue('front')
      myQueue.enqueue('back')

      expect(myQueue.back()).to.equal('back')
    })

    it('returns null if the stack is empty', () => {
      const myQueue = new Queue()

      expect(myQueue.back()).to.be.null
    })
  })

})


text:
package org.spongepowered.common.text.action;

import net.minecraft.util.text.event.ClickEvent;

import org.spongepowered.api.text.action.ClickAction;
import org.spongepowered.common.bridge.util.text.event.ClickEventBridge;

import java.util.UUID;

public final class SpongeClickAction {

    private SpongeClickAction() {}

    private static ClickEvent.Action getType(ClickAction<?> action) {
        if (action instanceof ClickAction.OpenUrl) {
            return ClickEvent.Action.OPEN_URL;
        } else if (action instanceof ClickAction.RunCommand || action instanceof ClickAction.ExecuteCallback) {
            return ClickEvent.Action.RUN_COMMAND;
        } else if (action instanceof ClickAction.SuggestCommand) {
            return ClickEvent.Action.SUGGEST_COMMAND;
        } else if (action instanceof ClickAction.ChangePage) {
            return ClickEvent.Action.CHANGE_PAGE;
        }

        throw new UnsupportedOperationException(action.getClass().toString());
    }

    public static ClickEvent getHandle(ClickAction<?> action) {
        final String text;
        if (action instanceof ClickAction.ExecuteCallback) {
            UUID callbackId = SpongeCallbackHolder.getInstance().getOrCreateIdForCallback(((ClickAction.ExecuteCallback) action).getResult());
            text = SpongeCallbackHolder.CALLBACK_COMMAND_QUALIFIED + " " + callbackId;
        } else {
            text = action.getResult().toString();
        }

        ClickEvent event = new ClickEvent(getType(action), text);
        ((ClickEventBridge) event).bridge$setHandle(action);
        return event;
    }

}


text:
using UnityEngine;
using System.Collections;
using System;

namespace GDGeek{

	[Serializable]
	public abstract class DataInfo{

		[SerializeField]
		public bool succeed = false;
		[SerializeField]
		public string message = "";
		[SerializeField]
		public double epoch = 0;

	}

/*public interface DataInfoLoader<T>{
		T load (string json);
	}
*/
	public class WebLoaderTask<T> : Task where T:DataInfo {
		public delegate void Succeed (T info);
		public delegate void Error (string msg);
		public event Succeed onSucceed;
		public event Error onError;
		private WebPack pack_ = null;
		public WebPack pack{
			get{
				return pack_;
			}
		}

		private void succeed(string json){
			Debug.Log(json);
			T t = JsonUtility.FromJson<T> (json);
			if (t.succeed) {
				WebTimestamp.GetInstance().synchro(t.epoch);
				if (onSucceed != null) {
					onSucceed (t);
				}
			} else {
				error (t.message);
			}

		}
		private void error(string msg){
			if (onError != null)
				onError (msg);
		}
		public WebLoaderTask(string url){
			pack_ = new WebPack (url);
			pack_.addField("a", "b");
			bool isOver = false;

			this.init = delegate {

				Task web = WebTaskFactory.Instance.create(pack,succeed,error);
				TaskManager.PushFront(web, delegate{
					isOver = false;
				});
				TaskManager.PushBack (web, delegate{
					isOver = true;
				});
				this.isOver = delegate {
					return isOver;
				};

				TaskManager.Run (web);
			};

		}

	}
}


text:
using System;

namespace Umbraco.Cms.Core.Models.Membership
{
    public class UserProfile : IProfile, IEquatable<UserProfile>
    {
        public UserProfile(int id, string name)
        {
            Id = id;
            Name = name;
        }

        public int Id { get; private set; }
        public string Name { get; private set; }

        public bool Equals(UserProfile other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Id == other.Id;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((UserProfile) obj);
        }

        public override int GetHashCode()
        {
            return Id;
        }

        public static bool operator ==(UserProfile left, UserProfile right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(UserProfile left, UserProfile right)
        {
            return Equals(left, right) == false;
        }
    }
}


text:
#include <QString>
#include <QStringList>
#include <QByteArray>
#include <QVariant>
#include <QtDebug>

#include "gconfitem.h"

#include <glib.h>
#include <gconf/gconf-value.h>
#include <gconf/gconf-client.h>

struct GConfItemPrivate {
    QString key;
    QVariant value;
    guint notify_id;

    static void notify_trampoline(GConfClient*, guint, GConfEntry *, gpointer);
};

/* We get the default client and never release it, on purpose, to
   avoid disconnecting from the GConf daemon when a program happens to
   not have any GConfItems for short periods of time.
 */
static GConfClient *
get_gconf_client ()
{
  static bool initialized = false;
  static GConfClient *client;

  if (initialized)
    return client;

  g_type_init ();
  client = gconf_client_get_default();
  initialized = true;

  return client;
}

/* Sometimes I like being too clever...
 */
#define withClient(c) for (GConfClient *c = get_gconf_client (); c; c = NULL)

static QByteArray convertKey (QString key)
{
    if (key.startsWith('/'))
        return key.toUtf8();
    else
    {
        qWarning() << "Using dot-separated key names with GConfItem is deprecated.";
        qWarning() << "Please use" << '/' + key.replace('.', '/') << "instead of" << key;
        return '/' + key.replace('.', '/').toUtf8();
    }
}

static QString convertKey(const char *key)
{
    return QString::fromUtf8(key);
}

static QVariant convertValue(GConfValue *src)
{
    if (!src) {
        return QVariant();
    } else {
        switch (src->type) {
        case GCONF_VALUE_INVALID:
            return QVariant(QVariant::Invalid);
        case GCONF_VALUE_BOOL:
            return QVariant((bool)gconf_value_get_bool(src));
        case GCONF_VALUE_INT:
            return QVariant(gconf_value_get_int(src));
        case GCONF_VALUE_FLOAT:
            return QVariant(gconf_value_get_float(src));
        case GCONF_VALUE_STRING:
            return QVariant(QString::fromUtf8(gconf_value_get_string(src)));
        case GCONF_VALUE_LIST:
            switch (gconf_value_get_list_type(src)) {
            case GCONF_VALUE_STRING:
                {
                    QStringList result;
                    for (GSList *elts = gconf_value_get_list(src); elts; elts = elts->next)
                        result.append(QString::fromUtf8(gconf_value_get_string((GConfValue *)elts->data)));
                    return QVariant(result);
                }
            default:
                {
                    QList<QVariant> result;
                    for (GSList *elts = gconf_value_get_list(src); elts; elts = elts->next)
                        result.append(convertValue((GConfValue *)elts->data));
                    return QVariant(result);
                }
            }
        case GCONF_VALUE_SCHEMA:
        default:
            return QVariant();
        }
    }
}

static GConfValue *convertString(const QString &str)
{
    GConfValue *v = gconf_value_new (GCONF_VALUE_STRING);
    gconf_value_set_string (v, str.toUtf8().data());
    return v;
}

static GConfValueType primitiveType (const QVariant &elt)
{
    switch(elt.type()) {
    case QVariant::String:
        return GCONF_VALUE_STRING;
    case QVariant::Int:
        return GCONF_VALUE_INT;
    case QVariant::Double:
        return GCONF_VALUE_FLOAT;
    case QVariant::Bool:
        return GCONF_VALUE_BOOL;
    default:
        return GCONF_VALUE_INVALID;
    }
}

static GConfValueType uniformType(const QList<QVariant> &list)
{
    GConfValueType result = GCONF_VALUE_INVALID;

    foreach (const QVariant &elt, list) {
        GConfValueType elt_type = primitiveType (elt);

        if (elt_type == GCONF_VALUE_INVALID)
            return GCONF_VALUE_INVALID;

        if (result == GCONF_VALUE_INVALID)
            result = elt_type;
        else if (result != elt_type)
            return GCONF_VALUE_INVALID;
    }

    if (result == GCONF_VALUE_INVALID)
        return GCONF_VALUE_STRING;  // empty list.
    else
        return result;
}

static int convertValue(const QVariant &src, GConfValue **valp)
{
    GConfValue *v;

    switch(src.type()) {
    case QVariant::Invalid:
        v = NULL;
        break;
    case QVariant::Bool:
        v = gconf_value_new (GCONF_VALUE_BOOL);
        gconf_value_set_bool (v, src.toBool());
        break;
    case QVariant::Int:
        v = gconf_value_new (GCONF_VALUE_INT);
        gconf_value_set_int (v, src.toInt());
        break;
    case QVariant::Double:
        v = gconf_value_new (GCONF_VALUE_FLOAT);
        gconf_value_set_float (v, src.toDouble());
        break;
    case QVariant::String:
        v = convertString(src.toString());
        break;
    case QVariant::StringList:
        {
            GSList *elts = NULL;
            v = gconf_value_new(GCONF_VALUE_LIST);
            gconf_value_set_list_type(v, GCONF_VALUE_STRING);
            foreach (const QString &str, src.toStringList())
                elts = g_slist_prepend(elts, convertString(str));
            gconf_value_set_list_nocopy(v, g_slist_reverse(elts));
            break;
        }
    case QVariant::List:
        {
            GConfValueType elt_type = uniformType(src.toList());
            if (elt_type == GCONF_VALUE_INVALID)
                v = NULL;
            else
            {
                GSList *elts = NULL;
                v = gconf_value_new(GCONF_VALUE_LIST);
                gconf_value_set_list_type(v, elt_type);
                foreach (const QVariant &elt, src.toList())
                {
                    GConfValue *val = NULL;
                    convertValue(elt, &val);  // guaranteed to succeed.
                    elts = g_slist_prepend(elts, val);
                }
                gconf_value_set_list_nocopy(v, g_slist_reverse(elts));
            }
            break;
        }
    default:
        return 0;
    }

    *valp = v;
    return 1;
}

void GConfItemPrivate::notify_trampoline (GConfClient*,
                                             guint,
                                             GConfEntry *,
                                             gpointer data)
{
    GConfItem *item = (GConfItem *)data;
    item->update_value (true);
}

void GConfItem::update_value (bool emit_signal)
{
    QVariant new_value;

    withClient(client) {
        GError *error = NULL;
        QByteArray k = convertKey(priv->key);
        GConfValue *v = gconf_client_get(client, k.data(), &error);

        if (error) {
            qWarning() << error->message;
            g_error_free (error);
            new_value = priv->value;
        } else {
            new_value = convertValue(v);
            if (v)
                gconf_value_free(v);
        }
    }

    if (new_value != priv->value) {
        priv->value = new_value;
        if (emit_signal)
            emit valueChanged();
    }
}

QString GConfItem::key() const
{
    return priv->key;
}

QVariant GConfItem::value() const
{
    return priv->value;
}

QVariant GConfItem::value(const QVariant &def) const
{
    if (priv->value.isNull())
        return def;
    else
        return priv->value;
}

void GConfItem::set(const QVariant &val)
{
    withClient(client) {
        QByteArray k = convertKey(priv->key);
        GConfValue *v;
        if (convertValue(val, &v)) {
            GError *error = NULL;

            if (v) {
                gconf_client_set(client, k.data(), v, &error);
                gconf_value_free(v);
            } else {
                gconf_client_unset(client, k.data(), &error);
            }

            if (error) {
                qWarning() << error->message;
                g_error_free(error);
            } else if (priv->value != val) {
                priv->value = val;
                emit valueChanged();
            }

        } else
            qWarning() << "Can't store a" << val.typeName();
    }
}

void GConfItem::unset() {
    set(QVariant());
}

QList<QString> GConfItem::listDirs() const
{
    QList<QString> children;

    withClient(client) {
        QByteArray k = convertKey(priv->key);
        GSList *dirs = gconf_client_all_dirs(client, k.data(), NULL);
        for (GSList *d = dirs; d; d = d->next) {
            children.append(convertKey((char *)d->data));
            g_free (d->data);
        }
        g_slist_free (dirs);
    }

    return children;
}

QList<QString> GConfItem::listEntries() const
{
    QList<QString> children;

    withClient(client) {
        QByteArray k = convertKey(priv->key);
        GSList *entries = gconf_client_all_entries(client, k.data(), NULL);
        for (GSList *e = entries; e; e = e->next) {
            children.append(convertKey(((GConfEntry *)e->data)->key));
            gconf_entry_free ((GConfEntry *)e->data);
        }
        g_slist_free (entries);
    }

    return children;
}

GConfItem::GConfItem(const QString &key, QObject *parent)
    : QObject (parent)
{
    priv = new GConfItemPrivate;
    priv->key = key;
    priv->notify_id = 0;
    withClient(client) {
        update_value (false);
        QByteArray k = convertKey(priv->key);
        gconf_client_add_dir (client, k.data(), GCONF_CLIENT_PRELOAD_ONELEVEL, NULL);
        priv->notify_id = gconf_client_notify_add (client, k.data(),
                                                   GConfItemPrivate::notify_trampoline, this,
                                                   NULL, NULL);
    }
}

GConfItem::~GConfItem()
{
    withClient(client) {
        QByteArray k = convertKey(priv->key);
        if (priv->notify_id)
          gconf_client_notify_remove (client, priv->notify_id);
        gconf_client_remove_dir (client, k.data(), NULL);
    }
    delete priv;
}


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

namespace _06_minNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int numbers = int.Parse(Console.ReadLine());

            int result = int.MaxValue;

            for (int i = 0; i < numbers; i++)
            {
                int num = int.Parse(Console.ReadLine());

                if (num<result)
                {
                    result = num;
                }
            }

            Console.WriteLine(result);

        }
    }
}


text:
[![Build Status](https://travis-ci.org/mapstream/mapstream.svg?branch=master)](https://travis-ci.org/mapstream/mapstream) [![Coverage Status](https://coveralls.io/repos/github/mapstream/mapstream/badge.svg?branch=master)](https://coveralls.io/github/mapstream/mapstream?branch=master) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.github.mapstream/mapstream/badge.svg)](https://maven-badges.herokuapp.com/maven-central/io.github.mapstream/mapstream) [![Gitter](https://img.shields.io/gitter/room/mapstream/mapstream.svg?maxAge=2592000)](https://gitter.im/mapstream/mapstream)

# mapstream :ocean:

Better stream api for `Map` (Java 8).

### Examples

With mapstream you can do:
```java
Map<String, Integer> map; // = ["five" -> 5, "one" -> 1, "ten" -> 10, "ignore" -> -10]
Map<String, Integer> dividedByTwo =
    MapStream.from(map)
        .filterKeys(name -> !name.equals("ignore"))
        .filterValues(number -> number % 2 == 0)
        .mapValues(number -> number / 2)
        .toMap(); // = ["ten" -> 5]
```

instead of

```java
Map<String, Integer> map; // = ["five" -> 5, "one" -> 1, "ten" -> 10, "ignore" -> -10]
Map<String, Integer> dividedByTwo =
    map.stream()
        .filter(entry -> !entry.getKey().equals("ignore") && entry.getValue() % 2 == 0)
        .collect(Collectors.toMap(
                entry -> entry.getKey(),
                entry -> entry.getValue() / 2
        )); // = ["ten" -> 5]
```

### Download

```xml
<dependency>
  <groupId>io.github.mapstream</groupId>
  <artifactId>mapstream</artifactId>
  <version>0.0.1</version>
</dependency>
```

### Implementation

Under the hood it uses `Stream<PairEntry<K, V>>` as a delegate, so you can for example use `MapStream.parallel()` and it will reuse well-tested jvm implementation of parallel stream (`Stream.parallel()`).

---------

#### Similar projects

- com.github.pyknic/map-stream (I found out about this just after deploying `0.0.1` version to Maven Central)


text:
layout: page
title: Haney - Mcpherson Wedding
date: 2016-05-24
author: Laura Evans
tags: weekly links, java
status: published
summary: Duis dignissim turpis nulla, ultrices fermentum eros porttitor pretium. Nunc.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 09/13/2016
  endDate: 09/16/2016
  ctyhocn: OKCNMHX
  groupCode: HMW
published: true
---
Praesent imperdiet urna at velit maximus varius. Praesent quis fermentum dolor. Mauris in iaculis libero, sit amet sagittis sem. Quisque sit amet orci venenatis, feugiat mauris ut, luctus risus. Quisque molestie volutpat sodales. Duis eget sagittis tortor. Pellentesque sed nibh ante. Donec ullamcorper condimentum pretium.
Vestibulum consequat fringilla lectus, ac maximus felis varius ut. Etiam accumsan non magna a pellentesque. Duis consequat elementum quam et iaculis. Duis sed velit porttitor, interdum nisl sit amet, faucibus dolor. Quisque et felis lorem. Duis enim sapien, pellentesque vel varius eu, feugiat at neque. Suspendisse porttitor odio ut interdum cursus. Donec sit amet dui id mi tincidunt accumsan id et sem. Suspendisse pulvinar ornare mi eu iaculis. Mauris aliquet ipsum nunc, sed consequat ipsum tincidunt pulvinar. Nullam et mi non ligula fringilla finibus. In non pharetra erat, et faucibus magna.

1 Nunc condimentum nibh et mi mattis venenatis
1 Curabitur pretium odio accumsan neque laoreet eleifend
1 Nullam volutpat orci ac arcu efficitur consequat
1 Curabitur quis libero congue, tincidunt massa vitae, convallis enim.

Sed sed arcu nec est ultrices pretium molestie non elit. Quisque pharetra ullamcorper libero a efficitur. Donec accumsan odio quis dolor volutpat, et lobortis libero vulputate. Aliquam ut tortor quam. Donec vitae consectetur mauris. Cras at elit sit amet elit volutpat tincidunt at eget massa. Praesent sed blandit sem. Nam lacinia sed arcu a lobortis. Pellentesque ultrices sagittis fringilla.