text:
/*global xit,it,describe,before,after,beforeEach,afterEach,require*/
"use strict";
require("requirish")._(module);
var assert = require("better-assert");
var should = require("should");
var async = require("async");

var opcua = require("index.js");

var OPCUAClient = opcua.OPCUAClient;
var ClientSession = opcua.ClientSession;
var ClientSubscription = opcua.ClientSubscription;
var AttributeIds = opcua.AttributeIds;
var resolveNodeId = opcua.resolveNodeId;
var Variant = opcua.Variant;
var DataType =opcua.DataType;

var build_server_with_temperature_device = require("test/helpers/build_server_with_temperature_device").build_server_with_temperature_device;
var perform_operation_on_client_session = require("test/helpers/perform_operation_on_client_session").perform_operation_on_client_session;
var address_space_for_conformance_testing = require("lib/simulation/address_space_for_conformance_testing");
var build_address_space_for_conformance_testing = address_space_for_conformance_testing.build_address_space_for_conformance_testing;

var _port = 2000;

var resourceLeakDetector = require("test/helpers/resource_leak_detector").resourceLeakDetector;

// bug : server reported to many datavalue changed when client monitored a UAVariable consructed with variation 1");

describe("Testing bug #119 - Verify that monitored item only reports expected value change notifications :", function () {

    this.timeout(50000);

    var server, client, temperatureVariableId, endpointUrl;

    before(function (done) {
        resourceLeakDetector.start();
        // we use a different port for each tests to make sure that there is
        // no left over in the tcp pipe that could generate an error
        server = build_server_with_temperature_device({port: _port}, function (err) {

            build_address_space_for_conformance_testing(server.engine, {mass_variables: false});

            endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;
            temperatureVariableId = server.temperatureVariableId;
            done(err);
        });
    });

    beforeEach(function (done) {
        client = new OPCUAClient();
        done();
    });

    afterEach(function (done) {
        client.disconnect(done);
        client = null;
    });

    after(function (done) {
        server.shutdown(function (err) {
            resourceLeakDetector.stop();
            done(err);
        });
        server = null;
    });

    it("monitoring variables shall only reports real value changes : fixing bug #1xx", function (done) {

        perform_operation_on_client_session(client, endpointUrl, function (session, inner_done) {

            assert(session instanceof ClientSession);

            var subscription = new ClientSubscription(session, {
                requestedPublishingInterval: 150,
                requestedLifetimeCount: 10 * 60 * 10,
                requestedMaxKeepAliveCount: 10,
                maxNotificationsPerPublish: 2,
                publishingEnabled: true,
                priority: 6
            });

            subscription.once("terminated", function () {
                inner_done();
            });

            var nodeId = "ns=0;i=2257"; // Server.StartTime
            var monitoredItem = subscription.monitor(
                {nodeId: resolveNodeId(nodeId), attributeId: AttributeIds.Value},
                {samplingInterval: 10, discardOldest: true, queueSize: 1});

            var change_count = 0;
            monitoredItem.on("changed", function (dataValue) {
                change_count += 1;
            });

            subscription.once("started", function (subscriptionId) {

                async.series([

                    function(callback) {
                        // first "changed" must happen almost immediately
                        setTimeout(function () {
                            change_count.should.eql(1);
                            callback();
                        } , 200);
                    },
                    function(callback) {
                        setTimeout(function () {
                            change_count.should.eql(1);
                            callback();
                        } , 500);
                    },
                    function(callback) {

                        //  change server startTime ( from the server side)
                        server.engine.startTime = new Date();

                        setTimeout(function () {
                            // check that the change has been identified
                            change_count.should.eql(2);
                            callback();
                        } , 200);
                    },

                    function(callback) {
                        setTimeout(function () {
                            change_count.should.eql(2);
                            subscription.terminate();
                            callback();
                        }, 500);
                    }

                ]);
            });
        }, done);

    });

    it("a server that have a fast sampling rate shall not report value changed faster on monitored " +
        "item faster than the sampling rate imposed by the client",function(done){

        perform_operation_on_client_session(client, endpointUrl, function (session, inner_done) {

            assert(session instanceof ClientSession);

            var subscription = new ClientSubscription(session, {
                requestedPublishingInterval: 250,
                requestedLifetimeCount: 10 * 60 * 10,
                requestedMaxKeepAliveCount: 10,
                maxNotificationsPerPublish: 2,
                publishingEnabled: true,
                priority: 6
            });

            subscription.once("terminated", function () {
                inner_done();
            });

            var nodeId = "ns=411;s=Scalar_Static_Double";

            var count = 1;
            var v = server.engine.findObject(nodeId);
            v.setValueFromSource( new Variant({dataType: DataType.Double, value:count}));

            var timerId = setInterval(function() {
                count +=1;
                v.setValueFromSource( new Variant({dataType: DataType.Double, value:count}));
            },20); // high rate !!!

            var monitoredItem = subscription.monitor(
                {nodeId: resolveNodeId(nodeId), attributeId: AttributeIds.Value},
                {
                    samplingInterval: 500, // slow rate  (slower than publishing rate)
                    discardOldest: true,
                    queueSize: 10
                },opcua.read_service.TimestampsToReturn.Both);

            var change_count = 0;
            monitoredItem.on("changed", function (dataValue) {
                //xx console.log(" data Value = ",dataValue.value.toString());
                change_count += 1;
            });

            subscription.once("started", function (subscriptionId) {

                //xx console.log(" monitoredItem = ",monitoredItem);

                async.series([

                    function(callback) {
                        setTimeout(function () {
                            //xx console.log(change_count);
                            change_count.should.be.within(1,2);
                            callback();
                        },500);
                    },
                    function(callback) {
                        setTimeout(function () {
                            //xx console.log(change_count);
                            change_count.should.be.within(2,4);
                            callback();
                        } , 500);
                    },

                    function(callback) {
                        setTimeout(function () {
                            change_count.should.be.within(4,6);

                            count.should.be.greaterThan(50);

                            clearInterval(timerId);
                            subscription.terminate();
                            callback();
                        }, 1000 );
                    }

                ]);
            });
        }, done);

    });

});


text:
"""Adds an ad customizer feed.

Associates the feed with customer and adds an ad that uses the feed to populate
dynamic data.

"""

from datetime import datetime
from uuid import uuid4

# Import appropriate classes from the client library.
from googleads import adwords
from googleads import errors

FEED_NAME = 'Interplanetary Feed Name %s' % uuid4()
ADGROUPS = [
    'INSERT_ADGROUP_ID_1_HERE',
    'INSERT_ADGROUP_ID_2_HERE'
]

def CreateAdsWithCustomizations(client, adgroup_ids, feed_name):
  """Creates ExpandedTextAds that use ad customizations for specified AdGroups.

  Args:
    client: an AdWordsClient instance.
    adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to.
    feed_name: the name of the feed used to apply customizations.

  Raises:
    GoogleAdsError: if no ExpandedTextAds were added.
  """
  # Get the AdGroupAdService
  adgroup_ad_service = client.GetService('AdGroupAdService', 'v201802')

  expanded_text_ad = {
      'xsi_type': 'ExpandedTextAd',
      'headlinePart1': 'Luxury Cruise to {=%s.Name}' % feed_name,
      'headlinePart2': 'Only {=%s.Price}' % feed_name,
      'description': 'Offer ends in {=countdown(%s.Date)}!' % feed_name,
      'finalUrls': ['http://www.example.com'],
  }

  # We add the same ad to both ad groups. When they serve, they will show
  # different values, since they match different feed items.
  operations = [{
      'operator': 'ADD',
      'operand': {
          'adGroupId': adgroup,
          'ad': expanded_text_ad
      }
  } for adgroup in adgroup_ids]

  response = adgroup_ad_service.mutate(operations)

  if response and 'value' in response:
    for ad in response['value']:
      print ('Created an ad with ID "%s", type "%s", and status "%s".'
             % (ad['ad']['id'], ad['ad']['Ad.Type'], ad['status']))
  else:
    raise errors.GoogleAdsError('No ads were added.')

def CreateCustomizerFeed(client, feed_name):
  """Creates a new AdCustomizerFeed.

  Args:
    client: an AdWordsClient instance.
    feed_name: the name for the new AdCustomizerFeed.

  Returns:
    The new AdCustomizerFeed.
  """
  # Get the AdCustomizerFeedService
  ad_customizer_feed_service = client.GetService('AdCustomizerFeedService',
                                                 'v201802')
  customizer_feed = {
      'feedName': feed_name,
      'feedAttributes': [
          {'type': 'STRING', 'name': 'Name'},
          {'type': 'STRING', 'name': 'Price'},
          {'type': 'DATE_TIME', 'name': 'Date'}
      ]
  }

  feed_service_operation = {
      'operator': 'ADD',
      'operand': customizer_feed
  }

  response = ad_customizer_feed_service.mutate([feed_service_operation])

  if response and 'value' in response:
    feed = response['value'][0]
    feed_data = {
        'feedId': feed['feedId'],
        'nameId': feed['feedAttributes'][0]['id'],
        'priceId': feed['feedAttributes'][1]['id'],
        'dateId': feed['feedAttributes'][2]['id']
    }
    print ('Feed with name "%s" and ID %s was added with:\n'
           '\tName attribute ID %s and price attribute ID %s and date attribute'
           'ID %s') % (feed['feedName'], feed['feedId'], feed_data['nameId'],
                       feed_data['priceId'], feed_data['dateId'])
    return feed
  else:
    raise errors.GoogleAdsError('No feeds were added')

def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed):
  """Creates FeedItems for the specified AdGroups.

  These FeedItems contain values to use in ad customizations for the AdGroups.

  Args:
    client: an AdWordsClient instance.
    adgroup_ids: a list containing two AdGroup Ids.
    ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems
        with.

  Raises:
    GoogleAdsError: if no FeedItems were added.
  """
  # Get the FeedItemService
  feed_item_service = client.GetService('FeedItemService', 'v201802')
  now = datetime.now()
  mars_date = datetime(now.year, now.month, 1, 0, 0)
  venus_date = datetime(now.year, now.month, 15, 0, 0)
  time_format = '%Y%m%d %H%M%S'

  feed_item_operations = [
      CreateFeedItemAddOperation(
          'Mars', '$1234.56', mars_date.strftime(time_format), adgroup_ids[0],
          ad_customizer_feed),
      CreateFeedItemAddOperation(
          'Venus', '$1450.00', venus_date.strftime(time_format),
          adgroup_ids[1], ad_customizer_feed)
  ]

  response = feed_item_service.mutate(feed_item_operations)

  if 'value' in response:
    for feed_item in response['value']:
      print 'Added FeedItem with ID %d.' % feed_item['feedItemId']
  else:
    raise errors.GoogleAdsError('No FeedItems were added.')

def CreateFeedItemAddOperation(name, price, date, adgroup_id,
                               ad_customizer_feed):
  """Creates a FeedItemOperation.

  The generated FeedItemOperation will create a FeedItem with the specified
  values and AdGroupTargeting when sent to FeedItemService.mutate.

  Args:
    name: the value for the name attribute of the FeedItem.
    price: the value for the price attribute of the FeedItem.
    date: the value for the date attribute of the FeedItem.
    adgroup_id: the ID of the ad_group to target with the FeedItem.
    ad_customizer_feed: the AdCustomizerFeed we're associating the FeedItems
        with.

  Returns:
    A new FeedItemOperation for adding a FeedItem.
  """
  feed_item = {
      'feedId': ad_customizer_feed['feedId'],
      'adGroupTargeting': {
          'TargetingAdGroupId': adgroup_id
      },
      'attributeValues': [
          {
              'feedAttributeId': ad_customizer_feed['feedAttributes'][0]['id'],
              'stringValue': name
          },
          {
              'feedAttributeId': ad_customizer_feed['feedAttributes'][1]['id'],
              'stringValue': price
          },
          {
              'feedAttributeId': ad_customizer_feed['feedAttributes'][2]['id'],
              'stringValue': date
          }
      ]
  }

  operation = {
      'operator': 'ADD',
      'operand': feed_item
  }

  return operation

def main(client, adgroup_ids, feed_name=FEED_NAME):
  # Create a customizer feed. One feed per account can be used for all ads.
  ad_customizer_feed = CreateCustomizerFeed(client, feed_name)
  # Add feed items containing the values we'd like to place in ads.
  CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed)
  # All set! We can now create ads with customizations.
  CreateAdsWithCustomizations(client, adgroup_ids, feed_name)

if __name__ == '__main__':
  # Initialize client object.
  adwords_client = adwords.AdWordsClient.LoadFromStorage()
  main(adwords_client, ADGROUPS)

redpajama_set_name: RedPajamaGithub


text:
#include <TrueTypeText.h>
#include <GL/glew.h>
#include <ft2build.h>
#include <freetype.h>
#include <ftglyph.h>
#include <ftoutln.h>
#include <fttrigon.h>
#include <vector>
#include <string>

using std::vector;
using std::string;

int TrueTypeText::next_p2(int a) {
		int rval=1;
		while(rval<a) rval<<=1;
		return rval;
}

TrueTypeText::TrueTypeText() {};

void TrueTypeText::make_dlist(FT_Face face, char ch, GLuint list_base, GLuint *tex_base) {
		if (FT_Load_Glyph(face,FT_Get_Char_Index(face,ch),FT_LOAD_DEFAULT)) printf("FT_Load_Glyph failed!\n");
		FT_Glyph glyph;
		if (FT_Get_Glyph(face->glyph,&glyph)) printf("FT_GET_Glyph failed");
		FT_Glyph_To_Bitmap(&glyph,ft_render_mode_normal,0,1);
		FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph;
		FT_Bitmap &bitmap = bitmap_glyph->bitmap;
		int width = next_p2(bitmap.width);
		int height = next_p2(bitmap.rows);
        GLubyte *expanded_data = new GLubyte[2*width*height];
        glLoadIdentity();
        for (int j=0; j < height; j++) {
            for (int i = 0; i < width; i++) {
                expanded_data[2*(i+j*width)] = expanded_data[2*(i+j*width)+1] = (i>=int(bitmap.width) || j>= int(bitmap.rows)) ? 0 : bitmap.buffer[i+bitmap.width*j];
            }
        }
        glBindTexture(GL_TEXTURE_2D, tex_base[ch]);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width,height,0,GL_LUMINANCE_ALPHA,GL_UNSIGNED_BYTE,expanded_data);
        delete[] expanded_data;

        glLoadIdentity();
        glNewList(list_base+ch,GL_COMPILE);
        glBindTexture(GL_TEXTURE_2D,tex_base[ch]);
        glPushMatrix();
        glTranslated(bitmap_glyph->left,0,0);
        glTranslated(0,int(bitmap_glyph->top)-int(bitmap.rows),0);

        float x = (float)bitmap.width/(float)width;
        float y = (float)bitmap.rows/(float)height;
        glBegin(GL_QUADS);
        glTexCoord2d(0,0); glVertex2f(0,float(bitmap.rows));
        glTexCoord2d(0,y); glVertex2f(0,0);
        glTexCoord2d(x,y); glVertex2f((float)bitmap.width,0);
        glTexCoord2d(x,0); glVertex2f((float)bitmap.width,(float)bitmap.rows);
        glEnd();
        glPopMatrix();
        glTranslatef((GLfloat)(face->glyph->advance.x>>6),0,0);
        glEndList();
}

void TrueTypeText::init(const char *fname, unsigned int h) {
        textures = new GLuint[128];
		this->h = float(h);
		FT_Library library;
		if (FT_Init_FreeType(&library)) printf("FT_Init_FreeType failed!\n");
		FT_Face face;
		if (FT_New_Face(library, fname, 0, &face)) printf("loading font failed?\n");
        FT_Set_Char_Size(face, h<<6, h<<6,72,72);
        list_base=glGenLists(128);
        glGenTextures(128,textures);
        for (unsigned char i = 0; i < 128; i++)
			make_dlist(face,i,list_base,textures);
		FT_Done_Face(face);
		FT_Done_FreeType(library);
	}

void TrueTypeText::clean() {
        glDeleteLists(list_base,128);
        glDeleteTextures(128,textures);
		delete[] textures;
	}

void TrueTypeText::pushScreenCoordinateMatrix(int *scrWidth, int *scrHeight) {
	glPushAttrib(GL_TRANSFORM_BIT);
	GLint viewport[4];
	glGetIntegerv(GL_VIEWPORT,viewport);
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	gluOrtho2D(viewport[0],viewport[2],viewport[1],viewport[3]);
	glPopAttrib();
	*scrWidth = viewport[2]-viewport[0]+1;
	*scrHeight = viewport[3]-viewport[1]+1;
}
void TrueTypeText::pop_projection_matrix() {
	glPushAttrib(GL_TRANSFORM_BIT);
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glPopAttrib();
}

void TrueTypeText::printTTF(float x, float y, float z, float scaleX, float scaleY, bool flipY, const char *text) { //const char *fmt, ...) {
   // glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT | GL_LIGHTING_BIT | GL_TEXTURE_BIT | GL_DEPTH_BUFFER_BIT);
    const TrueTypeText &ft_font = *this;
    glDisable(GL_DEPTH_TEST);
    glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);

    float ySign = 1.0f;
    if (flipY) {
        ySign = -1.0f;
    }

    GLuint font = ft_font.list_base;
    float h = ft_font.h/.63f;
    const char *start_line = text;
    vector<string> lines;
    const char *c = text;
    for (c = text; *c; c++) {
        if (*c == '\n') {
            string line;
            for (const char *n=start_line; n<c; n++) line.append(1,*n);
            lines.push_back(line);
            start_line=c+1;
        }
    }
    if (start_line) {
        string line;
        for (const char *n=start_line;n<c; n++) line.append(1,*n);
        lines.push_back(line);
    }
    glMatrixMode(GL_MODELVIEW);
    glDisable(GL_LIGHTING);
    glEnable(GL_TEXTURE_2D);

    glListBase(font);
    glPushMatrix();
    for (size_t i = 0; i < lines.size();i++) {
        glPushMatrix();
        glLoadIdentity();
        glTranslatef(x,y+h*i,z);
        glScalef(scaleX,ySign*scaleY,1);
        glCallLists((GLsizei)lines[i].length(),GL_UNSIGNED_BYTE,lines[i].c_str());
        glPopMatrix();
    }
    glPopMatrix();
    //glPopAttrib();
};


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.Script.Serialization;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Events;
using Umbraco.Core.IO;
using Umbraco.Core.Models;

using Umbraco.Core.Persistence.Repositories;
using umbraco.interfaces;
using System.Linq;
using Umbraco.Web.PublishedCache.XmlPublishedCache;

namespace Umbraco.Web.Cache
{
    /// <summary>
    /// A cache refresher to ensure media cache is updated
    /// </summary>
    /// <remarks>
    /// This is not intended to be used directly in your code and it should be sealed but due to legacy code we cannot seal it.
    /// </remarks>
    public class MediaCacheRefresher : JsonCacheRefresherBase<MediaCacheRefresher>
    {
        #region Static helpers

        /// <summary>
        /// Converts the json to a JsonPayload object
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static JsonPayload[] DeserializeFromJsonPayload(string json)
        {
            var serializer = new JavaScriptSerializer();
            var jsonObject = serializer.Deserialize<JsonPayload[]>(json);
            return jsonObject;
        }

        /// <summary>
        /// Creates the custom Json payload used to refresh cache amongst the servers
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="media"></param>
        /// <returns></returns>
        internal static string SerializeToJsonPayload(OperationType operation, params IMedia[] media)
        {
            var serializer = new JavaScriptSerializer();
            var items = media.Select(x => FromMedia(x, operation)).ToArray();
            var json = serializer.Serialize(items);
            return json;
        }

        internal static string SerializeToJsonPayloadForMoving(OperationType operation, MoveEventInfo<IMedia>[] media)
        {
            var serializer = new JavaScriptSerializer();
            var items = media.Select(x => new JsonPayload
            {
                Id = x.Entity.Id,
                Operation = operation,
                Path = x.OriginalPath
            }).ToArray();
            var json = serializer.Serialize(items);
            return json;
        }

        internal static string SerializeToJsonPayloadForPermanentDeletion(params int[] mediaIds)
        {
            var serializer = new JavaScriptSerializer();
            var items = mediaIds.Select(x => new JsonPayload
            {
                Id = x,
                Operation = OperationType.Deleted
            }).ToArray();
            var json = serializer.Serialize(items);
            return json;
        }

        /// <summary>
        /// Converts a macro to a jsonPayload object
        /// </summary>
        /// <param name="media"></param>
        /// <param name="operation"></param>
        /// <returns></returns>
        internal static JsonPayload FromMedia(IMedia media, OperationType operation)
        {
            if (media == null) return null;

            var payload = new JsonPayload
            {
                Id = media.Id,
                Path = media.Path,
                Operation = operation
            };
            return payload;
        }

        #endregion

        #region Sub classes

        public enum OperationType
        {
            Saved,
            Trashed,
            Deleted
        }

        public class JsonPayload
        {
            public string Path { get; set; }
            public int Id { get; set; }
            public OperationType Operation { get; set; }
        }

        #endregion

        protected override MediaCacheRefresher Instance
        {
            get { return this; }
        }

        public override Guid UniqueIdentifier
        {
            get { return new Guid(DistributedCache.MediaCacheRefresherId); }
        }

        public override string Name
        {
            get { return "Clears Media Cache from umbraco.library"; }
        }

        public override void Refresh(string jsonPayload)
        {
            ClearCache(DeserializeFromJsonPayload(jsonPayload));
            base.Refresh(jsonPayload);
        }

        public override void Refresh(int id)
        {
            ClearCache(FromMedia(ApplicationContext.Current.Services.MediaService.GetById(id), OperationType.Saved));
            base.Refresh(id);
        }

        public override void Remove(int id)
        {
            ClearCache(FromMedia(ApplicationContext.Current.Services.MediaService.GetById(id),
                //NOTE: we'll just default to trashed for this one.
                OperationType.Trashed));
            base.Remove(id);
        }

        private static void ClearCache(params JsonPayload[] payloads)
        {
            if (payloads == null) return;

            ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(CacheKeys.IdToKeyCacheKey);
            ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(CacheKeys.KeyToIdCacheKey);
            ApplicationContext.Current.ApplicationCache.ClearPartialViewCache();

            payloads.ForEach(payload =>
            {
                var mediaCache = ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.GetCache<IMedia>();

                //if there's no path, then just use id (this will occur on permanent deletion like emptying recycle bin)
                if (payload.Path.IsNullOrWhiteSpace())
                {
                    ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(
                        string.Format("{0}_{1}", CacheKeys.MediaCacheKey, payload.Id));
                }
                else
                {
                    foreach (var idPart in payload.Path.Split(','))
                    {
                        int idPartAsInt;
                        if (int.TryParse(idPart, out idPartAsInt) && mediaCache)
                        {
                            mediaCache.Result.ClearCacheItem(RepositoryBase.GetCacheIdKey<IMedia>(idPartAsInt));
                        }

                        ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(
                            string.Format("{0}_{1}_True", CacheKeys.MediaCacheKey, idPart));

                        // Also clear calls that only query this specific item!
                        if (idPart == payload.Id.ToString(CultureInfo.InvariantCulture))
                            ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(
                                string.Format("{0}_{1}", CacheKeys.MediaCacheKey, payload.Id));
                    }
                }

                // published cache...
                PublishedMediaCache.ClearCache(payload.Id);
            });

        }
    }
}


text:
package fi.testee.rest;

/**
 * Interface to REST testing.
 *
 * @author Alex Stockinger, IT-Stockinger
 */
public interface RestServer {
    int getPort();
}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Net.Http;
using System.Text;

namespace RealEstateXamarinAndroidDemo
{
    public class AzureSearchHelper
    {
        // This sample uses the prototype API.  Please review the documenation for details on this API version - http://msdn.microsoft.com/en-us/library/azure/dn864560.aspx
        public const string ApiVersionString = "api-version=2015-02-28-Preview";

        private static readonly JsonSerializerSettings _jsonSettings;

        static AzureSearchHelper()
        {
            _jsonSettings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented, // for readability, change to None for compactness
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            };

            _jsonSettings.Converters.Add(new StringEnumConverter());
        }

        public static string SerializeJson(object value)
        {
            return JsonConvert.SerializeObject(value, _jsonSettings);
        }

        public static T DeserializeJson<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json, _jsonSettings);
        }

        public static HttpResponseMessage SendSearchRequest(HttpClient client, HttpMethod method, Uri uri, string json = null)
        {
            UriBuilder builder = new UriBuilder(uri);
            string separator = string.IsNullOrWhiteSpace(builder.Query) ? string.Empty : "&";
            builder.Query = builder.Query.TrimStart('?') + separator + ApiVersionString;

            var request = new HttpRequestMessage(method, builder.Uri);

            if (json != null)
            {
                request.Content = new StringContent(json, Encoding.UTF8, "application/json");
            }

            return client.SendAsync(request).Result;
        }

        public static void EnsureSuccessfulSearchResponse(HttpResponseMessage response)
        {
            if (!response.IsSuccessStatusCode)
            {
                string error = response.Content == null ? null : response.Content.ReadAsStringAsync().Result;
                throw new Exception("Search request failed: " + error);
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Amer. Acad. Arts & Sci. (1923)

#### Original name
Peziza irregularis Schwein.

### Remarks
null


text:
int SLNServerDispatch(SLNRepoRef const repo, SLNSessionRef const session, HTTPConnectionRef const conn, HTTPMethod const method, strarg_t const URI, HTTPHeadersRef const headers);

static strarg_t path = NULL;
static SLNRepoRef repo = NULL;
static RSSServerRef rss = NULL;
static BlogRef blog = NULL;
static HTTPServerRef server_raw = NULL;
static HTTPServerRef server_tls = NULL;
static uv_signal_t sigint[1] = {};
static int sig = 0;

static void listener(void *ctx, HTTPServerRef const server, HTTPConnectionRef const conn) {
	assert(server);
	assert(conn);
	HTTPMethod method = 99; // 0 is HTTP_DELETE...
	str_t URI[URI_MAX]; URI[0] = '\0';
	HTTPHeadersRef headers = NULL;
	SLNSessionRef session = NULL;
	ssize_t len = 0;
	int rc = 0;

	len = HTTPConnectionReadRequest(conn, &method, URI, sizeof(URI));
	if(UV_EOF == len) goto cleanup;
	if(UV_ECONNRESET == len) goto cleanup;
	if(len < 0) {
		rc = len;
		alogf("Request error: %s\n", uv_strerror(rc));
		goto cleanup;
	}

	rc = HTTPHeadersCreateFromConnection(conn, &headers);
	if(rc < 0) goto cleanup;

	strarg_t const host = HTTPHeadersGet(headers, "host");
	str_t domain[1023+1]; domain[0] = '\0';
	if(host) sscanf(host, "%1023[^:]", domain);
	// TODO: Verify Host header to prevent DNS rebinding.

	if(SERVER_PORT_TLS && server != server_tls) {
		rc = HTTPConnectionSendSecureRedirect(conn, domain, SERVER_PORT_TLS, URI);
		goto cleanup;
	}

	strarg_t const cookie = HTTPHeadersGet(headers, "cookie");
	SLNSessionCacheRef const cache = SLNRepoGetSessionCache(repo);
	rc = SLNSessionCacheCopyActiveSession(cache, cookie, &session);
	if(rc < 0) goto cleanup;
	// Note: null session is valid (zero permissions).

	rc = -1;
	rc = rc >= 0 ? rc : SLNServerDispatch(repo, session, conn, method, URI, headers);
	rc = rc >= 0 ? rc : RSSServerDispatch(rss, session, conn, method, URI, headers);
	rc = rc >= 0 ? rc : BlogDispatch(blog, session, conn, method, URI, headers);
	if(rc < 0) rc = 404;
	if(rc > 0) HTTPConnectionSendStatus(conn, rc);

cleanup:
	if(rc < 0) HTTPConnectionSendStatus(conn, HTTPError(rc));
	strarg_t const username = SLNSessionGetUsername(session);
	HTTPConnectionLog(conn, URI, username, headers, SERVER_LOG_FILE);
	SLNSessionRelease(&session);
	HTTPHeadersFree(&headers);
}

static void stop(uv_signal_t *const signal, int const signum) {
	sig = signum;
	uv_stop(async_loop);
}

static int init_http(void) {
	if(!SERVER_PORT_RAW) return 0;
	HTTPServerRef server = NULL;
	int rc = HTTPServerCreate((HTTPListener)listener, blog, &server);
	if(rc < 0) goto cleanup;
	rc = HTTPServerListen(server, SERVER_ADDRESS, SERVER_PORT_RAW);
	if(rc < 0) goto cleanup;
	int const port = SERVER_PORT_RAW;
	alogf("StrongLink server running at http://localhost:%d/\n", port);
	server_raw = server; server = NULL;
cleanup:
	HTTPServerFree(&server);
	if(rc < 0) {
		alogf("HTTP server could not be started: %s\n", sln_strerror(rc));
		return -1;
	}
	return 0;
}
static int init_https(void) {
	if(!SERVER_PORT_TLS) return 0;
	HTTPServerRef server = NULL;
	str_t keypath[PATH_MAX];
	str_t crtpath[PATH_MAX];
	int rc;
	rc = snprintf(keypath, sizeof(keypath), "%s/key.pem", path);
	if(rc >= sizeof(keypath)) rc = UV_ENAMETOOLONG;
	if(rc < 0) goto cleanup;
	rc = snprintf(crtpath, sizeof(crtpath), "%s/crt.pem", path);
	if(rc >= sizeof(crtpath)) rc = UV_ENAMETOOLONG;
	if(rc < 0) goto cleanup;

	rc = HTTPServerCreate((HTTPListener)listener, blog, &server);
	if(rc < 0) goto cleanup;
	rc = HTTPServerListenSecurePaths(server, SERVER_ADDRESS, SERVER_PORT_TLS, keypath, crtpath);
	if(rc < 0) goto cleanup;
	int const port = SERVER_PORT_TLS;
	alogf("StrongLink server running at https://localhost:%d/\n", port);
	server_tls = server; server = NULL;
cleanup:
	HTTPServerFree(&server);
	if(rc < 0) {
		alogf("HTTPS server could not be started: %s\n", sln_strerror(rc));
		return -1;
	}
	return 0;
}
static void init(void *const unused) {
	int rc = async_random((byte_t *)&SLNSeed, sizeof(SLNSeed));
	if(rc < 0) {
		alogf("Random seed error\n");
		return;
	}

	str_t *tmp = strdup(path);
	strarg_t const reponame = basename(tmp); // TODO
	rc = SLNRepoCreate(path, reponame, &repo);
	FREE(&tmp);
	if(rc < 0) {
		alogf("Repository could not be opened: %s\n", sln_strerror(rc));
		return;
	}
	blog = BlogCreate(repo);
	if(!blog) {
		alogf("Blog server could not be initialized\n");
		return;
	}
	rc = RSSServerCreate(repo, &rss);
	if(rc < 0) {
		alogf("RSS server error: %s\n", sln_strerror(rc));
		return;
	}

	if(init_http() < 0 || init_https() < 0) {
		HTTPServerClose(server_raw);
		HTTPServerClose(server_tls);
		return;
	}

//	SLNRepoPullsStart(repo);

	uv_signal_init(async_loop, sigint);
	uv_signal_start(sigint, stop, SIGINT);
	uv_unref((uv_handle_t *)sigint);
}
static void term(void *const unused) {
	fprintf(stderr, "\n");
	alogf("Stopping StrongLink server...\n");

	uv_ref((uv_handle_t *)sigint);
	uv_signal_stop(sigint);
	async_close((uv_handle_t *)sigint);

	SLNRepoPullsStop(repo);
	HTTPServerClose(server_raw);
	HTTPServerClose(server_tls);

	async_pool_enter(NULL);
	fflush(NULL); // Everything.
	async_pool_leave(NULL);
}
static void cleanup(void *const unused) {
	HTTPServerFree(&server_raw);
	HTTPServerFree(&server_tls);
	RSSServerFree(&rss);
	BlogFree(&blog);
	SLNRepoFree(&repo);

	async_pool_enter(NULL);
	fflush(NULL); // Everything.
	async_pool_leave(NULL);

	async_pool_destroy_shared();
}

int main(int const argc, char const *const *const argv) {
	int rc = async_process_init();
	if(rc < 0) {
		fprintf(stderr, "Initialization error: %s\n", uv_strerror(rc));
		return 1;
	}
	rc = tls_init();
	if(rc < 0) {
		fprintf(stderr, "TLS initialization error: %s\n", strerror(errno));
		return 1;
	}

	if(2 != argc || '-' == argv[1][0]) {
		fprintf(stderr, "Usage:\n\t" "%s repo\n", argv[0]);
		return 1;
	}
	path = argv[1];

	// Even our init code wants to use async I/O.
	async_spawn(STACK_DEFAULT, init, NULL);
	uv_run(async_loop, UV_RUN_DEFAULT);

	async_spawn(STACK_DEFAULT, term, NULL);
	uv_run(async_loop, UV_RUN_DEFAULT);

#ifdef SLN_USE_VALGRIND
	// Note: With Valgrind disabled, libasync unrefs HTTP connections
	// while blocking, which lets us terminate promptly. However, those
	// unref'd connections don't actually get closed or freed, so
	// freeing other structures can cause problems. Instead, we just
	// let the process die and the OS clean everything up.
	//
	// With Valgrind enabled, we wait for all pending connections to close
	// and then free everything properly.
	//
	// The correct solution here is probably to keep a list of all
	// active connections, and tell them to terminate when we want to quit.

	async_spawn(STACK_DEFAULT, cleanup, NULL);
	uv_run(async_loop, UV_RUN_DEFAULT);

	async_process_destroy();
#endif

	// TODO: Windows?
	if(sig) raise(sig);

	return 0;
}


text:
/****************************************************************************/

/*
 *	mcftimer.h -- ColdFire internal TIMER support defines.
 *
 *	(C) Copyright 1999-2006, Greg Ungerer <gerg@snapgear.com>
 * 	(C) Copyright 2000, Lineo Inc. (www.lineo.com)
 */

/****************************************************************************/
#ifndef	mcftimer_h
#define	mcftimer_h
/****************************************************************************/

/*
 *	Get address specific defines for this ColdFire member.
 */
#if defined(CONFIG_M5204) || defined(CONFIG_M5206) || defined(CONFIG_M5206e)
#define	MCFTIMER_BASE1		0x100		/* Base address of TIMER1 */
#define	MCFTIMER_BASE2		0x120		/* Base address of TIMER2 */
#elif defined(CONFIG_M5272)
#define MCFTIMER_BASE1		0x200           /* Base address of TIMER1 */
#define MCFTIMER_BASE2		0x220           /* Base address of TIMER2 */
#define MCFTIMER_BASE3		0x240           /* Base address of TIMER4 */
#define MCFTIMER_BASE4		0x260           /* Base address of TIMER3 */
#elif defined(CONFIG_M5249) || defined(CONFIG_M5307) || defined(CONFIG_M5407)
#define MCFTIMER_BASE1		0x140           /* Base address of TIMER1 */
#define MCFTIMER_BASE2		0x180           /* Base address of TIMER2 */
#elif defined(CONFIG_M532x)
#define MCFTIMER_BASE1		0xfc070000	/* Base address of TIMER1 */
#define MCFTIMER_BASE2		0xfc074000	/* Base address of TIMER2 */
#define MCFTIMER_BASE3		0xfc078000	/* Base address of TIMER3 */
#define MCFTIMER_BASE4		0xfc07c000	/* Base address of TIMER4 */
#endif

/*
 *	Define the TIMER register set addresses.
 */
#define	MCFTIMER_TMR		0x00		/* Timer Mode reg (r/w) */
#define	MCFTIMER_TRR		0x04		/* Timer Reference (r/w) */
#define	MCFTIMER_TCR		0x08		/* Timer Capture reg (r/w) */
#define	MCFTIMER_TCN		0x0C		/* Timer Counter reg (r/w) */
#if defined(CONFIG_M532x)
#define	MCFTIMER_TER		0x03		/* Timer Event reg (r/w) */
#else
#define	MCFTIMER_TER		0x11		/* Timer Event reg (r/w) */
#endif

/*
 *	Bit definitions for the Timer Mode Register (TMR).
 *	Register bit flags are common accross ColdFires.
 */
#define	MCFTIMER_TMR_PREMASK	0xff00		/* Prescalar mask */
#define	MCFTIMER_TMR_DISCE	0x0000		/* Disable capture */
#define	MCFTIMER_TMR_ANYCE	0x00c0		/* Capture any edge */
#define	MCFTIMER_TMR_FALLCE	0x0080		/* Capture fallingedge */
#define	MCFTIMER_TMR_RISECE	0x0040		/* Capture rising edge */
#define	MCFTIMER_TMR_ENOM	0x0020		/* Enable output toggle */
#define	MCFTIMER_TMR_DISOM	0x0000		/* Do single output pulse  */
#define	MCFTIMER_TMR_ENORI	0x0010		/* Enable ref interrupt */
#define	MCFTIMER_TMR_DISORI	0x0000		/* Disable ref interrupt */
#define	MCFTIMER_TMR_RESTART	0x0008		/* Restart counter */
#define	MCFTIMER_TMR_FREERUN	0x0000		/* Free running counter */
#define	MCFTIMER_TMR_CLKTIN	0x0006		/* Input clock is TIN */
#define	MCFTIMER_TMR_CLK16	0x0004		/* Input clock is /16 */
#define	MCFTIMER_TMR_CLK1	0x0002		/* Input clock is /1 */
#define	MCFTIMER_TMR_CLKSTOP	0x0000		/* Stop counter */
#define	MCFTIMER_TMR_ENABLE	0x0001		/* Enable timer */
#define	MCFTIMER_TMR_DISABLE	0x0000		/* Disable timer */

/*
 *	Bit definitions for the Timer Event Registers (TER).
 */
#define	MCFTIMER_TER_CAP	0x01		/* Capture event */
#define	MCFTIMER_TER_REF	0x02		/* Refernece event */

/****************************************************************************/
#endif	/* mcftimer_h */


text:
module ChattyCrow
  module Request
    # HipChat request
    class HipChat < BaseRequest
      def initialize(*args)
        super(*args)

        # If arguments exists set as body into options!
        # Its for just easy ChattyCrow.send_hipchat 'Hello'
        @options[:body] = @arguments_flatten if @arguments_flatten

        # Set payload
        @payload = @options
      end
    end
  end
end


text: require "itamae/plugin/recipe/mackerel-agent/default"


text:
var Update = function (model, version) {
    this.model = model;
    this.previous_version = version;
};
Update.from = function (model, version) {
    return new Update(model, version);
};
Update.prototype.to = function (version, migration) {
    return this.model.find({schema_version: this.previous_version}).exec(function (err, objects) {
        objects.forEach(function (obj) {
            obj.update(migration).exec(function (err2, res) {
                if (res) {
                    console.log('Object Updated to Version {}'.format(version));
                } else {
                    console.log('Error while trying to update Object to Version {}'.format(version))
                }
            });
        });
    })
};

module.exports = Update;


text:
require 'spec_helper'

describe 'instrument_classes' do
  let(:config) { double(:config) }

  let(:influx_sampler) { double(:influx_sampler) }

  before do
    allow(config).to receive(:instrument_method)
    allow(config).to receive(:instrument_methods)
    allow(config).to receive(:instrument_instance_method)
    allow(config).to receive(:instrument_instance_methods)
    allow(Gitlab::Metrics::Samplers::InfluxSampler).to receive(:initialize_instance).and_return(influx_sampler)
    allow(influx_sampler).to receive(:start)
    allow(Gitlab::Application).to receive(:configure)
  end

  it 'can autoload and instrument all files' do
    require_relative '../../config/initializers/zz_metrics'
    expect { instrument_classes(config) }.not_to raise_error
  end
end


text:
package org.openflow.protocol.action;

import org.jboss.netty.buffer.ChannelBuffer;

public class OFActionMark extends OFAction {
	public static int MINIMUM_LENGTH = 8;

	protected int markerId;

	public OFActionMark() {
        super.setType(OFActionType.OPAQUE_MARK);
        super.setLength((short) OFActionMark.MINIMUM_LENGTH);
    }

    public OFActionMark(final int markerId) {
        this();
        this.markerId = markerId;
    }

    public void setMarkerId(final int markerId) {
    	this.markerId = markerId;
    }

    public int getMarkerId() {
    	return this.markerId;
    }

    @Override
    public void readFrom(final ChannelBuffer data) {
        super.readFrom(data);
        this.markerId = data.readInt();
    }

    @Override
    public void writeTo(final ChannelBuffer data) {
        super.writeTo(data);
        data.writeInt(this.markerId);
    }

    @Override
    public int hashCode() {
        final int prime = 691;
        int result = super.hashCode();
        result = prime * result + this.markerId;
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (!super.equals(obj)) {
            return false;
        }
        if (!(obj instanceof OFActionMark)) {
            return false;
        }
        final OFActionMark other = (OFActionMark) obj;
        if (this.markerId != other.markerId) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        final StringBuilder builder = new StringBuilder();
        builder.append(this.type);
        builder.append("[");
        builder.append("Marker Id: ");
        builder.append(this.markerId);
        builder.append("]");
        return builder.toString();
    }
}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-3-7.js
 * @description Object.defineProperties - no additional property is defined in 'O' when 'Properties' doesn't contain enumerable own property
 */

function testcase() {

        var obj = {};

        var props = {};

        Object.defineProperty(props, "prop1", {
            value: {},
            enumerable: false
        });

        Object.defineProperty(props, "prop2", {
            get: function () {
                return {};
            },
            enumerable: false
        });

        Object.defineProperties(obj, props);

        return !obj.hasOwnProperty("prop1") && !obj.hasOwnProperty("prop2");
    }
runTestCase(testcase);


text:
{% extends "oscar/catalogue/reviews/review_list.html" %}
{% load url from future %}
{% load currency_filters %}
{% load history_tags %}
{% load thumbnail %}
{% load i18n %}
{% load staticfiles %}
{% load reviews_tags %}

{% block content %}

                {% include "catalogue/partials/gallery.html" %}

                {% include "catalogue/partials/review_totals.html" %}
                {% if reviews %}

{% trans "Sort by:" %}

                    <form action="." method="get" class="form-inline">
                        <select name="sort_by">
                            <option value="score">{% trans "Score" %}</option>
                            <option value="recency">{% trans "Recency" %}</option>
                        </select>
                        <input type="submit" class="btn" value="{% trans "Go" %}" />
                    </form>

                    {% for review in reviews %}
                        {% include 'catalogue/partials/review.html' %}
                    {% endfor %}
                    {% include 'partials/pagination.html' %}

                {% else %}

{% trans "This product does not have any reviews yet." %}

                {% endif %}

{% endblock %}


text:
package org.apache.sling.query.iterator;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WarningIterator<T> extends AbstractIterator<T> {

	private static final Logger LOG = LoggerFactory.getLogger("SlingQuery");

	private static final int DEFAULT_LIMIT = 100;

	private final Iterator<T> iterator;

	private final int limit;

	private int count = 0;

	public WarningIterator(Iterator<T> iterator) {
		this(iterator, DEFAULT_LIMIT);
	}

	public WarningIterator(Iterator<T> iterator, int limit) {
		this.iterator = iterator;
		this.limit = limit;
	}

	@Override
	protected T getElement() {
		if (!iterator.hasNext()) {
			return null;
		}
		if (count++ == limit) {
			LOG.warn(
					"Number of processed resources exceeded {}. Consider using a JCR query instead of SlingQuery. More info here: http://git.io/h2HeUQ",
					new Object[] { limit });
		}
		return iterator.next();
	}

}


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

<title>LoadSamplesTask</title>
<meta name="date" content="2014-05-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.morzeux.bioseclogger.tasks

Class LoadSamplesTask

java.lang.Object

<any>

com.morzeux.bioseclogger.tasks.LoadSamplesTask

public class LoadSamplesTask
extends <any>

Loads samples from source directory as asynchronous task.

Author:

Stefan Smihla

Field Summary

Fields

Modifier and Type
Field and Description

private SamplesOverviewActivity
act

private PopupBuilder
popup

Constructor Summary

Constructors

Constructor and Description

LoadSamplesTask(SamplesOverviewActivity act)

Constructor with activity.

Method Summary

Methods

Modifier and Type
Method and Description

protected Datasets
doInBackground(java.lang.String... params)

protected void
onPostExecute(Datasets dataset)

protected void
onPreExecute()

Methods inherited from class java.lang.Object

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

Field Detail

act

private SamplesOverviewActivity act

popup

private PopupBuilder popup

Constructor Detail

LoadSamplesTask

public LoadSamplesTask(SamplesOverviewActivity act)

Constructor with activity. Activity is needed to invoke popup.

Parameters:

act - source activity

Method Detail

onPreExecute

protected void onPreExecute()

doInBackground

protected Datasets doInBackground(java.lang.String... params)

onPostExecute

protected void onPostExecute(Datasets dataset)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
@implementation SCDGLabel

- (instancetype)init{

    if (self = [super init]) {
        ;
    }

    return self;
}

-(instancetype)initWithFrame:(CGRect)frame{

    if (self = [super initWithFrame:frame]) {
        ;
    }

    return self;
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder{

    if (self = [super initWithCoder:aDecoder]) {

        self.acceptorId = (uint32_t)self.tag;

    }

    return self;
}

- (void)setTag:(NSInteger)tag{

    [super setTag:tag];

    self.acceptorId = (uint32_t)tag;

}

-(void)layoutSubviews{

    [super layoutSubviews];

    if (self.acceptorId) {

        [self layoutByControlInfo];

    }

}

- (void)layoutByControlInfo{

    NSArray<MsgMessageContent *> * puppies = [self getControlInfos];

    for (MsgMessageContent *controlInfo in puppies) {

        [self changeByControlInfo:controlInfo];

    }

}

- (void)changeByControlInfo:(MsgMessageContent*)controlInfo{

    if (controlInfo.type == SCDGControlTypeChangeUI) {

        switch (controlInfo.action) {

            case SCDGActionTypeContent:

                self.text = controlInfo.payload;
                break;

            case SCDGActionTypeTextColor:

                if (controlInfo.payload && [SCDGUtils isValidStr:controlInfo.payload] && controlInfo.payload.length == 6) {
                    self.textColor = [SCDGUtils getColor:controlInfo.payload];
                }
                break;

            case SCDGActionTypeBackgroundColor:

                if (controlInfo.payload && [SCDGUtils isValidStr:controlInfo.payload] && controlInfo.payload.length == 6) {
                    self.backgroundColor = [SCDGUtils getColor:controlInfo.payload];
                }
                break;

            default:
                break;
        }

    }else if (controlInfo.type == SCDGControlTypeEnable){

        self.userInteractionEnabled = controlInfo.action;

    }
}
- (void)handleControlWith:(MsgMessageContent *)message{

    dispatch_async(dispatch_get_main_queue(), ^{

        [self changeByControlInfo:message];

    });

}

- (void)dealloc{

    [self unsubscribeRemoteControl];

}

@end


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

<title>Uses of Class java.net.InetAddress (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev

Next

Frames

No Frames

All Classes

Uses of Class
java.net.InetAddress

Packages that use InetAddress

Package
Description

java.lang

Provides classes that are fundamental to the design of the Java
 programming language.

java.net

Provides the classes for implementing networking applications.

java.nio.channels

Defines channels, which represent connections to entities that are capable of
 performing I/O operations, such as files and sockets; defines selectors, for
 multiplexed, non-blocking I/O operations.

javax.net

Provides classes for networking applications.

javax.net.ssl

Provides classes for the secure socket package.

javax.security.auth.kerberos

This package contains utility classes related to the Kerberos network
    authentication protocol.

org.ietf.jgss

This package presents a framework that allows application developers to
    make use of security services like authentication, data integrity and
    data confidentiality from a variety of underlying security mechanisms
    like Kerberos, using a unified API.

Uses of InetAddress in java.lang

Methods in java.lang with parameters of type InetAddress

Modifier and Type
Method and Description

void
SecurityManager.checkMulticast(InetAddress maddr)

Throws a SecurityException if the
 calling thread is not allowed to use
 (join/leave/send/receive) IP multicast.

void
SecurityManager.checkMulticast(InetAddress maddr,
              byte ttl)

Deprecated.

Use #checkPermission(java.security.Permission) instead

Uses of InetAddress in java.net

Subclasses of InetAddress in java.net

Modifier and Type
Class and Description

class
Inet4Address

This class represents an Internet Protocol version 4 (IPv4) address.

class
Inet6Address

This class represents an Internet Protocol version 6 (IPv6) address.

Fields in java.net declared as InetAddress

Modifier and Type
Field and Description

protected InetAddress
SocketImpl.address

The IP address of the remote end of this socket.

Methods in java.net that return InetAddress

Modifier and Type
Method and Description

InetAddress
InterfaceAddress.getAddress()

Returns an InetAddress for this address.

InetAddress
InetSocketAddress.getAddress()

Gets the InetAddress.

InetAddress
DatagramPacket.getAddress()

Returns the IP address of the machine to which this datagram is being
 sent or from which the datagram was received.

static InetAddress[]
InetAddress.getAllByName(String host)

Given the name of a host, returns an array of its IP addresses,
 based on the configured name service on the system.

InetAddress
InterfaceAddress.getBroadcast()

Returns an InetAddress for the brodcast address
 for this InterfaceAddress.

static InetAddress
InetAddress.getByAddress(byte[] addr)

Returns an InetAddress object given the raw IP address .

static InetAddress
InetAddress.getByAddress(String host,
            byte[] addr)

Creates an InetAddress based on the provided host name and IP address.

static InetAddress
InetAddress.getByName(String host)

Determines the IP address of a host, given the host's name.

protected InetAddress
URLStreamHandler.getHostAddress(URL u)

Get the IP address of our host.

InetAddress
DatagramSocket.getInetAddress()

Returns the address to which this socket is connected.

InetAddress
Socket.getInetAddress()

Returns the address to which the socket is connected.

protected InetAddress
SocketImpl.getInetAddress()

Returns the value of this socket's address field.

InetAddress
ServerSocket.getInetAddress()

Returns the local address of this server socket.

InetAddress
MulticastSocket.getInterface()

Retrieve the address of the network interface used for
 multicast packets.

InetAddress
DatagramSocket.getLocalAddress()

Gets the local address to which the socket is bound.

InetAddress
Socket.getLocalAddress()

Gets the local address to which the socket is bound.

static InetAddress
InetAddress.getLocalHost()

Returns the address of the local host.

static InetAddress
InetAddress.getLoopbackAddress()

Returns the loopback address.

protected InetAddress
Authenticator.getRequestingSite()

Gets the InetAddress of the
 site requesting authorization, or null
 if not available.

Methods in java.net that return types with arguments of type InetAddress

Modifier and Type
Method and Description

Enumeration<InetAddress>
NetworkInterface.getInetAddresses()

Convenience method to return an Enumeration with all or a
 subset of the InetAddresses bound to this network interface.

Methods in java.net with parameters of type InetAddress

Modifier and Type
Method and Description

protected abstract void
SocketImpl.bind(InetAddress host,
    int port)

Binds this socket to the specified local IP address and port number.

protected abstract void
DatagramSocketImpl.bind(int lport,
    InetAddress laddr)

Binds a datagram socket to a local port and address.

void
DatagramSocket.connect(InetAddress address,
       int port)

Connects the socket to a remote address for this socket.

protected abstract void
SocketImpl.connect(InetAddress address,
       int port)

Connects this socket to the specified port number on the specified host.

protected void
DatagramSocketImpl.connect(InetAddress address,
       int port)

Connects a datagram socket to a remote destination.

static NetworkInterface
NetworkInterface.getByInetAddress(InetAddress addr)

Convenience method to search for a network interface that
 has the specified Internet Protocol (IP) address bound to
 it.

protected abstract void
DatagramSocketImpl.join(InetAddress inetaddr)

Join the multicast group.

void
MulticastSocket.joinGroup(InetAddress mcastaddr)

Joins a multicast group.

protected abstract void
DatagramSocketImpl.leave(InetAddress inetaddr)

Leave the multicast group.

void
MulticastSocket.leaveGroup(InetAddress mcastaddr)

Leave a multicast group.

protected abstract int
DatagramSocketImpl.peek(InetAddress i)

Peek at the packet to see who it is from.

static PasswordAuthentication
Authenticator.requestPasswordAuthentication(InetAddress addr,
                             int port,
                             String protocol,
                             String prompt,
                             String scheme)

Ask the authenticator that has been registered with the system
 for a password.

static PasswordAuthentication
Authenticator.requestPasswordAuthentication(String host,
                             InetAddress addr,
                             int port,
                             String protocol,
                             String prompt,
                             String scheme)

Ask the authenticator that has been registered with the system
 for a password.

static PasswordAuthentication
Authenticator.requestPasswordAuthentication(String host,
                             InetAddress addr,
                             int port,
                             String protocol,
                             String prompt,
                             String scheme,
                             URL url,
                             Authenticator.RequestorType reqType)

Ask the authenticator that has been registered with the system
 for a password.

void
DatagramPacket.setAddress(InetAddress iaddr)

Sets the IP address of the machine to which this datagram
 is being sent.

void
MulticastSocket.setInterface(InetAddress inf)

Set the multicast network interface used by methods
 whose behavior would be affected by the value of the
 network interface.

Constructors in java.net with parameters of type InetAddress

Constructor and Description

DatagramPacket(byte[] buf,
              int length,
              InetAddress address,
              int port)

Constructs a datagram packet for sending packets of length
 length to the specified port number on the specified
 host.

DatagramPacket(byte[] buf,
              int offset,
              int length,
              InetAddress address,
              int port)

Constructs a datagram packet for sending packets of length
 length with offset ioffsetto the
 specified port number on the specified host.

DatagramSocket(int port,
              InetAddress laddr)

Creates a datagram socket, bound to the specified local
 address.

InetSocketAddress(InetAddress addr,
                 int port)

Creates a socket address from an IP address and a port number.

ServerSocket(int port,
            int backlog,
            InetAddress bindAddr)

Create a server with the specified port, listen backlog, and
 local IP address to bind to.

Socket(InetAddress address,
      int port)

Creates a stream socket and connects it to the specified port
 number at the specified IP address.

Socket(InetAddress host,
      int port,
      boolean stream)

Deprecated.

Use DatagramSocket instead for UDP transport.

Socket(InetAddress address,
      int port,
      InetAddress localAddr,
      int localPort)

Creates a socket and connects it to the specified remote address on
 the specified remote port.

Socket(String host,
      int port,
      InetAddress localAddr,
      int localPort)

Creates a socket and connects it to the specified remote host on
 the specified remote port.

Uses of InetAddress in java.nio.channels

Methods in java.nio.channels that return InetAddress

Modifier and Type
Method and Description

abstract InetAddress
MembershipKey.group()

Returns the multicast group for which this membership key was created.

abstract InetAddress
MembershipKey.sourceAddress()

Returns the source address if this membership key is source-specific,
 or null if this membership is not source-specific.

Methods in java.nio.channels with parameters of type InetAddress

Modifier and Type
Method and Description

abstract MembershipKey
MembershipKey.block(InetAddress source)

Block multicast datagrams from the given source address.

MembershipKey
MulticastChannel.join(InetAddress group,
    NetworkInterface interf)

Joins a multicast group to begin receiving all datagrams sent to the group,
 returning a membership key.

MembershipKey
MulticastChannel.join(InetAddress group,
    NetworkInterface interf,
    InetAddress source)

Joins a multicast group to begin receiving datagrams sent to the group
 from a given source address.

abstract MembershipKey
MembershipKey.unblock(InetAddress source)

Unblock multicast datagrams from the given source address that was
 previously blocked using the block method.

Uses of InetAddress in javax.net

Methods in javax.net with parameters of type InetAddress

Modifier and Type
Method and Description

abstract ServerSocket
ServerSocketFactory.createServerSocket(int port,
                  int backlog,
                  InetAddress ifAddress)

Returns a server socket bound to the specified port,
 with a specified listen backlog and local IP.

abstract Socket
SocketFactory.createSocket(InetAddress host,
            int port)

Creates a socket and connects it to the specified port number
 at the specified address.

abstract Socket
SocketFactory.createSocket(InetAddress address,
            int port,
            InetAddress localAddress,
            int localPort)

Creates a socket and connect it to the specified remote address
 on the specified remote port.

abstract Socket
SocketFactory.createSocket(String host,
            int port,
            InetAddress localHost,
            int localPort)

Creates a socket and connects it to the specified remote host
 on the specified remote port.

Uses of InetAddress in javax.net.ssl

Constructors in javax.net.ssl with parameters of type InetAddress

Constructor and Description

SSLServerSocket(int port,
               int backlog,
               InetAddress address)

Used only by subclasses.

SSLSocket(InetAddress address,
         int port)

Used only by subclasses.

SSLSocket(InetAddress address,
         int port,
         InetAddress clientAddress,
         int clientPort)

Used only by subclasses.

SSLSocket(String host,
         int port,
         InetAddress clientAddress,
         int clientPort)

Used only by subclasses.

Uses of InetAddress in javax.security.auth.kerberos

Methods in javax.security.auth.kerberos that return InetAddress

Modifier and Type
Method and Description

InetAddress[]
KerberosTicket.getClientAddresses()

Returns a list of addresses from where the ticket can be used.

Constructors in javax.security.auth.kerberos with parameters of type InetAddress

Constructor and Description

KerberosTicket(byte[] asn1Encoding,
              KerberosPrincipal client,
              KerberosPrincipal server,
              byte[] sessionKey,
              int keyType,
              boolean[] flags,
              Date authTime,
              Date startTime,
              Date endTime,
              Date renewTill,
              InetAddress[] clientAddresses)

Constructs a KerberosTicket using credentials information that a
 client either receives from a KDC or reads from a cache.

Uses of InetAddress in org.ietf.jgss

Methods in org.ietf.jgss that return InetAddress

Modifier and Type
Method and Description

InetAddress
ChannelBinding.getAcceptorAddress()

Get the acceptor's address for this channel binding.

InetAddress
ChannelBinding.getInitiatorAddress()

Get the initiator's address for this channel binding.

Constructors in org.ietf.jgss with parameters of type InetAddress

Constructor and Description

ChannelBinding(InetAddress initAddr,
              InetAddress acceptAddr,
              byte[] appData)

Create a ChannelBinding object with user supplied address information
 and data.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
=====================
NetApp unified driver
=====================

The NetApp unified driver is a Block Storage driver that supports
multiple storage families and protocols. A storage family corresponds to
storage systems built on either clustered Data ONTAP or E-Series. The
storage protocol refers to the protocol used to initiate data storage and
access operations on those storage systems like iSCSI and NFS. The NetApp
unified driver can be configured to provision and manage OpenStack volumes
on a given storage family using a specified storage protocol.

Also, the NetApp unified driver supports over subscription or over
provisioning when thin provisioned Block Storage volumes are in use.
The OpenStack volumes can then be used for
accessing and storing data using the storage protocol on the storage
family system. The NetApp unified driver is an extensible interface
that can support new storage families and protocols.

.. note::

   With the Juno release of OpenStack, Block Storage has
   introduced the concept of storage pools, in which a single
   Block Storage back end may present one or more logical
   storage resource pools from which Block Storage will
   select a storage location when provisioning volumes.

   In releases prior to Juno, the NetApp unified driver contained some
   scheduling logic that determined which NetApp storage container
   (namely, a FlexVol volume for Data ONTAP, or a dynamic disk pool for
   E-Series) that a new Block Storage volume would be placed into.

   With the introduction of pools, all scheduling logic is performed
   completely within the Block Storage scheduler, as each
   NetApp storage container is directly exposed to the Block
   Storage scheduler as a storage pool. Previously, the NetApp
   unified driver presented an aggregated view to the scheduler and
   made a final placement decision as to which NetApp storage container
   the Block Storage volume would be provisioned into.

NetApp clustered Data ONTAP storage family
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The NetApp clustered Data ONTAP storage family represents a
configuration group which provides Compute instances access to
clustered Data ONTAP storage systems. At present it can be configured in
Block Storage to work with iSCSI and NFS storage protocols.

NetApp iSCSI configuration for clustered Data ONTAP
---------------------------------------------------

The NetApp iSCSI configuration for clustered Data ONTAP is an interface
from OpenStack to clustered Data ONTAP storage systems. It provisions
and manages the SAN block storage entity, which is a NetApp LUN that
can be accessed using the iSCSI protocol.

The iSCSI configuration for clustered Data ONTAP is a direct interface
from Block Storage to the clustered Data ONTAP instance and as
such does not require additional management software to achieve the
desired functionality. It uses NetApp APIs to interact with the
clustered Data ONTAP instance.

**Configuration options**

Configure the volume driver, storage family, and storage protocol to the
NetApp unified driver, clustered Data ONTAP, and iSCSI respectively by
setting the ``volume_driver``, ``netapp_storage_family`` and
``netapp_storage_protocol`` options in the ``cinder.conf`` file as follows:

.. code-block:: ini

   volume_driver = cinder.volume.drivers.netapp.common.NetAppDriver
   netapp_storage_family = ontap_cluster
   netapp_storage_protocol = iscsi
   netapp_vserver = openstack-vserver
   netapp_server_hostname = myhostname
   netapp_server_port = port
   netapp_login = username
   netapp_password = password

.. note::

   To use the iSCSI protocol, you must override the default value of
   ``netapp_storage_protocol`` with ``iscsi``.

.. include:: ../../tables/cinder-netapp_cdot_iscsi.inc

.. note::

   If you specify an account in the ``netapp_login`` that only has
   virtual storage server (Vserver) administration privileges (rather
   than cluster-wide administration privileges), some advanced features
   of the NetApp unified driver will not work and you may see warnings
   in the Block Storage logs.

.. note::

   The driver supports iSCSI CHAP uni-directional authentication.
   To enable it, set the ``use_chap_auth`` option to ``True``.

.. tip::

   For more information on these options and other deployment and
   operational scenarios, visit the `NetApp OpenStack website
   <http://netapp.io/openstack/>`_.

NetApp NFS configuration for clustered Data ONTAP
-------------------------------------------------

The NetApp NFS configuration for clustered Data ONTAP is an interface from
OpenStack to a clustered Data ONTAP system for provisioning and managing
OpenStack volumes on NFS exports provided by the clustered Data ONTAP system
that are accessed using the NFS protocol.

The NFS configuration for clustered Data ONTAP is a direct interface from
Block Storage to the clustered Data ONTAP instance and as such does
not require any additional management software to achieve the desired
functionality. It uses NetApp APIs to interact with the clustered Data ONTAP
instance.

**Configuration options**

Configure the volume driver, storage family, and storage protocol to NetApp
unified driver, clustered Data ONTAP, and NFS respectively by setting the
``volume_driver``, ``netapp_storage_family``, and ``netapp_storage_protocol``
options in the ``cinder.conf`` file as follows:

.. code-block:: ini

   volume_driver = cinder.volume.drivers.netapp.common.NetAppDriver
   netapp_storage_family = ontap_cluster
   netapp_storage_protocol = nfs
   netapp_vserver = openstack-vserver
   netapp_server_hostname = myhostname
   netapp_server_port = port
   netapp_login = username
   netapp_password = password
   nfs_shares_config = /etc/cinder/nfs_shares

.. include:: ../../tables/cinder-netapp_cdot_nfs.inc

.. note::

   Additional NetApp NFS configuration options are shared with the
   generic NFS driver. These options can be found here:
   :ref:`cinder-storage_nfs`.

.. note::

   If you specify an account in the ``netapp_login`` that only has
   virtual storage server (Vserver) administration privileges (rather
   than cluster-wide administration privileges), some advanced features
   of the NetApp unified driver will not work and you may see warnings
   in the Block Storage logs.

NetApp NFS Copy Offload client
------------------------------

A feature was added in the Icehouse release of the NetApp unified driver that
enables Image service images to be efficiently copied to a destination Block
Storage volume. When the Block Storage and Image service are configured to use
the NetApp NFS Copy Offload client, a controller-side copy will be attempted
before reverting to downloading the image from the Image service. This improves
image provisioning times while reducing the consumption of bandwidth and CPU
cycles on the host(s) running the Image and Block Storage services. This is due
to the copy operation being performed completely within the storage cluster.

The NetApp NFS Copy Offload client can be used in either of the following
scenarios:

- The Image service is configured to store images in an NFS share that is
  exported from a NetApp FlexVol volume *and* the destination for the new Block
  Storage volume will be on an NFS share exported from a different FlexVol
  volume than the one used by the Image service. Both FlexVols must be located
  within the same cluster.

- The source image from the Image service has already been cached in an NFS
  image cache within a Block Storage back end. The cached image resides on a
  different FlexVol volume than the destination for the new Block Storage
  volume. Both FlexVols must be located within the same cluster.

To use this feature, you must configure the Image service, as follows:

- Set the ``default_store`` configuration option to ``file``.

- Set the ``filesystem_store_datadir`` configuration option to the path
  to the Image service NFS export.

- Set the ``show_image_direct_url`` configuration option to ``True``.

- Set the ``show_multiple_locations`` configuration option to ``True``.

- Set the ``filesystem_store_metadata_file`` configuration option to a metadata
  file. The metadata file should contain a JSON object that contains the
  correct information about the NFS export used by the Image service.

To use this feature, you must configure the Block Storage service, as follows:

- Set the ``netapp_copyoffload_tool_path`` configuration option to the path to
  the NetApp Copy Offload binary.

  .. important::

     This feature requires that:

     - The storage system must have Data ONTAP v8.2 or greater installed.

     - The vStorage feature must be enabled on each storage virtual machine
       (SVM, also known as a Vserver) that is permitted to interact with the
       copy offload client.

     - To configure the copy offload workflow, enable NFS v4.0 or greater and
       export it from the SVM.

.. tip::

   To download the NetApp copy offload binary to be utilized in conjunction
   with the ``netapp_copyoffload_tool_path`` configuration option, please visit
   the Utility Toolchest page at the `NetApp Support portal
   <http://mysupport.netapp.com/NOW/download/tools/ntap_openstack_nfs/>`__
   (login is required).

.. tip::

   For more information on these options and other deployment and operational
   scenarios, visit the `NetApp OpenStack website
   <http://netapp.io/openstack/>`_.

NetApp-supported extra specs for clustered Data ONTAP
-----------------------------------------------------

Extra specs enable vendors to specify extra filter criteria.
The Block Storage scheduler uses the specs when the scheduler determines
which volume node should fulfill a volume provisioning request.
When you use the NetApp unified driver with a clustered Data ONTAP
storage system, you can leverage extra specs with Block Storage
volume types to ensure that Block Storage volumes are created
on storage back ends that have certain properties.
An example of this is when you configure QoS, mirroring,
or compression for a storage back end.

Extra specs are associated with Block Storage volume types.
When users request volumes of a particular volume type, the volumes
are created on storage back ends that meet the list of requirements.
An example of this is the back ends that have the available space or
extra specs. Use the specs in the following table to configure volumes.
Define Block Storage volume types by using the :command:`openstack volume
type set` command.

.. include:: ../../tables/manual/cinder-netapp_cdot_extraspecs.inc

NetApp E-Series storage family
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The NetApp E-Series storage family represents a configuration group which
provides OpenStack compute instances access to E-Series storage systems. At
present it can be configured in Block Storage to work with the iSCSI
storage protocol.

NetApp iSCSI configuration for E-Series
---------------------------------------

The NetApp iSCSI configuration for E-Series is an interface from OpenStack to
E-Series storage systems. It provisions and manages the SAN block storage
entity, which is a NetApp LUN which can be accessed using the iSCSI protocol.

The iSCSI configuration for E-Series is an interface from Block
Storage to the E-Series proxy instance and as such requires the deployment of
the proxy instance in order to achieve the desired functionality. The driver
uses REST APIs to interact with the E-Series proxy instance, which in turn
interacts directly with the E-Series controllers.

The use of multipath and DM-MP are required when using the Block
Storage driver for E-Series. In order for Block Storage and OpenStack
Compute to take advantage of multiple paths, the following configuration
options must be correctly configured:

- The ``use_multipath_for_image_xfer`` option should be set to ``True`` in the
  ``cinder.conf`` file within the driver-specific stanza (for example,
  ``[myDriver]``).

- The ``iscsi_use_multipath`` option should be set to ``True`` in the
  ``nova.conf`` file within the ``[libvirt]`` stanza.

**Configuration options**

Configure the volume driver, storage family, and storage protocol to the
NetApp unified driver, E-Series, and iSCSI respectively by setting the
``volume_driver``, ``netapp_storage_family`` and
``netapp_storage_protocol`` options in the ``cinder.conf`` file as follows:

.. code-block:: ini

   volume_driver = cinder.volume.drivers.netapp.common.NetAppDriver
   netapp_storage_family = eseries
   netapp_storage_protocol = iscsi
   netapp_server_hostname = myhostname
   netapp_server_port = 80
   netapp_login = username
   netapp_password = password
   netapp_controller_ips = 1.2.3.4,5.6.7.8
   netapp_sa_password = arrayPassword
   netapp_storage_pools = pool1,pool2
   use_multipath_for_image_xfer = True

.. note::

   To use the E-Series driver, you must override the default value of
   ``netapp_storage_family`` with ``eseries``.

   To use the iSCSI protocol, you must override the default value of
   ``netapp_storage_protocol`` with ``iscsi``.

.. include:: ../../tables/cinder-netapp_eseries_iscsi.inc

.. tip::

   For more information on these options and other deployment and
   operational scenarios, visit the `NetApp OpenStack website
   <http://netapp.io/openstack/>`_.

NetApp-supported extra specs for E-Series
-----------------------------------------

Extra specs enable vendors to specify extra filter criteria.
The Block Storage scheduler uses the specs when the scheduler determines
which volume node should fulfill a volume provisioning request.
When you use the NetApp unified driver with an E-Series storage system,
you can leverage extra specs with Block Storage volume types to ensure
that Block Storage volumes are created on storage back ends that have
certain properties. An example of this is when you configure thin
provisioning for a storage back end.

Extra specs are associated with Block Storage volume types.
When users request volumes of a particular volume type, the volumes are
created on storage back ends that meet the list of requirements.
An example of this is the back ends that have the available space or
extra specs. Use the specs in the following table to configure volumes.
Define Block Storage volume types by using the :command:`openstack volume
type set` command.

.. list-table:: Description of extra specs options for NetApp Unified Driver with E-Series
   :header-rows: 1

   * - Extra spec
     - Type
     - Description
   * - ``netapp_thin_provisioned``
     - Boolean
     - Limit the candidate volume list to only the ones that support thin
       provisioning on the storage controller.


text:
package gitbucket.core.controller

import gitbucket.core.service.{RepositoryService, AccountService}
import gitbucket.core.admin.users.html
import gitbucket.core.util._
import gitbucket.core.util.ControlUtil._
import gitbucket.core.util.StringUtil._
import gitbucket.core.util.Implicits._
import gitbucket.core.util.Directory._
import jp.sf.amateras.scalatra.forms._
import org.scalatra.i18n.Messages
import org.apache.commons.io.FileUtils

class UserManagementController extends UserManagementControllerBase
  with AccountService with RepositoryService with AdminAuthenticator

trait UserManagementControllerBase extends AccountManagementControllerBase {
  self: AccountService with RepositoryService with AdminAuthenticator =>

  case class NewUserForm(userName: String, password: String, fullName: String,
                         mailAddress: String, isAdmin: Boolean,
                         url: Option[String], fileId: Option[String])

  case class EditUserForm(userName: String, password: Option[String], fullName: String,
                          mailAddress: String, isAdmin: Boolean, url: Option[String],
                          fileId: Option[String], clearImage: Boolean, isRemoved: Boolean)

  case class NewGroupForm(groupName: String, url: Option[String], fileId: Option[String],
                          members: String)

  case class EditGroupForm(groupName: String, url: Option[String], fileId: Option[String],
                           members: String, clearImage: Boolean, isRemoved: Boolean)

  val newUserForm = mapping(
    "userName"    -> trim(label("Username"     ,text(required, maxlength(100), identifier, uniqueUserName))),
    "password"    -> trim(label("Password"     ,text(required, maxlength(20)))),
    "fullName"    -> trim(label("Full Name"    ,text(required, maxlength(100)))),
    "mailAddress" -> trim(label("Mail Address" ,text(required, maxlength(100), uniqueMailAddress()))),
    "isAdmin"     -> trim(label("User Type"    ,boolean())),
    "url"         -> trim(label("URL"          ,optional(text(maxlength(200))))),
    "fileId"      -> trim(label("File ID"      ,optional(text())))
  )(NewUserForm.apply)

  val editUserForm = mapping(
    "userName"    -> trim(label("Username"     ,text(required, maxlength(100), identifier))),
    "password"    -> trim(label("Password"     ,optional(text(maxlength(20))))),
    "fullName"    -> trim(label("Full Name"    ,text(required, maxlength(100)))),
    "mailAddress" -> trim(label("Mail Address" ,text(required, maxlength(100), uniqueMailAddress("userName")))),
    "isAdmin"     -> trim(label("User Type"    ,boolean())),
    "url"         -> trim(label("URL"          ,optional(text(maxlength(200))))),
    "fileId"      -> trim(label("File ID"      ,optional(text()))),
    "clearImage"  -> trim(label("Clear image"  ,boolean())),
    "removed"     -> trim(label("Disable"      ,boolean(disableByNotYourself("userName"))))
  )(EditUserForm.apply)

  val newGroupForm = mapping(
    "groupName" -> trim(label("Group name" ,text(required, maxlength(100), identifier, uniqueUserName))),
    "url"       -> trim(label("URL"        ,optional(text(maxlength(200))))),
    "fileId"    -> trim(label("File ID"    ,optional(text()))),
    "members"   -> trim(label("Members"    ,text(required, members)))
  )(NewGroupForm.apply)

  val editGroupForm = mapping(
    "groupName"  -> trim(label("Group name"  ,text(required, maxlength(100), identifier))),
    "url"        -> trim(label("URL"         ,optional(text(maxlength(200))))),
    "fileId"     -> trim(label("File ID"     ,optional(text()))),
    "members"    -> trim(label("Members"     ,text(required, members))),
    "clearImage" -> trim(label("Clear image" ,boolean())),
    "removed"    -> trim(label("Disable"     ,boolean()))
  )(EditGroupForm.apply)

  get("/admin/users")(adminOnly {
    val includeRemoved = params.get("includeRemoved").map(_.toBoolean).getOrElse(false)
    val users          = getAllUsers(includeRemoved)
    val members        = users.collect { case account if(account.isGroupAccount) =>
      account.userName -> getGroupMembers(account.userName).map(_.userName)
    }.toMap

    html.list(users, members, includeRemoved)
  })

  get("/admin/users/_newuser")(adminOnly {
    html.user(None)
  })

  post("/admin/users/_newuser", newUserForm)(adminOnly { form =>
    createAccount(form.userName, sha1(form.password), form.fullName, form.mailAddress, form.isAdmin, form.url)
    updateImage(form.userName, form.fileId, false)
    redirect("/admin/users")
  })

  get("/admin/users/:userName/_edituser")(adminOnly {
    val userName = params("userName")
    html.user(getAccountByUserName(userName, true))
  })

  post("/admin/users/:name/_edituser", editUserForm)(adminOnly { form =>
    val userName = params("userName")
    getAccountByUserName(userName, true).map { account =>

      if(form.isRemoved){
        // Remove repositories
//        getRepositoryNamesOfUser(userName).foreach { repositoryName =>
//          deleteRepository(userName, repositoryName)
//          FileUtils.deleteDirectory(getRepositoryDir(userName, repositoryName))
//          FileUtils.deleteDirectory(getWikiRepositoryDir(userName, repositoryName))
//          FileUtils.deleteDirectory(getTemporaryDir(userName, repositoryName))
//        }
        // Remove from GROUP_MEMBER, COLLABORATOR and REPOSITORY
        removeUserRelatedData(userName)
      }

      updateAccount(account.copy(
        password     = form.password.map(sha1).getOrElse(account.password),
        fullName     = form.fullName,
        mailAddress  = form.mailAddress,
        isAdmin      = form.isAdmin,
        url          = form.url,
        isRemoved    = form.isRemoved))

      updateImage(userName, form.fileId, form.clearImage)
      redirect("/admin/users")

    } getOrElse NotFound
  })

  get("/admin/users/_newgroup")(adminOnly {
    html.group(None, Nil)
  })

  post("/admin/users/_newgroup", newGroupForm)(adminOnly { form =>
    createGroup(form.groupName, form.url)
    updateGroupMembers(form.groupName, form.members.split(",").map {
      _.split(":") match {
        case Array(userName, isManager) => (userName, isManager.toBoolean)
      }
    }.toList)
    updateImage(form.groupName, form.fileId, false)
    redirect("/admin/users")
  })

  get("/admin/users/:groupName/_editgroup")(adminOnly {
    defining(params("groupName")){ groupName =>
      html.group(getAccountByUserName(groupName, true), getGroupMembers(groupName))
    }
  })

  post("/admin/users/:groupName/_editgroup", editGroupForm)(adminOnly { form =>
    defining(params("groupName"), form.members.split(",").map {
      _.split(":") match {
        case Array(userName, isManager) => (userName, isManager.toBoolean)
      }
    }.toList){ case (groupName, members) =>
      getAccountByUserName(groupName, true).map { account =>
        updateGroup(groupName, form.url, form.isRemoved)

        if(form.isRemoved){
          // Remove from GROUP_MEMBER
          updateGroupMembers(form.groupName, Nil)
          // Remove repositories
          getRepositoryNamesOfUser(form.groupName).foreach { repositoryName =>
            deleteRepository(groupName, repositoryName)
            FileUtils.deleteDirectory(getRepositoryDir(groupName, repositoryName))
            FileUtils.deleteDirectory(getWikiRepositoryDir(groupName, repositoryName))
            FileUtils.deleteDirectory(getTemporaryDir(groupName, repositoryName))
          }
        } else {
          // Update GROUP_MEMBER
          updateGroupMembers(form.groupName, members)
          // Update COLLABORATOR for group repositories
          getRepositoryNamesOfUser(form.groupName).foreach { repositoryName =>
            removeCollaborators(form.groupName, repositoryName)
            members.foreach { case (userName, isManager) =>
              addCollaborator(form.groupName, repositoryName, userName)
            }
          }
        }

        updateImage(form.groupName, form.fileId, form.clearImage)
        redirect("/admin/users")

      } getOrElse NotFound
    }
  })

  private def members: Constraint = new Constraint(){
    override def validate(name: String, value: String, messages: Messages): Option[String] = {
      if(value.split(",").exists {
        _.split(":") match { case Array(userName, isManager) => isManager.toBoolean }
      }) None else Some("Must select one manager at least.")
    }
  }

  protected def disableByNotYourself(paramName: String): Constraint = new Constraint() {
    override def validate(name: String, value: String, messages: Messages): Option[String] = {
      params.get(paramName).flatMap { userName =>
        if(userName == context.loginAccount.get.userName && params.get("removed") == Some("true"))
          Some("You can't disable your account yourself")
        else
          None
      }
    }
  }
}


text:
title: "Releases"
permalink: /releases/
excerpt: "Following release policy ensures releases are acts of the organization, not the release manager personally."
modified: 2017-01-14T10:05:00-05:00
categories:
  - Releases
tags:
  - Releases
  - Pragmatic
  - Charity
---

Project Management Committees (PMCs) vote on a final version of software to make the act of making a release - a formally available product to the public - as an act of the ASF as an organization (and not necessarily the individual rolling the release).

There are a number of policies and guidelines around how to make an Apache release.


text:
/* $NetBSD: t_fpu.c,v 1.2 2013/01/27 14:47:37 mbalmer Exp $ */

/*
 * Copyright (c) 2008 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__COPYRIGHT("@(#) Copyright (c) 2008\
 The NetBSD Foundation, inc. All rights reserved.");
__RCSID("$NetBSD: t_fpu.c,v 1.2 2013/01/27 14:47:37 mbalmer Exp $");

/*
 * This is adapted from part of csw/cstest of the MPD implementation by
 * the University of Arizona CS department (http://www.cs.arizona.edu/sr/)
 * which is in the public domain:
 *
 * "The MPD system is in the public domain and you may use and distribute it
 *  as you wish.  We ask that you retain credits referencing the University
 *  of Arizona and that you identify any changes you make.
 *
 *  We can't provide a warranty with MPD; it's up to you to determine its
 *  suitability and reliability for your needs.  We would like to hear of
 *  any problems you encounter but we cannot promise a timely correction."
 *
 * It was changed to use pthread_create() and sched_yield() instead of
 * the internal MPD context switching primitives by Ignatios Souvatzis
 * <is@netbsd.org>.
 */

#include <math.h>
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <atf-c.h>

#include "h_common.h"

#define N_RECURSE 10

static void recurse(void);

int recursion_depth = 0;
pthread_mutex_t recursion_depth_lock;

static void *
stir(void *p)
{
	double *q = (double *)p;
	double x = *q++;
	double y = *q++;
	double z = *q++;

	for (;;) {
		x = sin ((y = cos (x + y + .4)) - (z = cos (x + z + .6)));
		PTHREAD_REQUIRE(sched_yield());
	}
}

static double
mul3(double x, double y, double z)
{
	PTHREAD_REQUIRE(sched_yield());

	return x * y * z;
}

static void *
bar(void *p)
{
	double d;
	int rc;

	d = mul3(mul3(2., 3., 5.), mul3(7., 11., 13.), mul3(17., 19., 23.));
	ATF_REQUIRE_EQ(d, 223092870.);

	PTHREAD_REQUIRE(pthread_mutex_lock(&recursion_depth_lock));
	rc = recursion_depth++;
	PTHREAD_REQUIRE(pthread_mutex_unlock(&recursion_depth_lock));

	if (rc < N_RECURSE)
		recurse();
	else
		atf_tc_pass();

	/* NOTREACHED */
	return NULL;
}

static void
recurse(void) {
	pthread_t s2;
	pthread_create(&s2, 0, bar, 0);
	sleep(20); /* XXX must be long enough for our slowest machine */
}

ATF_TC(fpu);
ATF_TC_HEAD(fpu, tc)
{
	atf_tc_set_md_var(tc, "descr",
		"Checks that thread context switches will leave the "
		"floating point computations unharmed");
}
ATF_TC_BODY(fpu, tc)
{
	double stirseed[] = { 1.7, 3.2, 2.4 };
	pthread_t s5;

	printf("Testing threaded floating point computations...\n");

	PTHREAD_REQUIRE(pthread_mutex_init(&recursion_depth_lock, 0));

	pthread_create(&s5, 0, stir, stirseed);
	recurse();

	atf_tc_fail("exiting from main");
}

ATF_TP_ADD_TCS(tp)
{
	ATF_TP_ADD_TC(tp, fpu);

	return atf_no_error();
}


text:
package tntengine

import (
	"errors"
	"fmt"
	"time"

	"github.com/FZambia/tarantool"
	"github.com/centrifugal/centrifuge"
	"github.com/centrifugal/protocol"
	"github.com/vmihailenco/msgpack/v5"
)

// DefaultPresenceTTL is a default value for presence TTL in Tarantool.
const DefaultPresenceTTL = 60 * time.Second

// PresenceManagerConfig is a config for Tarantool-based PresenceManager.
type PresenceManagerConfig struct {
	// PresenceTTL is an interval how long to consider presence info
	// valid after receiving presence update. This allows to automatically
	// clean up unnecessary presence entries after TTL passed.
	PresenceTTL time.Duration

	// Shards is a list of Tarantool instances to shard data by channel.
	Shards []*Shard
}

// NewPresenceManager initializes Tarantool-based centrifuge.PresenceManager.
func NewPresenceManager(n *centrifuge.Node, config PresenceManagerConfig) (*PresenceManager, error) {
	if len(config.Shards) == 0 {
		return nil, errors.New("no Tarantool shards provided in configuration")
	}
	if len(config.Shards) > 1 {
		n.Log(centrifuge.NewLogEntry(centrifuge.LogLevelInfo, fmt.Sprintf("Tarantool sharding enabled: %d shards", len(config.Shards))))
	}
	e := &PresenceManager{
		node:     n,
		shards:   config.Shards,
		config:   config,
		sharding: len(config.Shards) > 1,
	}
	return e, nil
}

var _ centrifuge.PresenceManager = (*PresenceManager)(nil)

// PresenceManager uses Tarantool to implement centrifuge.PresenceManager functionality.
type PresenceManager struct {
	node     *centrifuge.Node
	sharding bool
	config   PresenceManagerConfig
	shards   []*Shard
}

type presenceRequest struct {
	Channel string
}

func (m *PresenceManager) Presence(ch string) (map[string]*centrifuge.ClientInfo, error) {
	s := consistentShard(ch, m.shards)
	result, err := s.Exec(tarantool.Call("centrifuge.presence", presenceRequest{Channel: ch}))
	if err != nil {
		return nil, err
	}
	if len(result) == 0 {
		return nil, errors.New("malformed presence result")
	}
	presenceInterfaceSlice, ok := result[0].([]interface{})
	if !ok {
		return nil, errors.New("malformed presence format: map expected")
	}
	presence := make(map[string]*centrifuge.ClientInfo, len(presenceInterfaceSlice))
	for _, v := range presenceInterfaceSlice {
		presenceRow, ok := v.([]interface{})
		if !ok {
			return nil, errors.New("malformed presence format: tuple expected")
		}
		var ci protocol.ClientInfo
		ciData, ok := presenceRow[3].(string)
		if !ok {
			return nil, errors.New("malformed presence format: data expected")
		}
		err := ci.UnmarshalVT([]byte(ciData))
		if err != nil {
			return nil, fmt.Errorf("unmarshal ClientInfo: %w", err)
		}
		presence[ci.Client] = &centrifuge.ClientInfo{
			ClientID: ci.Client,
			UserID:   ci.User,
			ConnInfo: ci.ConnInfo,
			ChanInfo: ci.ChanInfo,
		}
	}
	return presence, nil
}

type presenceStatsRequest struct {
	Channel string
}

type presenceStatsResponse struct {
	NumClients uint32
	NumUsers   uint32
}

func (m *presenceStatsResponse) DecodeMsgpack(d *msgpack.Decoder) error {
	var err error
	var l int
	if l, err = d.DecodeArrayLen(); err != nil {
		return err
	}
	if l != 2 {
		return fmt.Errorf("array len doesn't match: %d", l)
	}
	if m.NumClients, err = d.DecodeUint32(); err != nil {
		return err
	}
	if m.NumUsers, err = d.DecodeUint32(); err != nil {
		return err
	}
	return nil
}

func (m *PresenceManager) PresenceStats(ch string) (centrifuge.PresenceStats, error) {
	s := consistentShard(ch, m.shards)
	var resp presenceStatsResponse
	err := s.ExecTyped(tarantool.Call("centrifuge.presence_stats", presenceStatsRequest{Channel: ch}), &resp)
	if err != nil {
		return centrifuge.PresenceStats{}, err
	}
	return centrifuge.PresenceStats{NumClients: int(resp.NumClients), NumUsers: int(resp.NumUsers)}, err
}

type addPresenceRequest struct {
	Channel  string
	TTL      int
	ClientID string
	UserID   string
	Data     string
}

func (m *PresenceManager) AddPresence(ch string, clientID string, info *centrifuge.ClientInfo) error {
	s := consistentShard(ch, m.shards)
	ttl := DefaultPresenceTTL
	if m.config.PresenceTTL > 0 {
		ttl = m.config.PresenceTTL
	}
	_, err := s.Exec(tarantool.Call("centrifuge.add_presence", addPresenceRequest{
		Channel:  ch,
		TTL:      int(ttl.Seconds()),
		ClientID: clientID,
		UserID:   info.UserID,
		Data:     m.clientInfoString(info),
	}))
	return err
}

func (m *PresenceManager) clientInfoString(clientInfo *centrifuge.ClientInfo) string {
	var info string
	if clientInfo != nil {
		byteMessage, err := infoToProto(clientInfo).MarshalVT()
		if err != nil {
			return info
		}
		info = string(byteMessage)
	}
	return info
}

type removePresenceRequest struct {
	Channel  string
	ClientID string
}

func (m *PresenceManager) RemovePresence(ch string, clientID string) error {
	s := consistentShard(ch, m.shards)
	_, err := s.Exec(tarantool.Call("centrifuge.remove_presence", removePresenceRequest{Channel: ch, ClientID: clientID}))
	return err
}