text:
namespace NServiceBus.AcceptanceTests.Versioning
{
    using System.Threading.Tasks;
    using AcceptanceTesting;
    using EndpointTemplates;
    using Features;
    using NUnit.Framework;
    using Routing;

    public class When_multiple_versions_of_a_message_is_published : NServiceBusAcceptanceTest
    {
        [Test]
        public async Task Should_deliver_is_to_both_v1_and_vX_subscribers()
        {
            var context = await Scenario.Define<Context>()
                .WithEndpoint<V2Publisher>(b =>
                    b.When(c => c.V1Subscribed && c.V2Subscribed, (session, c) =>
                    {
                        return session.Publish<V2Event>(e =>
                        {
                            e.SomeData = 1;
                            e.MoreInfo = "dasd";
                        });
                    }))
                .WithEndpoint<V1Subscriber>(b => b.When(async (session, c) =>
                {
                    await session.Subscribe<V1Event>();
                    if (c.HasNativePubSubSupport)
                    {
                        c.V1Subscribed = true;
                    }
                }))
                .WithEndpoint<V2Subscriber>(b => b.When(async (session, c) =>
                {
                    await session.Subscribe<V2Event>();
                    if (c.HasNativePubSubSupport)
                    {
                        c.V2Subscribed = true;
                    }
                }))
                .Done(c => c.V1SubscriberGotTheMessage && c.V2SubscriberGotTheMessage)
                .Run();

            Assert.True(context.V1SubscriberGotTheMessage);
            Assert.True(context.V2SubscriberGotTheMessage);
        }

        public class Context : ScenarioContext
        {
            public bool V1SubscriberGotTheMessage { get; set; }

            public bool V2SubscriberGotTheMessage { get; set; }

            public bool V1Subscribed { get; set; }

            public bool V2Subscribed { get; set; }
        }

        public class V2Publisher : EndpointConfigurationBuilder
        {
            public V2Publisher()
            {
                EndpointSetup<DefaultPublisher>(b => b.OnEndpointSubscribed<Context>((s, context) =>
                {
                    if (s.SubscriberReturnAddress.Contains("V1Subscriber"))
                    {
                        context.V1Subscribed = true;
                    }

                    if (s.SubscriberReturnAddress.Contains("V2Subscriber"))
                    {
                        context.V2Subscribed = true;
                    }
                }));
            }
        }

        public class V1Subscriber : EndpointConfigurationBuilder
        {
            public V1Subscriber()
            {
                EndpointSetup<DefaultServer>(b => b.DisableFeature<AutoSubscribe>())
                    .ExcludeType<V2Event>()
                    .AddMapping<V1Event>(typeof(V2Publisher));
            }

            class V1Handler : IHandleMessages<V1Event>
            {
                public Context Context { get; set; }

                public Task Handle(V1Event message, IMessageHandlerContext context)
                {
                    Context.V1SubscriberGotTheMessage = true;
                    return Task.FromResult(0);
                }
            }
        }

        public class V2Subscriber : EndpointConfigurationBuilder
        {
            public V2Subscriber()
            {
                EndpointSetup<DefaultServer>(b => b.DisableFeature<AutoSubscribe>())
                    .AddMapping<V2Event>(typeof(V2Publisher));
            }

            class V2Handler : IHandleMessages<V2Event>
            {
                public Context Context { get; set; }

                public Task Handle(V2Event message, IMessageHandlerContext context)
                {
                    Context.V2SubscriberGotTheMessage = true;
                    return Task.FromResult(0);
                }
            }
        }

        public class V1Event : IEvent
        {
            public int SomeData { get; set; }
        }

        public class V2Event : V1Event
        {
            public string MoreInfo { get; set; }
        }
    }
}


text:
/*globals define*/
define([
  'backbone',
  'models/note'
], function( Backbone, Note ) {
  'use strict';

  var Tuning = Backbone.Collection.extend({
    model: Note,

    setTuning: function( tuning ) {
      var difference = tuning.length - this.length;

      // Remove/add Note models to match number of notes in new tuning.
      if ( difference > 0 ) {
        while ( difference-- ) {
          this.add( new Note() );
        }
      } else if ( difference < 0 ) {
        while ( difference++ ) {
          this.first().destroy();
        }
      }

      var that = this,
          model;

      // Set tuning to new tuning.
      tuning.each(function( note, index ) {
        model = that.at( index );
        model.set({
          note: note.get( 'note' ),
          octave: note.get( 'octave' )
        });
      });
    },

    getNoteNames: function( separator ) {
      var notes = '';

      var that = this;
      this.each(function( note, index ) {
        notes += note.getNoteName();
        if ( separator && index < that.length - 1 ) {
          notes += separator;
        }
      });

      return notes;
    }
  });

  return Tuning;
});

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include "../../Utils/Common/UtilBasic.h"
#include "../../Rendering/RenderData/RenderDataBase.h"
#include "../../Rendering/RenderingAdapter.h"
#include "../../Logic/LogicData.h"
#include "Actor.h"

namespace IceDogGameplay
{
	class Level
	{
	public:
		Level();
		~Level();

		/* init the level */
		void Init();

		/* close the level */
		void Close();

		/* register the render data */
		void RegistRenderData(std::shared_ptr<IceDogRendering::RenderDataBase> rd);
		void UnRegistRenderData(std::shared_ptr<IceDogRendering::RenderDataBase> rd);

		/* register the logic data */
		void RegistLogicData(std::shared_ptr<IceDogLogic::LogicData> ld);
		void UnRegistLogicData(std::shared_ptr<IceDogLogic::LogicData> ld);

		/* register the actor */
		void RegistActor(std::shared_ptr<IceDogGameplay::Actor> ac);
		void UnRegistActor(std::shared_ptr<IceDogGameplay::Actor> ac);
		void UnRegistActorByAddress(IceDogGameplay::Actor* ac);

		/* register the light data */
		void RegistLightData(std::shared_ptr<class IceDogRendering::LightBase> ld);
		void UnRegistLightData(std::shared_ptr<class IceDogRendering::LightBase> ld);

	private:
		// the render data that this level hold
		std::vector<std::shared_ptr<IceDogRendering::RenderDataBase>> r_renderDatas;
		// the logic data that this level hold
		std::vector<std::shared_ptr<IceDogLogic::LogicData>> r_logicDatas;
		// the actor that this level hold
		std::vector<std::shared_ptr<IceDogGameplay::Actor>> r_actors;
		// the light data this level hold
		std::vector<std::shared_ptr<class IceDogRendering::LightBase>> r_lightDatas;
	};
}


text:
var DiffSequence = require('diff-sequence');

var LocalCollection = require('./collection');

// ordered: bool.
// old_results and new_results: collections of documents.
//    if ordered, they are arrays.
//    if unordered, they are IdMaps
LocalCollection._diffQueryChanges = function (ordered, oldResults, newResults, observer, options) {
  return DiffSequence.diffQueryChanges(ordered, oldResults, newResults, observer, options);
};

LocalCollection._diffQueryUnorderedChanges = function (oldResults, newResults, observer, options) {
  return DiffSequence.diffQueryUnorderedChanges(oldResults, newResults, observer, options);
};

LocalCollection._diffQueryOrderedChanges = function (oldResults, newResults, observer, options) {
  return DiffSequence.diffQueryOrderedChanges(oldResults, newResults, observer, options);
};

LocalCollection._diffObjects = function (left, right, callbacks) {
  return DiffSequence.diffObjects(left, right, callbacks);
};


text:
package org.wso2.carbon.apimgt.gateway;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Logger manager to invoke the internal API and retrieve per API logging details.
 */
public class APILoggerManager {
    private static final Log log = LogFactory.getLog(APILoggerManager.class);
    private static final Map<String, String> logProperties = new HashMap<>();
    private static final APILoggerManager apiLoggerManager = new APILoggerManager();
    private final EventHubConfigurationDto eventHubConfigurationDto;
    public static final int RETRIEVAL_RETRIES = 15;
    public static final int RETRIEVAL_TIMEOUT_IN_SECONDS = 15;
    public static final String UTF8 = "UTF-8";

    public void initializeAPILoggerList() {
        try {
            String responseString = invokeService("/api-logging-configs",
                    MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
            JSONObject responseJson = new JSONObject(responseString);
            JSONArray apiLogArray = responseJson.getJSONArray("apis");
            for (int i = 0; i < apiLogArray.length(); i++) {
                JSONObject apiLoggerObject = apiLogArray.getJSONObject(i);
                logProperties.put(apiLoggerObject.getString("context"), apiLoggerObject.getString("logLevel"));
            }
            if (log.isDebugEnabled()) {
                log.debug("Response : " + responseString);
            }
        } catch (IOException | APIManagementException ex) {
            log.error("Error while calling internal service API", ex);
        }
    }

    public void updateLoggerMap(String apiContext, String logLevel) {
        logProperties.put(apiContext, logLevel);
    }

    public Map<String, String> getPerAPILoggerList() {
        return logProperties;
    }

    public APILoggerManager() {
        this.eventHubConfigurationDto = ServiceReferenceHolder.getInstance().getApiManagerConfigurationService()
                .getAPIManagerConfiguration().getEventHubConfigurationDto();
    }

    public static APILoggerManager getInstance() {
        return apiLoggerManager;
    }

    private byte[] getServiceCredentials(EventHubConfigurationDto eventHubConfigurationDto) {

        String username = eventHubConfigurationDto.getUsername();
        String pw = eventHubConfigurationDto.getPassword();
        return Base64.encodeBase64((username + APIConstants.DELEM_COLON + pw).getBytes
                (StandardCharsets.UTF_8));
    }
    private String invokeService(String path, String tenantDomain) throws IOException, APIManagementException {

        String serviceURLStr = eventHubConfigurationDto.getServiceUrl().concat(APIConstants.INTERNAL_WEB_APP_EP);
        HttpGet method = new HttpGet(serviceURLStr + path);

        URL serviceURL = new URL(serviceURLStr + path);
        byte[] credentials = getServiceCredentials(eventHubConfigurationDto);
        int servicePort = serviceURL.getPort();
        String serviceProtocol = serviceURL.getProtocol();
        method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC
                + new String(credentials, StandardCharsets.UTF_8));
        if (tenantDomain != null) {
            method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
        }
        HttpClient httpClient = APIUtil.getHttpClient(servicePort, serviceProtocol);

        HttpResponse httpResponse = null;
        int retryCount = 0;
        boolean retry;
        do {
            try {
                httpResponse = httpClient.execute(method);
                retry = false;
            } catch (IOException ex) {
                retryCount++;
                if (retryCount < RETRIEVAL_RETRIES) {
                    retry = true;
                    log.warn("Failed retrieving " + path + " from remote endpoint: " + ex.getMessage()
                             + ". Retrying after " + RETRIEVAL_TIMEOUT_IN_SECONDS +
                             " seconds.");
                    try {
                        Thread.sleep(RETRIEVAL_TIMEOUT_IN_SECONDS * 1000L);
                    } catch (InterruptedException e) {
                        // Ignore
                    }
                } else {
                    throw new APIManagementException("Error while calling internal service", ex);
                }
            }
        } while (retry);
        if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
            log.error("Could not retrieve subscriptions for tenantDomain : " + tenantDomain);
            throw new APIManagementException("Error while retrieving subscription from " + path);
        }
        return EntityUtils.toString(httpResponse.getEntity(), UTF8);
    }
}


text:
'use strict';

import CategoryActions from '../actions/CategoryActionCreators';
import ServerActions from '../actions/ServerActionCreators';
import SectionActions from '../actions/SectionActionCreators';
import Reflux from 'reflux';
import _ from 'lodash';

let category;
let _categories = [];

const CategoryStore = Reflux.createStore({
  listenables: [CategoryActions, SectionActions, ServerActions],

  onReceiveAllCategories(rawCategories) {
    _categories = rawCategories;
    this.trigger();
  },

  onReceiveCreatedCategory(rawCategory) {
    _categories.push(rawCategory);
    this.trigger();
  },

  onReceiveUpdatedCategory(rawCategory) {
    _.each(_categories, (category, index) => {
      if (category.id === rawCategory.id) {
        _categories[index].title = rawCategory.title;
      }
    });
    this.trigger();
  },

  onReceiveUpdatedCategories(rawCategories) {
    _categories = rawCategories;
    this.trigger();
  },

  onReceiveDeletedCategory(categoryId) {
    _.remove(_categories, { id: categoryId });
    this.trigger();
  },

  onReceiveCreatedSection(categoryId, section) {
    category = _.find(_categories, { id: categoryId });
    category.sections.push(section);
    this.trigger();
  },

  onReceiveDeletedSection(categoryId, sectionId) {
    category = _.find(_categories, { id: categoryId });
    _.remove(category.sections, { id: sectionId });
    this.trigger();
  },

  onReceiveUpdatedSection(rawSection) {
    _.each(_categories, (category) => {
      _.find(category.sections, (section, index) => {
        if (section.id === rawSection.id) {
          category.sections[index] = rawSection;
        }
      });
    });
    this.trigger();
  },

  onReceiveUpdatedSections(categoryId, rawSections) {
    category = _.find(_categories, { id: categoryId });
    category.sections = rawSections;
    this.trigger();
  },

  getCategories() {
    return _categories;
  },

  getAll() {
    return _categories;
  }
});

export default CategoryStore;


text:
Propeller Web Developer Test
==========================

To complete this test, you will need to write and deploy a small API web service, and provide us the URL to your solution. Note: as this is also an exercise in set-up and deployment, please don't solve this by adding an endpoint to an existing app or service. Your service should be standalone and deployed at a root path e.g. with Heroku on http://myservice.herokuapp.com/.

You can take as long as you need to submit your solution, but you should be able to finish it in 4 hours.

## The Test

We'll post some JSON data to the URL you provide. You'll need to filter that data and return a few fields.

## Details

View the request payload json sample provided; from the list of property data in the request payload, return a property record array for items having workflow completed (workflow: completed) for the type 'htv'.

* [request sample](hometrack-sample-request.json)
* [response sample](hometrack-sample-response.json)

The returned JSON should have a response key with an array of properties. Each element should have the followig fields from the request:

* Attribute 1: concataddress – a concatenation of the address object fields into a single string
* Attribute 2: lat
* Attribute 3: lon
* Attribute 2: type
* Attribute 3: workflow

### Error Handling

If we send invalid JSON, you'll need to return a JSON response with HTTP status 400 Bad Request, and with a `error` key containing the string could not decode request. For example:

```javascript
{
    "error": "Could not decode request: JSON parsing failed"
}
```

### Results

Send us the link to your solution and a link to the code in your github account.

### Useful links

[Heroku](https://www.heroku.com/) - A platform-as-a-service designed for developers, free for small apps.

[github](https://github.com/) - Source code hosting, free repositories for small teams.


text:
class Solution:
    def selfDividingNumbers(self, left: int, right: int) -> List[int]:
        def isSelfDividing(num):
            x = num
            while num:
                num, d = divmod(num, 10)
                if d == 0 or x % d:
                    return False
            return True
        return [num for num in range(left, right + 1) if isSelfDividing(num)]


text:
<?php
// extract the route
$route = $this->route;

// remove it from the parameter list
unset( $this->route );

$base_url = ( function_exists('filter_var') ) ? filter_var( $_SERVER['SCRIPT_NAME'] ) : $_SERVER['SCRIPT_NAME'];

// build the url and return it.
return $this->instance(
                        array( 'url'=> $base_url . '/' . preg_replace('/[^a-z0-9\/\_]/i', '', $route),
                               'parameters'=>$this,
                        )
            )->dispatch( __DIR__ . '/url.php');

// EOF


text:
package com.markwesterlund.ubo.adapters;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.markwesterlund.ubo.R;
import com.markwesterlund.ubo.utils.MD5Util;
import com.parse.ParseUser;
import com.squareup.picasso.Picasso;

public class UserAdapter extends ArrayAdapter<ParseUser> {

	protected Context mContext;
	protected List<ParseUser> mUser;

	public UserAdapter(Context context, List<ParseUser> user){
		super(context, R.layout.message_item, user);

		mContext = context;
		mUser = user;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder holder;

		if(convertView == null) {
			convertView = LayoutInflater.from(mContext).inflate(R.layout.user_item, null);
			holder = new ViewHolder();
			holder.userImageView = (ImageView)convertView.findViewById(R.id.userImageView);
			holder.nameLabel = (TextView)convertView.findViewById(R.id.nameLabel);
			holder.checkImageView = (ImageView)convertView.findViewById(R.id.checkImageView);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder)convertView.getTag();
		}

		ParseUser user = mUser.get(position);
		String email =user.getEmail().toLowerCase();

		if(email.equals("")){
			holder.userImageView.setImageResource(R.drawable.avatar_empty);
		} else {
			String hash = MD5Util.md5Hex(email);
			String gravatarUrl = "http://www.gravatar.com/avatar/" + hash + "?s=204&d=404";

			Log.d("Test", gravatarUrl);

			Picasso.with(mContext)
				.load(gravatarUrl)
				.placeholder(R.drawable.avatar_empty)
				.into(holder.userImageView);

		}

		holder.nameLabel.setText(user.getUsername());

		GridView gridView = (GridView)parent;
		if(gridView.isItemChecked(position)){
			holder.checkImageView.setVisibility(View.VISIBLE);
		} else {
			holder.checkImageView.setVisibility(View.INVISIBLE);
		}

		return convertView;
	}

	private static class ViewHolder{
		ImageView userImageView;
		ImageView checkImageView;
		TextView nameLabel;

	}

	public void refill(List<ParseUser> users) {
		mUser.clear();
		mUser.addAll(users);
		notifyDataSetChanged();
	}
}


text:
class PostsController < ApplicationController
  respond_to :html

  before_filter :authenticated, except: :index
  before_filter :authenticate_admin, except: :index

  expose(:post)
  expose(:posts)

  def create
    post.user = current_user
    post.save
    respond_with(post)
  end

  def update
    post.save
    respond_with(post)
  end

  def destroy
    post.destroy
    respond_with(post)
  end
end


text:
/* code-generation options: */

typedef enum
{

  /* Transfer control to an instructions semantic code using the the
     standard call/return mechanism */

  generate_calls,

  /* Transfer control to an instructions semantic code using
     (computed) goto's instead of the more conventional call/return
     mechanism */

  generate_jumps,

}
igen_code;

typedef enum
{
  nia_is_cia_plus_one,
  nia_is_void,
  nia_is_invalid,
}
igen_nia;

typedef struct _igen_gen_options igen_gen_options;
struct _igen_gen_options
{
  int direct_access;
  int semantic_icache;
  int insn_in_icache;
  int conditional_issue;
  int slot_verification;
  int delayed_branch;

  /* If zeroing a register, which one? */
  int zero_reg;
  int zero_reg_nr;

  /* should multiple simulators be generated? */
  int multi_sim;

  /* name of the default multi-sim model */
  char *default_model;

  /* should the simulator support multi word instructions and if so,
     what is the max nr of words. */
  int multi_word;

  /* SMP?  Should the generated code include SMP support (>0) and if
     so, for how many processors? */
  int smp;

  /* how should the next instruction address be computed? */
  igen_nia nia;

  /* nr of instructions in the decoded instruction cache */
  int icache;
  int icache_size;

  /* see above */
  igen_code code;
};

typedef struct _igen_trace_options igen_trace_options;
struct _igen_trace_options
{
  int rule_selection;
  int rule_rejection;
  int insn_insertion;
  int insn_expansion;
  int entries;
  int combine;
};

typedef struct _igen_name
{
  char *u;
  char *l;
}
igen_name;
typedef struct _igen_module
{
  igen_name prefix;
  igen_name suffix;
}
igen_module;

typedef struct _igen_module_options
{
  igen_module global;
  igen_module engine;
  igen_module icache;
  igen_module idecode;
  igen_module itable;
  igen_module semantics;
  igen_module support;
}
igen_module_options;

typedef struct _igen_decode_options igen_decode_options;
struct _igen_decode_options
{

  /* Combine tables?  Should the generator make a second pass through
     each generated table looking for any sub-entries that contain the
     same instructions.  Those entries being merged into a single
     table */
  int combine;

  /* Instruction expansion? Should the semantic code for each
     instruction, when the oportunity arrises, be expanded according
     to the variable opcode files that the instruction decode process
     renders constant */
  int duplicate;

  /* Treat reserved fields as constant (zero) instead of ignoring
     their value when determining decode tables */
  int zero_reserved;

  /* Convert any padded switch rules into goto_switch */
  int switch_as_goto;

  /* Force all tables to be generated with this lookup mechanism */
  char *overriding_gen;
};

typedef struct _igen_warn_options igen_warn_options;
struct _igen_warn_options
{

  /* Issue warning about discarded instructions */
  int discard;

  /* Issue warning about invalid instruction widths */
  int width;

  /* Issue warning about unimplemented instructions */
  int unimplemented;

};

typedef struct _igen_options igen_options;
struct _igen_options
{

  /* What does the instruction look like - bit ordering, size, widths or
     offesets */
  int hi_bit_nr;
  int insn_bit_size;
  int insn_specifying_widths;

  /* what should global names be prefixed with? */
  igen_module_options module;

  /* See above for options and flags */
  igen_gen_options gen;

  /* See above for trace options */
  igen_trace_options trace;

  /* See above for include options */
  table_include *include;

  /* See above for decode options */
  igen_decode_options decode;

  /* Filter set to be used on the flag field of the instruction table */
  filter *flags_filter;

  /* See above for warn options */
  igen_warn_options warn;

  /* Be more picky about the input */
  error_func (*warning);

  /* Model (processor) set - like flags_filter. Used to select the
     specific ISA within a processor family. */
  filter *model_filter;

  /* Format name set */
  filter *format_name_filter;
};

extern igen_options options;

/* default options - hopefully backward compatible */
#define INIT_OPTIONS() \
do { \
  memset (&options, 0, sizeof options); \
  memset (&options.warn, -1, sizeof (options.warn)); \
  options.hi_bit_nr = 0; \
  options.insn_bit_size = default_insn_bit_size; \
  options.insn_specifying_widths = 0; \
  options.module.global.prefix.u = ""; \
  options.module.global.prefix.l = ""; \
  /* the prefixes */ \
  options.module.engine = options.module.global; \
  options.module.icache = options.module.global; \
  options.module.idecode = options.module.global; \
  options.module.itable = options.module.global; \
  options.module.semantics = options.module.global; \
  options.module.support = options.module.global; \
  /* the suffixes */ \
  options.module.engine.suffix.l = "engine"; \
  options.module.engine.suffix.u = "ENGINE"; \
  options.module.icache.suffix.l = "icache"; \
  options.module.icache.suffix.u = "ICACHE"; \
  options.module.idecode.suffix.l = "idecode"; \
  options.module.idecode.suffix.u = "IDECODE"; \
  options.module.itable.suffix.l = "itable"; \
  options.module.itable.suffix.u = "ITABLE"; \
  options.module.semantics.suffix.l = "semantics"; \
  options.module.semantics.suffix.u = "SEMANTICS"; \
  options.module.support.suffix.l = "support"; \
  options.module.support.suffix.u = "SUPPORT"; \
  /* misc stuff */ \
  options.gen.code = generate_calls; \
  options.gen.icache_size = 1024; \
  options.warning = warning; \
} while (0)


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

namespace DAL.Interface
{
    public interface IDAL
    {
        bool Insert<T>(T obj) where T : class, new();
        bool Update<T>(T obj) where T : class, new();
        void Delete(DateTime dteKey);
        bool Delete(string strKey);
        DataTable getById(string strKey);
        DataTable getById(string strKey1, string strKey2);
        string getStringById(string strKey1, string strKey2);
        void setProgram(string strProgram);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 25(1-6): 58 (1972)

#### Original name
Ceriospora prinsepiae R. Rao

### Remarks
null


text:
package cyclops.data;

import com.oath.cyclops.hkt.Higher;
import cyclops.control.Option;
import com.oath.cyclops.hkt.DataWitness.zipper;
import cyclops.data.tuple.Tuple3;
import cyclops.reactive.ReactiveSeq;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.experimental.Wither;
import cyclops.data.tuple.Tuple;
import cyclops.data.tuple.Tuple2;

import java.util.Iterator;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;

@AllArgsConstructor
@Getter
@Wither
public class Zipper<T> implements Iterable<T>,
                                    Higher<zipper,T> {

    private final ImmutableList<T> left;
    private final T point;
    private final ImmutableList<T> right;

    public static <T> Zipper<T> of(ImmutableList<T> left, T value, ImmutableList<T> right){
        return new Zipper<>(left,value,right);
    }
    public static <T> Zipper of(ReactiveSeq<T> left, T value, ReactiveSeq<T> right){
        return new Zipper<>(LazySeq.fromStream(left),value, LazySeq.fromStream(right));
    }

    public boolean isStart(){
        return left.isEmpty();
    }
    public boolean isEnd(){
        return right.isEmpty();
    }
    public <R> Zipper<R> map(Function<? super T, ? extends R> fn){
        return of(left.map(fn),fn.apply(point),right.map(fn));
    }
    public <R> Zipper<R> zip(Zipper<T> zipper, BiFunction<? super T, ? super T, ? extends R> fn){
        ImmutableList<R> newLeft = left.zip(zipper.left.stream(),fn);
        R newPoint = fn.apply(point, zipper.point);
        ImmutableList<R> newRight = right.zip(zipper.right.stream(),fn);
        return of(newLeft,newPoint,newRight);
    }

    public  Zipper<Tuple2<T,T>> zip(Zipper<T> zipper){
        return zip(zipper, Tuple::tuple);
    }

    public Zipper<T> start() {
        Option<Zipper<T>> result = Option.some(this);
        Option<Zipper<T>> next = result;
        while(next.isPresent()){
                next = result.flatMap(p->p.previous());
                if(next.isPresent())
                    result = next;

        }
        return result.orElse(this);
    }
    public Zipper<T> end() {
        Option<Zipper<T>> result = Option.some(this);
        Option<Zipper<T>> next = result;
        while(next.isPresent()){
            next = result.flatMap(p->p.next());
            if(next.isPresent())
                result = next;
        }
        return result.orElse(this);
    }
    public int index(){
        return left.size();
    }
    public Option<Zipper<T>> position(int index) {
        Zipper<T> result = this;
        while (index != result.index()) {
            if (result.index() < index && !result.isEnd()) {
                result = result.next(result);
            } else if (result.index() > index && !result.isStart()) {
                result = result.previous(result);
            } else {
                return Option.none();
            }
        }
        return Option.some(result);
    }
    public <R> Option<Zipper<T>> next(){
        return right.fold(c-> Option.some(new Zipper(left.append(point), c.head(), c.tail())), nil-> Option.none());
    }
    public <R> Zipper<T> next(Zipper<T> alt){
        return next().orElse(alt);
    }
    public <R> Zipper<T> previous(Zipper<T> alt){
        return previous().orElse(alt);
    }
    public Zipper<T> cycleNext() {
        return left.fold(cons->right.fold(c->next().orElse(this), nil->{

            return of(LazySeq.empty(),cons.head(),cons.tail().append(point));
        }),nil->this);

    }
    public Zipper<T> cyclePrevious() {
        return right.fold(cons->left.fold(c->previous().orElse(this), nil->{
            ImmutableList.Some<T> reversed = cons.reverse();
            return of(reversed.tail().reverse().prepend(point),reversed.head(), LazySeq.empty());
        }),nil->this);
    }
    public <R> Option<Zipper<T>> previous(){
        return left.fold(c-> Option.some(new Zipper(c.take(c.size()-1),c.last(null) ,right.prepend(point))), nil-> Option.none());
    }

    public Zipper<T> left(T value){
        return new Zipper<>(left,value,right.prepend(point));
    }
    public Zipper<T> right(T value){
        return new Zipper<>(left.append(point),value,right);
    }
    public Zipper<T> deleteAllLeftAndRight() {
        return new Zipper<>(LazySeq.empty(), point, LazySeq.empty());
    }
    public Option<Zipper<T>> deleteLeft() {

        return left.fold(c->right.fold(c2-> Option.some(of(c.dropRight(1),c.last(null),right)), n-> Option.some(of(c.dropRight(1),c.last(null),right))),
                n->right.fold(c-> Option.some(of(left,c.head(),c.tail())), n2-> Option.none()));
    }
    public Option<Zipper<T>> deleteRight() {

        return right.fold(c->left.fold(c2-> Option.some(of(left,c.head(),c.tail())), n-> Option.some(of(left,c.head(),c.tail()))),
                n->left.fold(c-> Option.some(of(c.tail(),c.head(),right)), n2-> Option.none()));
    }

    public Zipper<T> filterLeft(Predicate<? super T> predicate) {
        return of(left.filter(predicate),point,right);
    }

    public Zipper<T> filterRight(Predicate<? super T> predicate) {
        return of(left,point,right.filter(predicate));
    }

    public Tuple3<ImmutableList<T>,T, ImmutableList<T>> split() {
        return Tuple.tuple(left,point, right);
    }
    public ImmutableList<T> list(){
        return right.prepend(point).prependAll(left);
    }

    public ReactiveSeq<T> stream(){
        return left.stream().append(point).appendStream(right.stream());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Zipper<?> zipper = (Zipper<?>) o;

        return Objects.equals(left, zipper.left) &&
                Objects.equals(point, zipper.point) &&
                Objects.equals(right, zipper.right);
    }

    @Override
    public int hashCode() {
        return Objects.hash(left, point, right);
    }

    @Override
    public String toString() {
        String l = left.stream().join(", ","[","");
        String p = ",>>" + point.toString() + "<<";

        String r = right.stream().join(", ",",","]");
       return l + p +r ;
    }

    @Override
    public Iterator<T> iterator() {
        return stream().iterator();
    }
}


text:
#include "instruction_set_features_arm.h"

#if defined(HAVE_ANDROID_OS) && defined(__arm__)
#include <sys/auxv.h>
#include <asm/hwcap.h>
#endif

#include "signal.h"
#include <fstream>

#include "base/stringprintf.h"
#include "utils.h"  // For Trim.

#if defined(__arm__)
extern "C" bool artCheckForArmSdivInstruction();
#endif

namespace art {

const ArmInstructionSetFeatures* ArmInstructionSetFeatures::FromVariant(
    const std::string& variant, std::string* error_msg) {
  // Assume all ARM processors are SMP.
  // TODO: set the SMP support based on variant.
  const bool smp = true;

  // Look for variants that have divide support.
  static const char* arm_variants_with_div[] = {
          "cortex-a7", "cortex-a12", "cortex-a15", "cortex-a17", "cortex-a53", "cortex-a57",
          "cortex-m3", "cortex-m4", "cortex-r4", "cortex-r5",
          "cyclone", "denver", "krait", "swift"};

  bool has_div = FindVariantInArray(arm_variants_with_div, arraysize(arm_variants_with_div),
                                    variant);

  // Look for variants that have LPAE support.
  static const char* arm_variants_with_lpae[] = {
      "cortex-a7", "cortex-a15", "krait", "denver"
  };
  bool has_lpae = FindVariantInArray(arm_variants_with_lpae, arraysize(arm_variants_with_lpae),
                                     variant);

  if (has_div == false && has_lpae == false) {
    // Avoid unsupported variants.
    static const char* unsupported_arm_variants[] = {
        // ARM processors that aren't ARMv7 compatible aren't supported.
        "arm2", "arm250", "arm3", "arm6", "arm60", "arm600", "arm610", "arm620",
        "cortex-m0", "cortex-m0plus", "cortex-m1",
        "fa526", "fa626", "fa606te", "fa626te", "fmp626", "fa726te",
        "iwmmxt", "iwmmxt2",
        "strongarm", "strongarm110", "strongarm1100", "strongarm1110",
        "xscale"
    };
    if (FindVariantInArray(unsupported_arm_variants, arraysize(unsupported_arm_variants),
                           variant)) {
      *error_msg = StringPrintf("Attempt to use unsupported ARM variant: %s", variant.c_str());
      return nullptr;
    }
    // Warn if the variant is unknown.
    // TODO: some of the variants below may have feature support, but that support is currently
    //       unknown so we'll choose conservative (sub-optimal) defaults without warning.
    // TODO: some of the architectures may not support all features required by ART and should be
    //       moved to unsupported_arm_variants[] above.
    static const char* arm_variants_without_known_features[] = {
        "default",
        "arm7", "arm7m", "arm7d", "arm7dm", "arm7di", "arm7dmi", "arm70", "arm700", "arm700i",
        "arm710", "arm710c", "arm7100", "arm720", "arm7500", "arm7500fe", "arm7tdmi", "arm7tdmi-s",
        "arm710t", "arm720t", "arm740t",
        "arm8", "arm810",
        "arm9", "arm9e", "arm920", "arm920t", "arm922t", "arm946e-s", "arm966e-s", "arm968e-s",
        "arm926ej-s", "arm940t", "arm9tdmi",
        "arm10tdmi", "arm1020t", "arm1026ej-s", "arm10e", "arm1020e", "arm1022e",
        "arm1136j-s", "arm1136jf-s",
        "arm1156t2-s", "arm1156t2f-s", "arm1176jz-s", "arm1176jzf-s",
        "cortex-a5", "cortex-a8", "cortex-a9", "cortex-a9-mp", "cortex-r4f",
        "marvell-pj4", "mpcore", "mpcorenovfp"
    };
    if (!FindVariantInArray(arm_variants_without_known_features,
                            arraysize(arm_variants_without_known_features),
                            variant)) {
      LOG(WARNING) << "Unknown instruction set features for ARM CPU variant (" << variant
          << ") using conservative defaults";
    }
  }
  return new ArmInstructionSetFeatures(smp, has_div, has_lpae);
}

const ArmInstructionSetFeatures* ArmInstructionSetFeatures::FromBitmap(uint32_t bitmap) {
  bool smp = (bitmap & kSmpBitfield) != 0;
  bool has_div = (bitmap & kDivBitfield) != 0;
  bool has_atomic_ldrd_strd = (bitmap & kAtomicLdrdStrdBitfield) != 0;
  return new ArmInstructionSetFeatures(smp, has_div, has_atomic_ldrd_strd);
}

const ArmInstructionSetFeatures* ArmInstructionSetFeatures::FromCppDefines() {
  const bool smp = true;
#if defined(__ARM_ARCH_EXT_IDIV__)
  const bool has_div = true;
#else
  const bool has_div = false;
#endif
#if defined(__ARM_FEATURE_LPAE)
  const bool has_lpae = true;
#else
  const bool has_lpae = false;
#endif
  return new ArmInstructionSetFeatures(smp, has_div, has_lpae);
}

const ArmInstructionSetFeatures* ArmInstructionSetFeatures::FromCpuInfo() {
  // Look in /proc/cpuinfo for features we need.  Only use this when we can guarantee that
  // the kernel puts the appropriate feature flags in here.  Sometimes it doesn't.
  bool smp = false;
  bool has_lpae = false;
  bool has_div = false;

  std::ifstream in("/proc/cpuinfo");
  if (!in.fail()) {
    while (!in.eof()) {
      std::string line;
      std::getline(in, line);
      if (!in.eof()) {
        LOG(INFO) << "cpuinfo line: " << line;
        if (line.find("Features") != std::string::npos) {
          LOG(INFO) << "found features";
          if (line.find("idivt") != std::string::npos) {
            // We always expect both ARM and Thumb divide instructions to be available or not
            // available.
            CHECK_NE(line.find("idiva"), std::string::npos);
            has_div = true;
          }
          if (line.find("lpae") != std::string::npos) {
            has_lpae = true;
          }
        } else if (line.find("processor") != std::string::npos &&
            line.find(": 1") != std::string::npos) {
          smp = true;
        }
      }
    }
    in.close();
  } else {
    LOG(ERROR) << "Failed to open /proc/cpuinfo";
  }
  return new ArmInstructionSetFeatures(smp, has_div, has_lpae);
}

const ArmInstructionSetFeatures* ArmInstructionSetFeatures::FromHwcap() {
  bool smp = sysconf(_SC_NPROCESSORS_CONF) > 1;

  bool has_div = false;
  bool has_lpae = false;

#if defined(HAVE_ANDROID_OS) && defined(__arm__)
  uint64_t hwcaps = getauxval(AT_HWCAP);
  LOG(INFO) << "hwcaps=" << hwcaps;
  if ((hwcaps & HWCAP_IDIVT) != 0) {
    // We always expect both ARM and Thumb divide instructions to be available or not
    // available.
    CHECK_NE(hwcaps & HWCAP_IDIVA, 0U);
    has_div = true;
  }
  if ((hwcaps & HWCAP_LPAE) != 0) {
    has_lpae = true;
  }
#endif

  return new ArmInstructionSetFeatures(smp, has_div, has_lpae);
}

// A signal handler called by a fault for an illegal instruction.  We record the fact in r0
// and then increment the PC in the signal context to return to the next instruction.  We know the
// instruction is an sdiv (4 bytes long).
static void bad_divide_inst_handle(int signo ATTRIBUTE_UNUSED, siginfo_t* si ATTRIBUTE_UNUSED,
                                   void* data) {
#if defined(__arm__)
  struct ucontext *uc = (struct ucontext *)data;
  struct sigcontext *sc = &uc->uc_mcontext;
  sc->arm_r0 = 0;     // Set R0 to #0 to signal error.
  sc->arm_pc += 4;    // Skip offending instruction.
#else
  UNUSED(data);
#endif
}

const ArmInstructionSetFeatures* ArmInstructionSetFeatures::FromAssembly() {
  const bool smp = true;

  // See if have a sdiv instruction.  Register a signal handler and try to execute an sdiv
  // instruction.  If we get a SIGILL then it's not supported.
  struct sigaction sa, osa;
  sa.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO;
  sa.sa_sigaction = bad_divide_inst_handle;
  sigaction(SIGILL, &sa, &osa);

  bool has_div = false;
#if defined(__arm__)
  if (artCheckForArmSdivInstruction()) {
    has_div = true;
  }
#endif

  // Restore the signal handler.
  sigaction(SIGILL, &osa, nullptr);

  // Use compile time features to "detect" LPAE support.
  // TODO: write an assembly LPAE support test.
#if defined(__ARM_FEATURE_LPAE)
  const bool has_lpae = true;
#else
  const bool has_lpae = false;
#endif
  return new ArmInstructionSetFeatures(smp, has_div, has_lpae);
}

bool ArmInstructionSetFeatures::Equals(const InstructionSetFeatures* other) const {
  if (kArm != other->GetInstructionSet()) {
    return false;
  }
  const ArmInstructionSetFeatures* other_as_arm = other->AsArmInstructionSetFeatures();
  return IsSmp() == other_as_arm->IsSmp() &&
      has_div_ == other_as_arm->has_div_ &&
      has_atomic_ldrd_strd_ == other_as_arm->has_atomic_ldrd_strd_;
}

uint32_t ArmInstructionSetFeatures::AsBitmap() const {
  return (IsSmp() ? kSmpBitfield : 0) |
      (has_div_ ? kDivBitfield : 0) |
      (has_atomic_ldrd_strd_ ? kAtomicLdrdStrdBitfield : 0);
}

std::string ArmInstructionSetFeatures::GetFeatureString() const {
  std::string result;
  if (IsSmp()) {
    result += "smp";
  } else {
    result += "-smp";
  }
  if (has_div_) {
    result += ",div";
  } else {
    result += ",-div";
  }
  if (has_atomic_ldrd_strd_) {
    result += ",atomic_ldrd_strd";
  } else {
    result += ",-atomic_ldrd_strd";
  }
  return result;
}

const InstructionSetFeatures* ArmInstructionSetFeatures::AddFeaturesFromSplitString(
    const bool smp, const std::vector<std::string>& features, std::string* error_msg) const {
  bool has_atomic_ldrd_strd = has_atomic_ldrd_strd_;
  bool has_div = has_div_;
  for (auto i = features.begin(); i != features.end(); i++) {
    std::string feature = Trim(*i);
    if (feature == "div") {
      has_div = true;
    } else if (feature == "-div") {
      has_div = false;
    } else if (feature == "atomic_ldrd_strd") {
      has_atomic_ldrd_strd = true;
    } else if (feature == "-atomic_ldrd_strd") {
      has_atomic_ldrd_strd = false;
    } else {
      *error_msg = StringPrintf("Unknown instruction set feature: '%s'", feature.c_str());
      return nullptr;
    }
  }
  return new ArmInstructionSetFeatures(smp, has_div, has_atomic_ldrd_strd);
}

}  // namespace art


text:
/******************************************************************************
 *
 * Module Name: ahmain - Main module for the acpi help utility
 *
 *****************************************************************************/

/*
 * Copyright (C) 2000 - 2013, Intel Corp.
 * 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,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 * 3. Neither the names of the above-listed copyright holders nor the names
 *    of any contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * Alternatively, this software may be distributed under the terms of the
 * GNU General Public License ("GPL") version 2 as published by the Free
 * Software Foundation.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
 */

#include "acpihelp.h"

/* Local prototypes */

static void
AhDisplayUsage (
    void);

#define AH_UTILITY_NAME             "ACPI Help Utility"
#define AH_SUPPORTED_OPTIONS        "ehikmopsv"

/******************************************************************************
 *
 * FUNCTION:    AhDisplayUsage
 *
 * DESCRIPTION: Usage message
 *
 ******************************************************************************/

static void
AhDisplayUsage (
    void)
{

    ACPI_USAGE_HEADER ("acpihelp <options> [NamePrefix | HexValue]");
    ACPI_OPTION ("-h",                      "Display help");
    ACPI_OPTION ("-v",                      "Display version information");

    printf ("\nACPI Names and Symbols:\n");
    ACPI_OPTION ("-k [NamePrefix]",         "Find/Display ASL non-operator keyword(s)");
    ACPI_OPTION ("-m [NamePrefix]",         "Find/Display AML opcode name(s)");
    ACPI_OPTION ("-p [NamePrefix]",         "Find/Display ASL predefined method name(s)");
    ACPI_OPTION ("-s [NamePrefix]",         "Find/Display ASL operator name(s)");

    printf ("\nACPI Values:\n");
    ACPI_OPTION ("-e [HexValue]",           "Decode ACPICA exception code");
    ACPI_OPTION ("-i",                      "Display known ACPI Device IDs (_HID)");
    ACPI_OPTION ("-o [HexValue]",           "Decode hex AML opcode");

    printf ("\nNamePrefix/HexValue not specified means \"Display All\"\n");
    printf ("\nDefault search with NamePrefix and no options:\n");
    printf ("    Find ASL operator names - if NamePrefix does not start with underscore\n");
    printf ("    Find ASL predefined method names - if NamePrefix starts with underscore\n");
}

/******************************************************************************
 *
 * FUNCTION:    main
 *
 * DESCRIPTION: C main function for AcpiHelp utility.
 *
 ******************************************************************************/

int ACPI_SYSTEM_XFACE
main (
    int                     argc,
    char                    *argv[])
{
    char                    *Name;
    UINT32                  DecodeType;
    int                     j;

    ACPI_DEBUG_INITIALIZE (); /* For debug version only */
    printf (ACPI_COMMON_SIGNON (AH_UTILITY_NAME));
    DecodeType = AH_DECODE_DEFAULT;

    if (argc < 2)
    {
        AhDisplayUsage ();
        return (0);
    }

    /* Command line options */

    while ((j = AcpiGetopt (argc, argv, AH_SUPPORTED_OPTIONS)) != EOF) switch (j)
    {
    case 'e':

        DecodeType = AH_DECODE_EXCEPTION;
        break;

    case 'i':

        DecodeType = AH_DISPLAY_DEVICE_IDS;
        break;

    case 'k':

        DecodeType = AH_DECODE_ASL_KEYWORD;
        break;

    case 'm':

        DecodeType = AH_DECODE_AML;
        break;

    case 'o':

        DecodeType = AH_DECODE_AML_OPCODE;
        break;

    case 'p':

        DecodeType = AH_DECODE_PREDEFINED_NAME;
        break;

    case 's':

        DecodeType = AH_DECODE_ASL;
        break;

    case 'v': /* -v: (Version): signon already emitted, just exit */

        return (0);

    case 'h':
    default:

        AhDisplayUsage ();
        return (-1);
    }

    /* Missing (null) name means "display all" */

    Name = argv[AcpiGbl_Optind];

    switch (DecodeType)
    {
    case AH_DECODE_AML:

        AhFindAmlOpcode (Name);
        break;

    case AH_DECODE_AML_OPCODE:

        AhDecodeAmlOpcode (Name);
        break;

    case AH_DECODE_PREDEFINED_NAME:

        AhFindPredefinedNames (Name);
        break;

    case AH_DECODE_ASL:

        AhFindAslOperators (Name);
        break;

    case AH_DECODE_ASL_KEYWORD:

        AhFindAslKeywords (Name);
        break;

    case AH_DISPLAY_DEVICE_IDS:

        AhDisplayDeviceIds ();
        break;

    case AH_DECODE_EXCEPTION:

        AhDecodeException (Name);
        break;

    default:

        if (!Name)
        {
            AhFindAslOperators (Name);
            break;
        }

        if (*Name == '_')
        {
            AhFindPredefinedNames (Name);
        }
        else
        {
            AhFindAslOperators (Name);
        }
        break;
    }

    return (0);
}

/*******************************************************************************
 *
 * FUNCTION:    AhStrupr (strupr)
 *
 * PARAMETERS:  SrcString           - The source string to convert
 *
 * RETURN:      None
 *
 * DESCRIPTION: Convert string to uppercase
 *
 * NOTE: This is not a POSIX function, so it appears here, not in utclib.c
 *
 ******************************************************************************/

void
AhStrupr (
    char                    *SrcString)
{
    char                    *String;

    if (!SrcString)
    {
        return;
    }

    /* Walk entire string, uppercasing the letters */

    for (String = SrcString; *String; String++)
    {
        *String = (char) toupper ((int) *String);
    }

    return;
}


text:
/**
 * External dependencies
 */
import styled from 'styled-components';
import { __ } from '@googleforcreators/i18n';
import PropTypes from 'prop-types';

/**
 * Internal dependencies
 */
import DirectionAware from '../directionAware';
import Carousel from './carousel';
import PrimaryMenu from './primaryMenu';
import SecondaryMenu from './secondaryMenu';
import { MAX_MENU_WIDTH } from './constants';

const Wrapper = styled.section`
  position: relative;
  display: grid;
  grid:
    /* Note the two empty 1fr areas each side of the buttons - that's on purpose */
    'secondary carousel primary' auto /
    1fr
    minmax(auto, calc(100% - ${3 * MAX_MENU_WIDTH}px))
    1fr;
  width: 100%;
  max-width: 100%;
  height: 100%;
`;

const Area = styled.div`
  grid-area: ${({ area }) => area};
  display: flex;
  align-items: flex-end;
  justify-content: center;
  z-index: ${({ zIndex = 'auto' }) => zIndex};
`;

function FooterLayout({ footer, zIndex }) {
  return (
    <DirectionAware>
      <Wrapper aria-label={__('Workspace Footer', 'web-stories')}>
        <Area area="carousel">
          <Carousel />
        </Area>
        <Area area="primary" zIndex={zIndex}>
          <PrimaryMenu />
        </Area>
        <Area area="secondary" zIndex={zIndex}>
          <SecondaryMenu menu={footer?.secondaryMenu} />
        </Area>
      </Wrapper>
    </DirectionAware>
  );
}

FooterLayout.propTypes = {
  footer: PropTypes.object,
  zIndex: PropTypes.number,
};

export default FooterLayout;


text:
package org.finra.datagenerator.scaffolding.transformer;

/**
 * Created by dkopel on 9/27/16.
 */
public class BigClass {
    private Integer id;

    private String name;

    private Long num;

    public Integer getId() {
        return id;
    }

    public BigClass setId(Integer id) {
        this.id = id;
        return this;
    }

    public String getName() {
        return name;
    }

    public BigClass setName(String name) {
        this.name = name;
        return this;
    }

    public Long getNum() {
        return num;
    }

    public BigClass setNum(Long num) {
        this.num = num;
        return this;
    }
}


text:
<?php

namespace Ryo88c\GlobeApiClient\Module;

use BEAR\Package\PackageModule;
use Ray\Di\AbstractModule;
use josegonzalez\Dotenv\Loader as Dotenv;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use BEAR\Resource\SchemeCollectionInterface;
use BEAR\Resource\ResourceInterface;
use Ryo88c\GlobeApiClient\Resource\Resource;

class AppModule extends AbstractModule
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $dotEnvPath = dirname(dirname(__DIR__)) . '/.env';
        if (file_exists($dotEnvPath) && is_readable($dotEnvPath)) {
            Dotenv::load([
                'filepath' => $dotEnvPath,
                'toEnv' => true
            ]);
        }
        $this->install(new PackageModule);
        $this->bind(ClientInterface::class)->to(Client::class);
        $this->bind(GlobeApiClientInterface::class)->to(GlobeApiClient::class);
    }
}


text:
<?php

namespace Magento\Framework\Exception;

class AuthorizationException extends LocalizedException
{
    const NOT_AUTHORIZED = 'Consumer is not authorized to access %resources';
}


text:
import time
from max7219.font import DEFAULT_FONT as deffont
from max7219.rotate8x8 import rotate

class constants(object):

  noop=0x0
  for i in range(8): eval("digit%i=0x%i"%(i,i+1))
  decodemode=0x9
  intensity=0xA
  scanlimit=0xB
  shutdown=0xC
  displaytest=0xF

class device(object):
  """
  Base class for handling multiple cascaded MAX7219 devices.
  Callers should generally pick either the :py:class:`sevensegment` or
  :py:class:`matrix` subclasses instead depending on which application
  is required.

  A buffer is maintained which holds the bytes that will be cascaded
  every time :py:func:`flush` is called.
  """

  NUM_digitS=8

  def __init__(self, cascaded=1, spi_bus=0, spi_device=0):
    """
    Constructor: `cascaded` should be the number of cascaded MAX7219
    devices that are connected.
    """

    import spidev
    assert cascaded>0, "Must have at least one device!"

    self._cascaded=cascaded
    self._buffer=[0]*self.NUM_digitS*self._cascaded
    self._spi=spidev.SpiDev()
    self._spi.open(spi_bus, spi_device)

    self.command(constants.scanlimit, 7)  # show all 8 digits
    self.command(constants.decodemode, 0)   # use matrix (not digits)
    self.command(constants.displaytest, 0)  # no display test
    self.command(constants.shutdown, 1)   # not shutdown mode
    self.brightness(7)                  # intensity: range: 0..15
    self.clear()

  def command(self, register, data):
    """
    Sends a specific register some data, replicated for all cascaded
    devices
    """

    assert constants.decodemode<=register<=constants.displaytest
    self._write([register, data]*self._cascaded)

  def _write(self, data):
    """
    Send the bytes (which should comprise of alternating command,
    data values) over the SPI device.
    """

    self._spi.xfer2(list(data))

  def _values(self, position, buf):
    """
    A generator which yields the digit/column position and the data
    value from that position for each of the cascaded devices.
    """

    for deviceId in range(self._cascaded):
      yield position+constants.digit0
      yield buf[(deviceId*self.NUM_digitS)+position]

  def clear(self, deviceId=None):
    """
    Clears the buffer the given deviceId if specified (else clears all
    devices), and flushes.
    """

    assert not deviceId or 0<=deviceId<self._cascaded, "Invalid deviceId: {0}".format(deviceId)

    if deviceId is None:
      start=0
      end=self._cascaded
    else:
      start=deviceId
      end=deviceId+1

    for deviceId in range(start, end):
      for position in range(self.NUM_digitS):
        self.set_byte(deviceId,
          position+constants.digit0,
          0, redraw=False)

    self.flush()

  def _preprocess_buffer(self, buf):
    """
    Overload in subclass to provide custom behaviour: see
    matrix implementation for example.
    """

    return buf

  def flush(self):
    """
    For each digit/column, cascade out the contents of the buffer
    cells to the SPI device.
    """

    # Allow subclasses to pre-process the buffer: they shouldn't
    # alter it, so make a copy first.
    buf=self._preprocess_buffer(list(self._buffer))
    assert len(buf)==len(self._buffer), "Preprocessed buffer is wrong size"
    for posn in range(self.NUM_digitS):
      self._write(self._values(posn, buf))

  def brightness(self, intensity):
    """
    Sets the brightness level of all cascaded devices to the same
    intensity level, ranging from 0..15. Note that setting the brightness
    to a high level will draw more current, and may cause intermittent
    issues / crashes if the USB power source is insufficient.
    """

    assert 0<=intensity<16, "Invalid brightness: {0}".format(intensity)
    self.command(constants.intensity, intensity)

  def set_byte(self, deviceId, position, value, redraw=True):
    """
    Low level mechanism to set a byte value in the buffer array. If redraw
    is not suppled, or set to True, will force a redraw of _all_ buffer
    items: If you are calling this method rapidly/frequently (e.g in a
    loop), it would be more efficient to set to False, and when done,
    call :py:func:`flush`.

    Prefer to use the higher-level method calls in the subclasses below.
    """

    assert 0<=deviceId<self._cascaded, "Invalid deviceId: {0}".format(deviceId)
    assert constants.digit0<=position<=constants.digit7, "Invalid digit/column: {0}".format(position)
    assert 0<=value<256, 'Value {0} outside range 0..255'.format(value)

    offset=(deviceId*self.NUM_digitS)+position - constants.digit0
    self._buffer[offset]=value

    if redraw: self.flush()

  def scroll_left(self, redraw=True):
    """
    Scrolls the buffer one column to the left. Any data that scrolls off
    the left side is lost and does not re-appear on the right. An empty
    column is inserted at the right-most position. If redraw
    is not suppled, or set to True, will force a redraw of _all_ buffer
    items
    """

    del self._buffer[0]
    self._buffer.append(0)
    if redraw: self.flush()

  def scroll_right(self, redraw=True):
    """
    Scrolls the buffer one column to the right. Any data that scrolls off
    the right side is lost and does not re-appear on the left. An empty
    column is inserted at the left-most position. If redraw
    is not suppled, or set to True, will force a redraw of _all_ buffer
    items
    """
    del self._buffer[-1]
    self._buffer.insert(0, 0)
    if redraw: self.flush()

class sevensegment(device):
  """
  Implementation of MAX7219 devices cascaded with a series of seven-segment
  LEDs. It provides a convenient method to write a number to a given device
  in octal, decimal or hex, flushed left/right with zero padding. Base 10
  numbers can be either integers or floating point (with the number of
  decimal points configurable).
  """

  _radix={8: 'o', 10: 'f', 16: 'x'}
  _digitS={
    ' ': 0x00,
    '-': 0x01,
    '0': 0x7e,
    '1': 0x30,
    '2': 0x6d,
    '3': 0x79,
    '4': 0x33,
    '5': 0x5b,
    '6': 0x5f,
    '7': 0x70,
    '8': 0x7f,
    '9': 0x7b,
    'a': 0x77,
    'b': 0x1f,
    'c': 0x4e,
    'd': 0x3d,
    'e': 0x4f,
    'f': 0x47
  }

  def letter(self, deviceId, position, char, dot=False, redraw=True):
    """
    Looks up the most appropriate character representation for char
    from the digits table, and writes that bitmap value into the buffer
    at the given deviceId / position.
    """

    assert dot in [0, 1, False, True]
    value=self._digitS[str(char)] | (dot << 7)
    self.set_byte(deviceId, position, value, redraw)

  def write_number(self, deviceId, value, base=10, decimalPlaces=0, zeroPad=False, leftJustify=False):
    """
    Formats the value according to the parameters supplied, and displays
    on the specified device. If the formatted number is larger than
    8 digits, then an OverflowError is raised.
    """

    assert 0<=deviceId<self._cascaded, "Invalid deviceId: {0}".format(deviceId)
    assert base in self._radix, "Invalid base: {0}".format(base)

    # Magic up a printf format string
    size=self.NUM_digitS
    formatStr='%'

    if zeroPad: formatStr+='0'
    if decimalPlaces>0: size+=1
    if leftJustify: size *= -1

    formatStr='{fmt}{size}.{dp}{type}'.format(fmt=formatStr, size=size, dp=decimalPlaces, type=self._radix[base])

    position=constants.digit7
    strValue=formatStr%value

    # Go through each digit in the formatted string,
    # updating the buffer accordingly
    for char in strValue:

      if position<constants.digit0:
        self.clear(deviceId)
        raise OverflowError('{0} too large for display'.format(strValue))

      if char=='.': continue

      dp=(decimalPlaces>0 and position==decimalPlaces+1)
      self.letter(deviceId, position, char, dot=dp, redraw=False)
      position-=1

    self.flush()

class matrix(device):
  """
  Implementation of MAX7219 devices cascaded with a series of 8x8 LED
  matrix devices. It provides a convenient methods to write letters
  to specific devices, to scroll a large message from left-to-right, or
  to set specific pixels. It is assumed the matrices are linearly aligned.
  """

  _invert=0
  _orientation=0

  def letter(self, deviceId, asciiCode, font=None, redraw=True):
    """
    Writes the ASCII letter code to the given device in the specified font.
    """

    assert 0<=asciiCode<256
    if not font: font=deffont

    col=constants.digit0
    for value in font[asciiCode]:
      if col>constants.digit7:
        self.clear(deviceId)
        raise OverflowError('Font for \'{0}\' too large for display'.format(asciiCode))

      self.set_byte(deviceId, col, value, redraw=False)
      col+=1

    if redraw: self.flush()

  def scroll_up(self, redraw=True):
    """
    Scrolls the underlying buffer (for all cascaded devices) up one pixel
    """

    self._buffer=[value >> 1 for value in self._buffer]
    if redraw: self.flush()

  def scroll_down(self, redraw=True):
    """
    Scrolls the underlying buffer (for all cascaded devices) down one pixel
    """

    self._buffer=[(value << 1) & 0xff for value in self._buffer]
    if redraw: self.flush()

  def show_message(self, text, font=None, delay=0.05):
    """
    Transitions the text message across the devices from left-to-right
    """

    # Add some spaces on (same number as cascaded devices) so that the
    # message scrolls off to the left completely.

    if not font: font=deffont
    text+=' '*self._cascaded
    src=(value for asciiCode in text for value in font[ord(asciiCode)])

    for value in src:
      time.sleep(delay)
      self.scroll_left(redraw=False)
      self._buffer[-1]=value
      self.flush()

  def pixel(self, x, y, value, redraw=True):
    """
    Sets (value=1) or clears (value=0) the pixel at the given
    co-ordinate. It may be more efficient to batch multiple pixel
    operations together with redraw=False, and then call
    :py:func:`flush` to redraw just once.
    """

    assert 0<=x<len(self._buffer)
    assert 0<=y<self.NUM_digitS

    if value: self._buffer[x] |= (1 << y)
    else: self._buffer[x] &= ~(1 << y)
    if redraw: self.flush()

  def _rotate(self, buf):
    """
    Rotates tiles in the buffer by the given orientation
    """
    result=[]
    for i in range(0, self._cascaded*self.NUM_digitS, self.NUM_digitS):
      tile=buf[i:i+self.NUM_digitS]
      for _ in range(self._orientation // 90):
        tile=rotate(tile)

      result+=tile

    return result

  def _preprocess_buffer(self, buf):
    """
    Inverts and/or orientates the buffer before flushing according to
    user set parameters
    """

    if self._invert: buf=[~x & 0xff for x in buf]
    if self._orientation: buf=self._rotate(buf)
    return super(matrix, self)._preprocess_buffer(buf)

  def invert(self, value, redraw=True):
    """
    Sets whether the display should be inverted or not when displaying
    letters.
    """

    assert value in [0, 1, False, True]

    self._invert=value
    if redraw: self.flush()

  def orientation(self, angle, redraw=True):
    """
    Sets the orientation (angle should be 0, 90, 180 or 270) at which
    the characters are displayed.
    """

    assert angle in [0, 90, 180, 270]

    self._orientation=angle
    if redraw: self.flush()


text:
    <snap-drawer>

HOME

REPORTS

LOGOUT

MORE PREMIUM THEME

    </snap-drawer>
    <snap-dragger></snap-dragger>
    <snap-content snap-opt-tap-to-close="false" class="bg-dark">

Reports
                Work with Chart.js and D3

Add Charts here

You can use C3.js or Chart.js

                    Back to Overview

    </snap-content>


text:
{% extends "base.html" %}
{% load static %}
{% block siteTitle %}Integrieren & Ableiten{% endblock %}
{% block moreStylesheets %}
    <link rel="stylesheet" href="{% static 'dropzone/dropzone.min.css' %}">
    {% include 'includeDefs/javascript-plotly.html' %}
{% endblock %}
{% block naviSpace %}
    {% include 'includeDefs/normalNavi.html' %}
{% endblock %}
{% block container %}

Integrieren & Ableiten

                    Du bearbeitest gerade das Experiment

                        {{experimentName}} (#{{experimentId}}).

 Hier kannst du Spalten über andere ableiten und integrieren, jeweils über einen "Auftrag".

                    Die neuen Spalten werden zusammen mit den alten in einem Experiment abgespeichert, sobald du - nach Ausführung aller gewünschten Aufträge - auf den Button "als Experiment speichern" klickst.

                    Dann kannst du deine neuen Spalten in der Analyse des neuen Experimentes ansehen.

                    <form method="post" enctype="multipart/form-data" id="newTaskForm">

                                {% csrf_token %}
                                Neuer Auftrag:

Ich möchte

                                    <select class="inline" id="firstCol" style="">
                                        {% for header, unit in jsonHeaderAndUnits %}
                                        <option value="{{ forloop.counter0 }}">({{ forloop.counter0 }}) {{ header }} ({{ unit }})</option>
                                        {% endfor %}
                                    </select>

                                über

                                    <select class="inline" id="secondCol">
                                    </select>

                                    <select class="inline" id="function">
                                        <option value="0">ableiten</option>
                                        <option value="1">integrieren</option>
                                    </select>

 !

                                    <input id="newColName" type="text" class="validate">
                                    Name der neuen Spalte

                                    <select class="" id='newColUnit'>
                                        <optgroup label='Zeit'>
                                            <option value='ms' selected>ms</option>
                                            <option value='sec'>sek</option>
                                            <option value='min'>min</option>
                                            <option value='h'>h</option>
                                        </optgroup>
                                        <optgroup label='Kraft'>
                                            <option value='N'>N</option>
                                            <option value='kN'>kN</option>
                                        </optgroup>
                                        <optgroup label='Weg'>
                                            <option value='m'>m</option>
                                            <option value='mm'>mm</option>
                                            <option value='cm'>cm</option>
                                            <option value='µm'>µm</option>
                                        </optgroup>
                                        <optgroup label='Geschwindigkeit'>
                                            <option value='m/s'>m/s</option>
                                            <option value='km/h'>km/h</option>
                                            <option value='mm/s'>mm/s</option>
                                        </optgroup>
                                        <optgroup label='Beschleunigung'>
                                            <option value='m/s²'>m/s²</option>
                                            <option value='g'>g</option>
                                            <option value='mm/s²'>mm/s²</option>
                                        </optgroup>
                                        <optgroup label='Impuls'>
                                            <option value='Ns'>Ns</option>
                                        </optgroup>
                                    </select>
                                    Einheit der neuen Spalte

                                <button class="btn waves-effect waves-light" type="submit" id="submitButton">ausführen
                                    send
                                </button>

                    </form>

                            Dein Auftrag wird gerade ausgeführt.

                    Abgeschlossene Aufträge:

                            check

                                Auftrag Task#:

                                Spalte
                                    FIRST ("NAME" (EINHEIT))
                                    wurde über Spalte
                                    SECOND ("NAME" (EINHEIT))
                                    ABGELEITET/INTEGRIERT.

                                    Das Ergebnis ist in Spalte
                                    RESULT_SPALTE ("NAME" EINHEIT)

                  {% if current_user_id == experiment_owner_id %}
                    Daten zum Experiment eingeben:
                    {% endif %}
                    <form action="{% url 'experiments:newESave' %}" method="post" enctype="multipart/form-data" id="">
                        {% csrf_token %}

                            <textarea style="display: none;" id="jsonEinheiten" name="jsonEinheiten">{{jsonEinheitenRealJson}}</textarea>
                            <textarea style="display: none;" id="jsonMeasurementInstruments" name="jsonMeasurementInstruments">{{jsonMInstrumentsRealJson}}</textarea>
                            <textarea style="display: none;" id="jsonData" name="jsonData">{{jsonData}}</textarea>
                            <input type="hidden" id="timeRowCol" name="zeitreihenSpalte" value="{{timerow}}"/>
                            <input type="hidden" id="projectId" name="projectId" value="{{ projectId }}"/>
                            <input type="hidden" id="dateFormat" name="dateFormat" value="{{ dateFormat }}"/>
                            <input type="hidden" id="jsonHeader" name="jsonHeader" value='{{jsonHeaderRealJson}}'/>
                            {% if current_user_id == experiment_owner_id %}

                                <input id="datensatzName" class="validate" name="datensatzName" type="text" value="{{experimentName}} - modifiziert" data-length="40"/>
                                Name des Experimentes

                                <textarea type="text" class="materialize-textarea" id="experimentDescr" name="experimentDescr">Aus "{{experimentName}}" (Experiment-ID: {{experimentId}}) entstanden.</textarea>
                                Weitere Informationen:

                            <button class="btn waves-effect waves-light" type="submit" style="position: relative; z-index: auto;">als Experiment speichern save</button>
                            {% endif %}
                    </form>

<input type="hidden" value="{{ experimentId }}" id="experimentId" />
<input type="hidden" value="{{ numOfCols }}" id="numOfCols" />

{% endblock %}

{% block moreScripts %}
    {% include 'includeDefs/javascript-forms.html' %}
    {% include 'includeDefs/jquery-validation.html' %}

{% endblock %}


text:
package cn.limw.summer.spring.web.view.image;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.View;

/**
 * @author li
 * @version 1 (2014年10月21日 下午3:03:33)
 * @since Java7
 */
public class TextToImageView implements View {
    private String text;

    public TextToImageView(String text) {
        this.text = text;
    }

    public String getContentType() {
        return "image/png";
    }

    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2d = bufferedImage.createGraphics();
        graphics2d.drawString(text, 20, 20);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(bufferedImage, "jpg", outputStream);
        outputStream.flush();
        outputStream.close();
    }
}


text:
package io.trane.ndbc.postgres.value;

public final class ByteArrayArrayValue extends PostgresValue<byte[][]> {

  public ByteArrayArrayValue(final byte[][] value) {
    super(value);
  }

  @Override
  public final byte[][] getByteArrayArray() {
    return get();
  }
}


text:
import {NgModule} from "@angular/core";
import {RouterModule} from "@angular/router";
import {CatsComponent} from "./cats.component";
import {CatListComponent} from "./cat-list.component";
import {CatDetailComponent} from "./cat-detail.component";
import {CatFormComponent} from "./cat-form.component";
@NgModule({
	imports: [
		RouterModule.forChild([
			{ path: "cats",
			  component: CatsComponent,
			  children: [
				  { path: "", component: CatListComponent, pathMatch: "full" },
				  { path: ":id/edit", component: CatFormComponent },
				  { path: "new", component: CatFormComponent },
				  { path: ":id", component: CatDetailComponent }
			  ]
			}
		])
	],
	exports: [RouterModule]
})
export class CatRoutingModule {}


text:
package nl.esciencecenter.vbrowser.vrs.mimetypes;

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

public class TestMimeTypes {

    @Test
    public void testDefaultMimeTypes() {

        MimeTypes mimeTypes=new MimeTypes();

        assertMimeType(mimeTypes,"test.pdf","application/pdf");
        assertMimeType(mimeTypes,"test.txt","text/plain");
        assertMimeType(mimeTypes,"test.html","text/html");
        assertMimeType(mimeTypes,"test.gif","image/gif");
        assertMimeType(mimeTypes,"test.png","image/png");

    }

    protected void assertMimeType(MimeTypes mimeTypes,String filename, String expected) {

        String mimeType=mimeTypes.getMimeType(filename);
        Assert.assertEquals("Expected mimetype doesn't match",expected,mimeType);

    }

}


text:
ace.define("ace/mode/textile_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module){"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var TextileHighlightRules = function () {
    this.$rules = {
        "start": [
            {
                token: function (value) {
                    if (value.charAt(0) == "h")
                        return "markup.heading." + value.charAt(1);
                    else
                        return "markup.heading";
                },
                regex: "h1|h2|h3|h4|h5|h6|bq|p|bc|pre",
                next: "blocktag"
            },
            {
                token: "keyword",
                regex: "[\\*]+|[#]+"
            },
            {
                token: "text",
                regex: ".+"
            }
        ],
        "blocktag": [
            {
                token: "keyword",
                regex: "\\. ",
                next: "start"
            },
            {
                token: "keyword",
                regex: "\\(",
                next: "blocktagproperties"
            }
        ],
        "blocktagproperties": [
            {
                token: "keyword",
                regex: "\\)",
                next: "blocktag"
            },
            {
                token: "string",
                regex: "[a-zA-Z0-9\\-_]+"
            },
            {
                token: "keyword",
                regex: "#"
            }
        ]
    };
};
oop.inherits(TextileHighlightRules, TextHighlightRules);
exports.TextileHighlightRules = TextileHighlightRules;

});

ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module){"use strict";
var Range = require("../range").Range;
var MatchingBraceOutdent = function () { };
(function () {
    this.checkOutdent = function (line, input) {
        if (!/^\s+$/.test(line))
            return false;
        return /^\s*\}/.test(input);
    };
    this.autoOutdent = function (doc, row) {
        var line = doc.getLine(row);
        var match = line.match(/^(\s*\})/);
        if (!match)
            return 0;
        var column = match[1].length;
        var openBracePos = doc.findMatchingBracket({ row: row, column: column });
        if (!openBracePos || openBracePos.row == row)
            return 0;
        var indent = this.$getIndent(doc.getLine(openBracePos.row));
        doc.replace(new Range(row, 0, row, column - 1), indent);
    };
    this.$getIndent = function (line) {
        return line.match(/^\s*/)[0];
    };
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;

});

ace.define("ace/mode/textile",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/textile_highlight_rules","ace/mode/matching_brace_outdent"], function(require, exports, module){"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var TextileHighlightRules = require("./textile_highlight_rules").TextileHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Mode = function () {
    this.HighlightRules = TextileHighlightRules;
    this.$outdent = new MatchingBraceOutdent();
    this.$behaviour = this.$defaultBehaviour;
};
oop.inherits(Mode, TextMode);
(function () {
    this.type = "text";
    this.getNextLineIndent = function (state, line, tab) {
        if (state == "intag")
            return tab;
        return "";
    };
    this.checkOutdent = function (state, line, input) {
        return this.$outdent.checkOutdent(line, input);
    };
    this.autoOutdent = function (state, doc, row) {
        this.$outdent.autoOutdent(doc, row);
    };
    this.$id = "ace/mode/textile";
    this.snippetFileId = "ace/snippets/textile";
}).call(Mode.prototype);
exports.Mode = Mode;

});                (function() {
                    ace.require(["ace/mode/textile"], function(m) {
                        if (typeof module == "object" && typeof exports == "object" && module) {
                            module.exports = m;
                        }
                    });
                })();


text:
user_home = "/home/" + node["user"]

package "libssl-dev" do
  action :install
end

package "gcc" do
  action :install
end

package "libreadline-dev" do
  action :install
end

package "zlib1g-dev" do
  action :install
end

bash "ruby-build" do
    user node["user"]
    cwd user_home
    code <<-EOH
      git clone https://github.com/sstephenson/ruby-build.git ruby-build
      cd ruby-build
      sudo ./install.sh
      cd ..
      rm -rf ruby-build
    EOH
end


text:
package org.sagebionetworks.repo.model.dbo.file.download.v2;

public enum ActionType {

	ACCESS_REQUIREMENT,
	DOWNLOAD_PERMISSION
}


text: Redirecting to https://github.com/ericgio.


text:
var japaneseModeStr = 'japanese';

module.exports = {
  browseMode: null,
  fontListPageNum: 1,
  fontListCardsPerPage: 16,
  lastFontListScrollPos: 0,
  searchText: '',
  sort: 'featured_rank',
  currentCollection: 'full',

  imsClientID : 'TypekitPlatformDemoApp', // Replace this with your client-id

  isJapaneseBrowseMode: function() {
    return this.browseMode === japaneseModeStr;
  },

  setJapaneseMode: function(toJapanese) {
    if (toJapanese) {
      this.browseMode = japaneseModeStr;
    }
    else {
      this.browseMode = null;
    }
  },

  captureFontListScrollPos: function() {
    this.lastFontListScrollPos = document.body.scrollTop;
  },

  setFontListScrollPos: function(pos) {
    document.body.scrollTop = pos;
  },

  restoreFontListScrollPos: function() {
    this.setFontListScrollPos(this.lastFontListScrollPos);
  },

  getClientID: function() {
    return this.imsClientID;
  },

  setSearchText: function(searchText) {
    this.searchText = searchText;
  },

  getSearchText: function() {
    return this.searchText;
  },

  setSortOrder: function(sort) {
    this.sort = sort;
  },

  getSortOrder: function() {
    return this.sort;
  },

  setCurrentCollection: function(collection) {
    this.currentCollection = collection;
  },

  getCurrentCollection: function() {
    return this.currentCollection;
  },
}


text:
<?php
namespace NinjaTooken\ClanBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ClanType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $kamonChoices = array();
        for($i=1;$i<135;$i++){
            $num = substr('0000'.$i,-4);
            $kamonChoices['kamon'.$num] = 'bundles/ninjatookenclan/kamon/kamon'.$num.'.png';
        }
        $builder
            ->add('nom', 'text', array(
                'label' => 'label.nom',
                'label_attr' => array('class' => 'libelle')
            ))
            ->add('tag', 'text', array(
                'label' => 'label.tag',
                'label_attr' => array('class' => 'libelle'),
                'required' => false
            ))
            ->add('accroche', 'text', array(
                'label' => 'label.accroche',
                'label_attr' => array('class' => 'libelle'),
                'required' => false
            ))
            ->add('description', 'textarea', array(
                'label' => 'label.description',
                'label_attr' => array('class' => 'libelle')
            ))
            ->add('url', 'url', array(
                'label' => 'label.url',
                'label_attr' => array('class' => 'libelle'),
                'required' => false
            ))
            ->add('kamon', 'choice', array(
                'label' => 'label.kamon',
                'label_attr' => array('class' => 'libelle'),
                'multiple' => false,
                'choices'  => $kamonChoices,
                'choices_as_values' => true,
                'data' => (isset($options['data']) && $options['data']->getKamon() !== null) ? $options['data']->getKamon() : key($kamonChoices)
            ))
            ->add('kamonUpload', 'file', array(
                'label' => 'label.kamonUpload',
                'label_attr' => array('class' => 'libelle'),
                'data_class' => null,
                'required' => false
            ))
            ->add('isRecruting', 'choice', array(
                'label' => 'label.isRecruting',
                'label_attr' => array('class' => 'libelle'),
                'multiple' => false,
                'expanded' => true,
                'choices'  => array(true => 'label.oui', false => 'label.non')
            ));
    }

    public function getName()
    {
        return 'clan';
    }
}


text:
function varargout = vis_gui(varargin)
% VIS_GUI M-file for vis_gui.fig
%      VIS_GUI, by itself, creates a new VIS_GUI or raises the existing
%      singleton*.
%
%      H = VIS_GUI returns the handle to a new VIS_GUI or the handle to
%      the existing singleton*.
%
%      VIS_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in VIS_GUI.M with the given input arguments.
%
%      VIS_GUI('Property','Value',...) creates a new VIS_GUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before vis_gui_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to vis_gui_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help vis_gui

% Last Modified by GUIDE v2.5 13-Jul-2003 03:28:58

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @vis_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @vis_gui_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before vis_gui is made visible.
function vis_gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to vis_gui (see VARARGIN)

% Choose default command line output for vis_gui
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes vis_gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% set checkboxes according to current values
global VIS;
set(handles.pos_real,'Value',VIS.show.real_pos);
set(handles.pos_calc,'Value',VIS.show.calc_pos);
set(handles.pos_error,'Value',VIS.show.pos_error);
set(handles.mag_contour, 'Value', VIS.show.mag_contour);

set(handles.routing_tree,'Value',VIS.show.route_tree);
set(handles.show_crumb, 'Value', VIS.show.crumb_trails);
%set(handles.route_messages,'Value',VIS.show.route_messages);

set(handles.real_agent_pos, 'Value', VIS.show.real_agent_pos);
set(handles.calc_agent_pos, 'Value', VIS.show.calc_agent_pos);

set(handles.agent_heading, 'Value', VIS.show.agent_heading);

% FIXME: for the demo, hide things that aren't implemented
set(handles.agent_heading, 'Visible', 'off');
%set(handles.pos_calc, 'Visible', 'off');
%set(handles.pos_error, 'Visible', 'off');

% --- Outputs from this function are returned to the command line.
function varargout = vis_gui_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% check the real_route flag, and do something reasonable based on
% whether we are showing real or calculated node positions
function fix_real_route
global VIS;
if VIS.show.real_pos || ~VIS.show.calc_pos
  %if VIS.show.real_route == 0
  %  VIS.flag.route_tree_updated = 1;
  %end
  VIS.show.real_route = 1;
else
  %if VIS.show.real_route == 1
  %  VIS.flag.route_tree_updated = 1;
  %end
  VIS.show.real_route = 0;
end

% --- Executes on button press in pos_real.
function pos_real_Callback(hObject, eventdata, handles)
global VIS;
VIS.show.real_pos = get(hObject,'Value');
fix_real_route;

% --- Executes on button press in pos_calc.
function pos_calc_Callback(hObject, eventdata, handles)
global VIS;
VIS.show.calc_pos = get(hObject,'Value');
fix_real_route;

% --- Executes on button press in pos_error.
function pos_error_Callback(hObject, eventdata, handles)
global VIS;
VIS.show.pos_error = get(hObject,'Value');

% --- Executes on button press in routing_tree.
function routing_tree_Callback(hObject, eventdata, handles)
global VIS;
VIS.show.route_tree = get(hObject,'Value');

% --- Executes on button press in route_messages.
function route_messages_Callback(hObject, eventdata, handles)
global VIS;
VIS.show.route_messages = get(hObject,'Value');

% --- Executes on button press in show_crumb.
function show_crumb_Callback(hObject, eventdata, handles)
global VIS;
VIS.show.crumb_trails = get(hObject,'Value');

% --- Executes on button press in mag_contour.
function mag_contour_Callback(hObject, eventdata, handles)
global VIS;
VIS.show.mag_nodes = get(hObject,'Value');
VIS.show.mag_contour = get(hObject,'Value');

% --- Executes on button press in real_agent_pos.
function real_agent_pos_Callback(hObject, eventdata, handles)
global VIS;
VIS.show.real_agent_pos = get(hObject,'Value');

% --- Executes on button press in calc_agent_pos.
function calc_agent_pos_Callback(hObject, eventdata, handles)
global VIS;
VIS.show.calc_agent_pos = get(hObject,'Value');

% --- Executes on button press in agent_heading.
function agent_heading_Callback(hObject, eventdata, handles)
global VIS;
VIS.show.agent_heading = get(hObject,'Value');

% --- Executes on button press in pause_vis.
function pause_vis_Callback(hObject, eventdata, handles)
global VIS;
if get(hObject,'Value') == 1
    stopVisTimer;
else
    startVisTimer;
end

% --- Executes during object creation, after setting all properties.
function ranging_data_CreateFcn(hObject, eventdata, handles)
set(hObject,'BackgroundColor','white');

% --- Executes on button press in ranging_data.
function ranging_data_Callback(hObject, eventdata, handles)
drawRangingInfo( get(hObject,'String') );

% --- Executes during object creation, after setting all properties.
function anchor_data_CreateFcn(hObject, eventdata, handles)
set(hObject,'BackgroundColor','white');

function anchor_data_Callback(hObject, eventdata, handles)
drawAnchorInfo( get(hObject,'String') );


text:
require_relative "../config/initializers/ruby_monkey_patches"

ENV['RAILS_ENV'] ||= 'test'
require "rspec"

$: << File.expand_path('../lib', File.dirname(__FILE__))

require "support/stub_helper.rb"


text:
import React from 'react';
import { mount, shallow } from 'enzyme';
import { ProgressBar } from '../ProgressBar';
import theme from '../theme.module.css';

describe('ProgressBar', () => {
  describe('#calculateRatio', () => {
    it('calculates the right ratio', () => {
      const wrapper = shallow(<ProgressBar min={100} max={300} theme={theme} />);
      const progressBar = wrapper.instance();
      expect(progressBar.calculateRatio(150)).toEqual(0.25);
    });

    it('gets 0 when value is less than min', () => {
      const wrapper = shallow(<ProgressBar min={100} max={300} theme={theme} />);
      const progressBar = wrapper.instance();
      expect(progressBar.calculateRatio(10)).toEqual(0);
    });

    it('gets 1 when value is more than max', () => {
      const wrapper = shallow(<ProgressBar min={100} max={300} theme={theme} />);
      const progressBar = wrapper.instance();
      expect(progressBar.calculateRatio(400)).toEqual(1);
    });
  });

  describe('#render', () => {
    it('renders the value and buffer bars when it is linear', () => {
      const wrapper = mount(<ProgressBar theme={theme} />);
      expect(wrapper.childAt(0).childAt(0).props().children.length).toEqual(2);
    });

    it('renders the value and buffer bars when it is linear', () => {
      const wrapper = mount(<ProgressBar mode="determinate" value={30} buffer={60} theme={theme} />);
      const buffer = wrapper.childAt(0).childAt(0).childAt(0);
      const value = wrapper.childAt(0).childAt(0).childAt(1);
      expect(buffer.props().style.transform).toEqual(`scaleX(${0.6})`);
      expect(value.props().style.transform).toEqual(`scaleX(${0.3})`);
    });

    it('renders the svg circle when it is circular', () => {
      const wrapper = mount(<ProgressBar type="circular" theme={theme} />);
      expect(wrapper.childAt(0).childAt(0).props().children.type).toEqual('circle');
    });

    it('renders the proper circle length style when it is circular and determinate', () => {
      const wrapper = mount(<ProgressBar type="circular" mode="determinate" value={30} theme={theme} />);
      const circle = wrapper.childAt(0).childAt(0).props().children;
      const strokeLength = 2 * Math.PI * circle.props.r * 0.3;
      expect(circle.props.style.strokeDasharray).toEqual(`${strokeLength}, 400`);
    });

    it('contains className in its className', () => {
      const wrapper = mount(<ProgressBar className="tight" mode="determinate" theme={theme} />);
      expect(wrapper.props().className).toContain('tight');
    });
  });
});


text:
package com.thunisoft.mediax.core.vfs;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

import junit.framework.TestCase;

import org.apache.commons.io.IOUtils;

import com.thunisoft.mediax.core.vfs.RandomAccessChannel;
import com.thunisoft.mediax.core.vfs.VFS;
import com.thunisoft.mediax.core.vfs.http.RandomAccessHttpChannelImpl;

public class TestRandomAccessHttpChannel extends TestCase {
    RandomAccessChannel rch;
    FileChannel fch;

    @Override
    protected void setUp() throws Exception {
        String localUrl = "http://localhost:8080/streamer/mp4/test1.mp4";
        rch = VFS.getRandomAccessChannel(localUrl);

        File file = new File(
                "E:/programs/Workspaces/MyEclipse 8.6/streamer/web/mp4/test1.mp4");
        fch = new FileInputStream(file).getChannel();
    }

    public void testReadByteBuffer() throws IOException {
        ByteBuffer b1 = ByteBuffer
                .allocate(RandomAccessHttpChannelImpl.RANGE_LENGTH * 2 - 5);
        ByteBuffer b2 = ByteBuffer
                .allocate(RandomAccessHttpChannelImpl.RANGE_LENGTH * 2 - 5);

        // at start
        for (int i = 0; i < 10; i++) {
            fch.position(i * RandomAccessHttpChannelImpl.RANGE_LENGTH + 4);
            rch.position(i * RandomAccessHttpChannelImpl.RANGE_LENGTH + 4);

            b1.clear();
            b2.clear();

            int rst1 = fch.read(b1);
            int rst2 = rch.read(b2);
            assertEquals(rst1, rst2);
            assertEquals(fch.position(), rch.position());
            assertEquals(b1, b2);
        }

        // at end side
        for (long i = fch.size() - 5; i < fch.size(); i++) {
            fch.position(i);
            rch.position(i);

            b1.clear();
            b2.clear();

            int rst1 = fch.read(b1);
            int rst2 = rch.read(b2);
            assertEquals(rst1, rst2);
            assertEquals(fch.position(), rch.position());
            assertEquals(b1, b2);
        }
    }

    public void testReadByteBuffer_01() throws IOException {
        ByteBuffer b1 = ByteBuffer
                .allocate(RandomAccessHttpChannelImpl.RANGE_LENGTH * 2 - 5);
        ByteBuffer b2 = ByteBuffer
                .allocate(RandomAccessHttpChannelImpl.RANGE_LENGTH * 2 - 5);

        // at start
        for (int i = 0; i < 10; i++) {
            fch.position(i);
            rch.position(i);

            b1.clear();
            b2.clear();
            b1.put((byte)1);
            b2.put((byte)1);

            int rst1 = fch.read(b1);
            int rst2 = rch.read(b2);
            assertEquals(rst1, rst2);
            assertEquals(fch.position(), rch.position());
            assertEquals(b1, b2);
        }

        // at end side
        for (long i = fch.size() - 5; i < fch.size(); i++) {
            fch.position(i);
            rch.position(i);

            b1.clear();
            b2.clear();
            b1.put((byte)1);
            b2.put((byte)1);

            int rst1 = fch.read(b1);
            int rst2 = rch.read(b2);
            assertEquals(rst1, rst2);
            assertEquals(fch.position(), rch.position());
            assertEquals(b1, b2);
        }
    }

    public void testMap() throws IOException {
        int size = RandomAccessHttpChannelImpl.RANGE_LENGTH + 1;

        // at start
        for (int i = 0; i < 10; i++) {
            fch.position(i);
            rch.position(i);

            ByteBuffer b1 = fch.map(MapMode.READ_ONLY, i, size);
            ByteBuffer b2 = rch.map(i, size);

            assertEquals(fch.position(), rch.position());
            assertEquals(b1, b2);
        }

        // at end side
        for (long i = fch.size() - size - 10; i < fch.size() - size; i++) {
            fch.position(i);
            rch.position(i);

            ByteBuffer b1 = fch.map(MapMode.READ_ONLY, i, size);
            ByteBuffer b2 = rch.map(i, size);

            assertEquals(fch.position(), rch.position());
            assertEquals(b1, b2);
        }
    }

    public void testTransferTo() {

    }

    @Override
    protected void tearDown() throws Exception {

        IOUtils.closeQuietly(rch);
        IOUtils.closeQuietly(fch);
    }
}


text:
<?php namespace Phalcon\Mvc\Model\EagerLoading;

use Phalcon\Mvc\Model\Query\Builder;

final class QueryBuilder extends Builder
{
    const E_NOT_ALLOWED_METHOD_CALL = 'When eager loading relations queries must return full entities';

    public function distinct($distinct)
    {
        throw new \LogicException(static::E_NOT_ALLOWED_METHOD_CALL);
    }

    public function columns($columns)
    {
        throw new \LogicException(static::E_NOT_ALLOWED_METHOD_CALL);
    }

    public function where($conditions, $bindParams = null, $bindTypes = null)
    {
        $currentConditions = $this->_conditions;

        /**
         * Nest the condition to current ones or set as unique
         */
        if ($currentConditions) {
            $conditions = "(" . $currentConditions . ") AND (" . $conditions . ")";
        }

        return parent::where($conditions, $bindParams, $bindTypes);
    }
}