text:
We are pleased to announce the inaugural class of Better Scientific Software (BSSw) Fellows: four Fellows and four Honorable Mentions.

The inaugural class of BSSw Fellows will be recognized during the [Exascale Computing Project 2nd Annual Meeting](https://www.ecpannualmeeting.com), February 6-9, 2018, in Knoxville, TN.  Thanks to _all_ fellowship applicants. The broad range of creative and interesting proposals made the selection process difficult.

The [BSSw Fellowship Program](https://bssw.io/fellowship) gives recognition and funding to leaders and advocates of high-quality scientific software. Each Fellow will receive up to $10,000 for an activity that promotes better scientific software, such as organizing a workshop, preparing a tutorial, or creating content to engage the scientific software community.

## 2018 BSSw Fellows

### Jeffrey Carver
University of Alabama, Professor, Computer Science

_BSSw Focus_: Contemporary peer code review in scientific software development

### Ivo Jimenez
University of California Santa Cruz, Ph.D. candidate, Computer Science

_BSSw focus_: generation of computational experimentation pipelines that are easy to re-execute and validate

### Daniel S. Katz
University of Illinois at Urbana-Champaign, Research Associate Professor, Computer Science, Electrical and Computer Engineering, and the School of Information Sciences

National Center for Supercomputing Applications, Assistant Director for Scientific Software and Applications

_BSSw focus_: techniques for making scientific software more sustainable by providing credit to its developers via software citation

### Andrew Lumsdaine
Pacific Northwest National Laboratory, Fellow, Advanced Computing, Mathematics, and Data Division

University of Washington, Affiliate Professor, Computer Science

Northwest Institute for Advanced Computing, Chief Scientist

_BSSw focus_: practices for high-performance and high-quality scientific software in modern C++

## 2018 BSSw Honorable Mentions

### Neal Davis
University of Illinois at Urbana-Champaign, Teaching Assistant Professor, Computer Science

### Elsa Gonsiorowski
Lawrence Livermore National Laboratory, HPC I/O Specialist, Livermore Computing

### Marc Henry de Frahan
National Renewable Energy Laboratory, Postdoctoral Researcher

### Ying Li
Argonne National Laboratory, Argonne Scholar, Argonne Leadership Computing Facility

### About the BSSw Fellowship
As described in a [prior blog article](https://bssw.io/blog_posts/applications-open-for-new-bssw-fellowship-program-q-a-webinar-on-dec-12-2017), the main goal of the BSSw Fellowship program is to foster and promote practices, processes, and tools to improve developer productivity and software sustainability of scientific codes. BSSw Fellows are selected annually based on an application process that includes the proposal of an activity that promotes better scientific software. Subscribe to the [BSSw email digest](https://bssw.io/pages/receive-our-email-digest) for notification about next year's call for applications, which will be announced in fall 2018.

Stay tuned for more from the 2018 BSSw Fellows.


text:
using System;
namespace DBlog.Data
{

    ///--------------------------------------------------------------------------------
    ///
    ///Persistent domain entity class representing 'DailyCounter' entities.
    ///
    ///<remarks>
    ///
    ///Mapping information:
    ///This class maps to the 'DailyCounter' table in the data source.
    ///</remarks>
    ///--------------------------------------------------------------------------------
    public class DailyCounter
    {
#region " Generated Code Region "
        //Private field variables

        //Holds property values
        private System.Int32 m_Id;
        private System.DateTime m_DateTime;
        private System.Int32 m_RequestCount;

        //Public properties
        ///--------------------------------------------------------------------------------
        ///
        ///Persistent primitive identity property.
        ///
        ///<remarks>
        ///This property is an identity property.
        ///The identity index for this property is '0'.
        ///This property accepts values of the type 'System.Int32'.
        ///The accessibility level for this property is 'PublicAccess'.
        ///The accessibility level for the field 'm_Id' that holds the value for this property is 'PrivateAccess'.
        ///
        ///Mapping information:
        ///The property maps to the column 'DailyCounter_Id' in the data source.
        ///</remarks>
        ///--------------------------------------------------------------------------------
        public virtual System.Int32 Id
        {
            get
            {
                return m_Id;
            }
        }

        ///--------------------------------------------------------------------------------
        ///
        ///Persistent primitive property.
        ///
        ///<remarks>
        ///This property accepts values of the type 'System.DateTime'.
        ///The accessibility level for this property is 'PublicAccess'.
        ///The accessibility level for the field 'm_DateTime' that holds the value for this property is 'PrivateAccess'.
        ///
        ///Mapping information:
        ///The property maps to the column 'DateTime' in the data source.
        ///</remarks>
        ///--------------------------------------------------------------------------------
        public virtual System.DateTime DateTime
        {
            get
            {
                return m_DateTime;
            }
            set
            {
                m_DateTime = value;
            }
        }

        ///--------------------------------------------------------------------------------
        ///
        ///Persistent primitive property.
        ///
        ///<remarks>
        ///This property accepts values of the type 'System.Int32'.
        ///The accessibility level for this property is 'PublicAccess'.
        ///The accessibility level for the field 'm_RequestCount' that holds the value for this property is 'PrivateAccess'.
        ///
        ///Mapping information:
        ///The property maps to the column 'RequestCount' in the data source.
        ///</remarks>
        ///--------------------------------------------------------------------------------
        public virtual System.Int32 RequestCount
        {
            get
            {
                return m_RequestCount;
            }
            set
            {
                m_RequestCount = value;
            }
        }

#endregion //Generated Code Region

        //Add your synchronized custom code here:
#region " Synchronized Custom Code Region "
#endregion //Synchronized Custom Code Region

        //Add your unsynchronized custom code here:
#region " Unsynchronized Custom Code Region "

#endregion //Unsynchronized Custom Code Region

    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';

import AwesomeSevenSegmentBase from '../index.js';

const SegmentVertical = (props) =>
{
return <rect {...props} width="1" height="4" />;
}
const SegmentHorisontal = (props) => <rect {...props} width="5" height="1" />;

const segmentOffsetMap = [
  { x: 1, y: 0 },
  { x: 6, y: 1 },
  { x: 6, y: 6 },
  { x: 1, y: 10 },
  { x: 0, y: 6 },
  { x: 0, y: 1 },
  { x: 1, y: 5 }
];

const segmentMap = [ SegmentHorisontal, SegmentVertical, SegmentVertical, SegmentHorisontal, SegmentVertical, SegmentVertical, SegmentHorisontal ];

const SsGuiLed = (props) => <AwesomeSevenSegmentBase digits={props.digits} segmentOffsetMap={segmentOffsetMap} segmentMap={segmentMap} />;

// Below causes a false positive!
// SsGuiLed.propTypes = {
//   digit: React.PropTypes.string,
// };

export default SsGuiLed;


text:
{% if not PLUGINS or 'seo' not in PLUGINS %}
  {% if SITELOGO %}
    {% set default_cover = SITELOGO %}
  {% else %}
    {% set default_cover = '{{ SITEURL }}/{{ THEME_STATIC_DIR }}/img/profile.png' %}
  {% endif %}
  <script type="application/ld+json">
  {
    "@context": "http://schema.org",
    "@type": "BlogPosting",
    "name": "{{ article.title|striptags }}",
    "headline": "{{ article.title|striptags }}",
    "datePublished": "{{ article.date }}",
    "dateModified": "{{ article.modified }}",
    "author": {
      "@type": "Person",
      "name": "{{ article.author.name }}",
      "url": "{{ SITEURL }}/{{ article.author.url }}"
    },
    "image": "{{ article.metadata.get('cover', default_cover) }}",
    "url": "{{ SITEURL }}/{{ article.url }}",
    "description": "{{ article.summary|striptags }}"
  }
  </script>
{% endif %}


text:
#if !defined(XTYPES_H)
#define XTYPES_H

typedef struct s_chanode {
	struct s_chanode *next;
	long icurr;
} chanode_t;

typedef struct s_chastore {
	chanode_t *head, *tail;
	long isize, nsize;
	chanode_t *ancur;
	chanode_t *sncur;
	long scurr;
} chastore_t;

typedef struct s_xrecord {
	struct s_xrecord *next;
	char const *ptr;
	long size;
	unsigned long ha;
} xrecord_t;

typedef struct s_xdfile {
	chastore_t rcha;
	long nrec;
	unsigned int hbits;
	xrecord_t **rhash;
	long dstart, dend;
	xrecord_t **recs;
	char *rchg;
	long *rindex;
	long nreff;
	unsigned long *ha;
} xdfile_t;

typedef struct s_xdfenv {
	xdfile_t xdf1, xdf2;
} xdfenv_t;

#endif /* #if !defined(XTYPES_H) */


text:
package bindings

// CommitDescription to avoid dupplication
type CommitDescription struct {
	Author struct {
		Raw  string `json:"raw"`
		User struct {
			DisplayName string `json:"display_name"`
			Links       struct {
				Avatar struct {
					Href string `json:"href"`
				} `json:"avatar"`
				HTML struct {
					Href string `json:"href"`
				} `json:"html"`
				Self struct {
					Href string `json:"href"`
				} `json:"self"`
			} `json:"links"`
			Type     string `json:"type"`
			Username string `json:"username"`
			UUID     string `json:"uuid"`
		} `json:"user"`
	} `json:"author"`
	Date  string `json:"date"`
	Hash  string `json:"hash"`
	Links struct {
		HTML struct {
			Href string `json:"href"`
		} `json:"html"`
		Self struct {
			Href string `json:"href"`
		} `json:"self"`
	} `json:"links"`
	Message string `json:"message"`
	Parents []struct {
		Hash  string `json:"hash"`
		Links struct {
			HTML struct {
				Href string `json:"href"`
			} `json:"html"`
			Self struct {
				Href string `json:"href"`
			} `json:"self"`
		} `json:"links"`
		Type string `json:"type"`
	} `json:"parents"`
	Type string `json:"type"`
}

// PushEvent to avoid dupplication
type PushEvent struct {
	Links struct {
		Commits struct {
			Href string `json:"href"`
		} `json:"commits"`
		HTML struct {
			Href string `json:"href"`
		} `json:"html"`
		Self struct {
			Href string `json:"href"`
		} `json:"self"`
	} `json:"links"`
	Name       string `json:"name"`
	Repository struct {
		FullName string `json:"full_name"`
		Links    struct {
			Avatar struct {
				Href string `json:"href"`
			} `json:"avatar"`
			HTML struct {
				Href string `json:"href"`
			} `json:"html"`
			Self struct {
				Href string `json:"href"`
			} `json:"self"`
		} `json:"links"`
		Name string `json:"name"`
		Type string `json:"type"`
		UUID string `json:"uuid"`
	} `json:"repository"`
	Target CommitDescription `json:"target"`
	Type   string            `json:"type"`
}

// BitbucketPushEvent is a JSON struct used to parsed the JSON payload send
// by Github on push events
type BitbucketPushEvent struct {
	Actor struct {
		DisplayName string `json:"display_name"`
		Links       struct {
			Avatar struct {
				Href string `json:"href"`
			} `json:"avatar"`
			HTML struct {
				Href string `json:"href"`
			} `json:"html"`
			Self struct {
				Href string `json:"href"`
			} `json:"self"`
		} `json:"links"`
		Type     string `json:"type"`
		Username string `json:"username"`
		UUID     string `json:"uuid"`
	} `json:"actor"`
	Push struct {
		Changes []struct {
			Closed  bool                `json:"closed"`
			Commits []CommitDescription `json:"commits"`
			Created bool                `json:"created"`
			Forced  bool                `json:"forced"`
			Links   struct {
				Commits struct {
					Href string `json:"href"`
				} `json:"commits"`
				Diff struct {
					Href string `json:"href"`
				} `json:"diff"`
				HTML struct {
					Href string `json:"href"`
				} `json:"html"`
			} `json:"links"`
			New       PushEvent `json:"new"`
			Old       PushEvent `json:"old"`
			Truncated bool      `json:"truncated"`
		} `json:"changes"`
	} `json:"push"`
	Repository struct {
		FullName  string `json:"full_name"`
		IsPrivate bool   `json:"is_private"`
		Links     struct {
			Avatar struct {
				Href string `json:"href"`
			} `json:"avatar"`
			HTML struct {
				Href string `json:"href"`
			} `json:"html"`
			Self struct {
				Href string `json:"href"`
			} `json:"self"`
		} `json:"links"`
		Name  string `json:"name"`
		Owner struct {
			DisplayName string `json:"display_name"`
			Links       struct {
				Avatar struct {
					Href string `json:"href"`
				} `json:"avatar"`
				HTML struct {
					Href string `json:"href"`
				} `json:"html"`
				Self struct {
					Href string `json:"href"`
				} `json:"self"`
			} `json:"links"`
			Type     string `json:"type"`
			Username string `json:"username"`
			UUID     string `json:"uuid"`
		} `json:"owner"`
		Scm     string `json:"scm"`
		Type    string `json:"type"`
		UUID    string `json:"uuid"`
		Website string `json:"website"`
	} `json:"repository"`
}


text:
package com.auth0.json.mgmt.organizations;

import com.fasterxml.jackson.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Represents the Invitation object for an organization.
 *
 * @see com.auth0.client.mgmt.OrganizationsEntity
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Invitation {

    @JsonProperty("id")
    private String id;
    @JsonProperty("inviter")
    private Inviter inviter;
    @JsonProperty("invitee")
    private Invitee invitee;
    @JsonProperty("ttl_sec")
    private Integer ttlInSeconds;
    @JsonProperty("client_id")
    private String clientId;
    @JsonProperty("connection_id")
    private String connectionId;
    @JsonProperty("app_metadata")
    private Map<String, Object> appMetadata;
    @JsonProperty("user_metadata")
    private Map<String, Object> userMetadata;
    @JsonProperty("send_invitation_email")
    private Boolean sendInvitationEmail;
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    @JsonProperty("created_at")
    private Date createdAt;
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    @JsonProperty("expires_at")
    private Date expiresAt;
    @JsonProperty("ticket_id")
    private String ticketId;
    @JsonProperty("invitation_url")
    private String invitationUrl;
    @JsonProperty("organization_id")
    private String organizationId;
    @JsonProperty("roles")
    private List<String> roles;

    /**
     * Create a new instance.
     *
     * @param inviter  the {@linkplain Inviter} of this invitation.
     * @param invitee  the {@linkplain Invitee} of this invitation.
     * @param clientId Auth0 client ID. Used to resolve the application's login initiation endpoint.
     */
    @JsonCreator
    public Invitation(@JsonProperty("inviter") Inviter inviter, @JsonProperty("invitee") Invitee invitee, @JsonProperty("client_id") String clientId) {
        this.inviter = inviter;
        this.invitee = invitee;
        this.clientId = clientId;
    }

    /**
     * @return the ID of this invitation.
     */
    public String getId() {
        return id;
    }

    /**
     * @return the {@linkplain Inviter} of this invitation.
     */
    public Inviter getInviter() {
        return inviter;
    }

    /**
     * @return the {@linkplain Invitee} of this invitation.
     */
    public Invitee getInvitee() {
        return invitee;
    }

    /**
     * @return the number of seconds before this invitation expires.
     */
    public Integer getTtlInSeconds() {
        return ttlInSeconds;
    }

    /**
     * Sets the number of seconds before this invitation expires.
     * If unspecified or set to 0, this value defaults to 604800 seconds (7 days). Max value: 2592000 seconds (30 days).
     *
     * @param ttlInSeconds the number of seconds before this invitation expires.
     */
    public void setTtlInSeconds(Integer ttlInSeconds) {
        this.ttlInSeconds = ttlInSeconds;
    }

    /**
     * @return the client ID of this invitation.
     */
    public String getClientId() {
        return clientId;
    }

    /**
     * @return the connection ID of this invitation.
     */
    public String getConnectionId() {
        return connectionId;
    }

    /**
     * Sets the ID of the connection for the inviter to authenticate with.
     *
     * @param connectionId the ID of the connection.
     */
    public void setConnectionId(String connectionId) {
        this.connectionId = connectionId;
    }

    /**
     * @return the app metadata of this invitation.
     */
    public Map<String, Object> getAppMetadata() {
        return appMetadata;
    }

    /**
     * Sets the app metadata associated with this invitation.
     *
     * @param appMetadata the app metadata.
     */
    public void setAppMetadata(Map<String, Object> appMetadata) {
        this.appMetadata = appMetadata;
    }

    /**
     * @return the user metadata of this invitation.
     */
    public Map<String, Object> getUserMetadata() {
        return userMetadata;
    }

    /**
     * Sets the user metadata associated with this invitation.
     *
     * @param userMetadata the user metadata.
     */
    public void setUserMetadata(Map<String, Object> userMetadata) {
        this.userMetadata = userMetadata;
    }

    /**
     * @return whether the user will receive an invitation email (true) or no email (false).
     */
    public Boolean isSendInvitationEmail() {
        return sendInvitationEmail;
    }

    /**
     * Whether the user will receive an invitation email (true) or no email (false). If not specified, default value is true.
     *
     * @param sendInvitationEmail whether to send the user an invitation email or not.
     */
    public void setSendInvitationEmail(Boolean sendInvitationEmail) {
        this.sendInvitationEmail = sendInvitationEmail;
    }

    /**
     * @return the date this invitation was created at.
     */
    public Date getCreatedAt() {
        return createdAt;
    }

    /**
     * @return the date this invitation expires.
     */
    public Date getExpiresAt() {
        return expiresAt;
    }

    /**
     * @return the ID of the invitation ticket.
     */
    public String getTicketId() {
        return ticketId;
    }

    /**
     * @return the roles associated with the user invited.
     */
    @JsonIgnore
    public Roles getRoles() {
        return new Roles(roles);
    }

    /**
     * Sets the roles to be associated with the user invited.
     *
     * @param roles the {@linkplain Roles} to associated with the user invited.
     */
    @JsonIgnore
    public void setRoles(Roles roles) {
        this.roles = roles.getRoles();
    }

    /**
     * @return the invitation url to be send to the invitee.
     */
    public String getInvitationUrl() {
        return invitationUrl;
    }

    /**
     * @return the ID of the organization for this invitation.
     */
    public String getOrganizationId() {
        return organizationId;
    }
}


text:
using System;
using Newtonsoft.Json;

namespace pcl
{
	public class Mobile
	{
		[JsonProperty ("name")]
		public string Name { get; set; }
		[JsonProperty ("id")]
		public int Id { get; set; }
		public bool Selected { get; set; }
		public string Title { get; set; }
		public string SubTitle { get; set; }

		public Mobile ()
		{
		}

		// Search for one element selected
		public static void Deselect(System.Collections.Generic.IList<Mobile> list)
		{
			foreach (var bean in list) {
				if (bean.Selected) {
					bean.Selected = false;
					break;
				}
			}
		}

		// Search for element id that is currently selected
		public static int SelectedId(System.Collections.Generic.IList<Mobile> list)
		{
			foreach (var bean in list) {
				if (bean.Selected) {
					return bean.Id;
				}
			}
			return 0;
		}

		// Search for element ids that are currently selected
		public static System.Collections.Generic.IList<int> SelectedIds(System.Collections.Generic.IList<Mobile> list)
		{
			System.Collections.Generic.List<int> selected = new System.Collections.Generic.List<int> ();
			foreach (var bean in list) {
				if (bean.Selected) {
					selected.Add (bean.Id);
				}
			}
			return selected;
		}

		// Whant to know index list for selected element
		public static int IndexSelected(System.Collections.Generic.IList<Mobile> list)
		{
			for (int i = 0; i < list.Count; i++) {
				if (list[i].Selected) {
					return i;
				}
			}
			return 0;
		}

		public override string ToString ()
		{
			return Name;
		}
	}
}


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE

using System;
using osu.Framework.Desktop;
using osu.Framework.Platform;

namespace osu.Framework.VisualTests
{
    public static class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            bool benchmark = args.Length > 0 && args[0] == @"-benchmark";

            using (GameHost host = Host.GetSuitableHost(@"visual-tests"))
            {
                if (benchmark)
                    host.Run(new AutomatedVisualTestGame());
                else
                    host.Run(new VisualTestGame());
            }
        }
    }
}


text:
package pe.fu.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author Administrator
 */
public class SerializeUtil {
    /**
     * 序列化对象
     *
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 反序列化对象
     *
     * @param bytes
     * @return
     */
    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {

        }
        return null;
    }
}


text:
'use strict';

var utils = require('../../lib/utils');
var Mocha = require('../../lib/mocha');
var sinon = require('sinon');

describe('Mocha', function() {
  var opts = {reporter: function() {}}; // no output
  var sandbox;

  beforeEach(function() {
    sandbox = sinon.createSandbox();
  });

  afterEach(function() {
    sandbox.restore();
  });

  describe('constructor', function() {
    beforeEach(function() {
      sandbox.stub(Mocha.prototype, 'useColors').returnsThis();
      sandbox.stub(utils, 'deprecate');
    });
    it('should prefer "color" over "useColors"', function() {
      // eslint-disable-next-line no-new
      new Mocha({useColors: true, color: false});
      expect(Mocha.prototype.useColors, 'to have a call satisfying', [false]);
    });

    it('should assign "useColors" to "color"', function() {
      // eslint-disable-next-line no-new
      new Mocha({useColors: true});
      expect(Mocha.prototype.useColors, 'to have a call satisfying', [true]);
    });

    it('should call utils.deprecate()', function() {
      // eslint-disable-next-line no-new
      new Mocha({useColors: true});
      expect(utils.deprecate, 'was called');
    });
  });

  describe('.run(fn)', function() {
    it('should not raise errors if callback was not provided', function() {
      sandbox.stub(Mocha.Runner.prototype, 'run');
      var mocha = new Mocha(opts);
      expect(function() {
        mocha.run();
      }, 'not to throw');
    });

    it('should execute the callback when complete', function(done) {
      var mocha = new Mocha(opts);
      sandbox.stub(Mocha.Runner.prototype, 'run').callsArg(0);
      mocha.run(done);
    });
  });

  describe('.reporter("xunit").run(fn)', function() {
    it('should not raise errors if callback was not provided', function() {
      var mocha = new Mocha();
      expect(function() {
        try {
          mocha.reporter('xunit').run();
        } catch (e) {
          console.log(e);
          expect.fail(e.message);
        }
      }, 'not to throw');
    });
  });

  describe('.addFile()', function() {
    it('should add the given file to the files array', function() {
      var mocha = new Mocha(opts);
      mocha.addFile('myFile.js');
      expect(mocha.files, 'to have length', 1).and('to contain', 'myFile.js');
    });
  });

  describe('.invert()', function() {
    it('should set the invert option to true', function() {
      var mocha = new Mocha(opts);
      mocha.invert();
      expect(mocha.options, 'to have property', 'invert', true);
    });

    it('should be chainable', function() {
      var mocha = new Mocha(opts);
      expect(mocha.invert(), 'to be', mocha);
    });
  });

  describe('.ignoreLeaks()', function() {
    it('should set the ignoreLeaks option to true when param equals true', function() {
      var mocha = new Mocha(opts);
      mocha.ignoreLeaks(true);
      expect(mocha.options, 'to have property', 'ignoreLeaks', true);
    });

    it('should set the ignoreLeaks option to false when param equals false', function() {
      var mocha = new Mocha(opts);
      mocha.ignoreLeaks(false);
      expect(mocha.options, 'to have property', 'ignoreLeaks', false);
    });

    it('should set the ignoreLeaks option to false when the param is undefined', function() {
      var mocha = new Mocha(opts);
      mocha.ignoreLeaks();
      expect(mocha.options, 'to have property', 'ignoreLeaks', false);
    });

    it('should be chainable', function() {
      var mocha = new Mocha(opts);
      expect(mocha.ignoreLeaks(), 'to be', mocha);
    });
  });

  describe('.checkLeaks()', function() {
    it('should set the ignoreLeaks option to false', function() {
      var mocha = new Mocha(opts);
      mocha.checkLeaks();
      expect(mocha.options, 'to have property', 'ignoreLeaks', false);
    });

    it('should be chainable', function() {
      var mocha = new Mocha(opts);
      expect(mocha.checkLeaks(), 'to be', mocha);
    });
  });

  describe('.fullTrace()', function() {
    it('should set the fullStackTrace option to true', function() {
      var mocha = new Mocha(opts);
      mocha.fullTrace();
      expect(mocha.options, 'to have property', 'fullStackTrace', true);
    });

    it('should be chainable', function() {
      var mocha = new Mocha(opts);
      expect(mocha.fullTrace(), 'to be', mocha);
    });
  });

  describe('.growl()', function() {
    describe('if capable of notifications', function() {
      it('should set the growl option to true', function() {
        var mocha = new Mocha(opts);
        mocha.isGrowlCapable = function forceEnable() {
          return true;
        };
        mocha.growl();
        expect(mocha.options, 'to have property', 'growl', true);
      });
    });
    describe('if not capable of notifications', function() {
      it('should set the growl option to false', function() {
        var mocha = new Mocha(opts);
        mocha.isGrowlCapable = function forceDisable() {
          return false;
        };
        mocha.growl();
        expect(mocha.options, 'to have property', 'growl', false);
      });
    });
    it('should be chainable', function() {
      var mocha = new Mocha(opts);
      expect(mocha.growl(), 'to be', mocha);
    });
  });

  describe('.useInlineDiffs()', function() {
    it('should set the useInlineDiffs option to true when param equals true', function() {
      var mocha = new Mocha(opts);
      mocha.useInlineDiffs(true);
      expect(mocha.options, 'to have property', 'useInlineDiffs', true);
    });

    it('should set the useInlineDiffs option to false when param equals false', function() {
      var mocha = new Mocha(opts);
      mocha.useInlineDiffs(false);
      expect(mocha.options, 'to have property', 'useInlineDiffs', false);
    });

    it('should set the useInlineDiffs option to false when the param is undefined', function() {
      var mocha = new Mocha(opts);
      mocha.useInlineDiffs();
      expect(mocha.options, 'to have property', 'useInlineDiffs', false);
    });

    it('should be chainable', function() {
      var mocha = new Mocha(opts);
      expect(mocha.useInlineDiffs(), 'to be', mocha);
    });
  });

  describe('.noHighlighting()', function() {
    it('should set the noHighlighting option to true', function() {
      var mocha = new Mocha(opts);
      mocha.noHighlighting();
      expect(mocha.options, 'to have property', 'noHighlighting', true);
    });
  });

  describe('.allowUncaught()', function() {
    it('should set the allowUncaught option to true', function() {
      var mocha = new Mocha(opts);
      mocha.allowUncaught();
      expect(mocha.options, 'to have property', 'allowUncaught', true);
    });
  });

  describe('.delay()', function() {
    it('should set the delay option to true', function() {
      var mocha = new Mocha(opts);
      mocha.delay();
      expect(mocha.options, 'to have property', 'delay', true);
    });
  });

  describe('.bail()', function() {
    it('should set the suite._bail to true if there is no arguments', function() {
      var mocha = new Mocha(opts);
      mocha.bail();
      expect(mocha.suite._bail, 'to be', true);
    });
  });

  describe('error handling', function() {
    it('should throw reporter error if an invalid reporter is given', function() {
      var updatedOpts = {reporter: 'invalidReporter', reporterOptions: {}};
      var throwError = function() {
        // eslint-disable-next-line no-new
        new Mocha(updatedOpts);
      };
      expect(throwError, 'to throw', {
        message: 'invalid reporter "invalidReporter"',
        code: 'ERR_MOCHA_INVALID_REPORTER',
        reporter: 'invalidReporter'
      });
    });
  });
});


text:
import React from 'react'
import BlogPostReview from '../components/Blog/post-review'
import BlogPostList from '../components/Blog/post-list'

export default function Index ({ data }) {
  const { edges: posts } = data.allMarkdownRemark
  return (
    <div>
      <BlogPostList>
        {posts
          .filter(post => post.node.frontmatter.title.length > 0)
          .map(({ node: post }) => {
            return (
              <BlogPostReview key={post.id} excerpt={post} />
            )
          })}
      </BlogPostList>
    </div>
  )
}

export const pageQuery = graphql`
  query IndexQuery {
    allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
      edges {
        node {
          excerpt(pruneLength: 250)
          id
          frontmatter {
            title
            date(formatString: "MMMM DD, YYYY")
            path
            language
            cover {
              publicURL
            }
          }
        }
      }
    }
  }
`


text:
package com.openxc.enabler;

import android.os.Looper;

import com.openxcplatform.enabler.BuildConfig;

public class ThreadPreconditions {
    private ThreadPreconditions(){

    }
    public static void checkOnMainThread() {
        if (BuildConfig.DEBUG && Thread.currentThread() != Looper.getMainLooper().getThread()) {
                throw new IllegalStateException("This method should be called from the Main Thread");
        }
    }
}


text:
package com.twitter.finagle.tracing

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FunSuite

@RunWith(classOf[JUnitRunner])
class TracerTest extends FunSuite {
  case class TestTracer(res: Option[Boolean]) extends Tracer {
    def record(record: Record) {}
    def sampleTrace(traceId: TraceId): Option[Boolean] = res
    override def isActivelyTracing(traceId: TraceId): Boolean = res.getOrElse(true)
  }

  test("Combined tracers sample correctly") {
    val id = TraceId(None, None, SpanId(0L), None)
    assert(BroadcastTracer(
      Seq(TestTracer(None), TestTracer(None), TestTracer(None))
    ).sampleTrace(id) == None, "If all None returns None")

    assert(BroadcastTracer(
      Seq(TestTracer(Some(true)), TestTracer(None), TestTracer(None))
    ).sampleTrace(id) == Some(true), "If one Some(true) returns Some(true)")

    assert(BroadcastTracer(
      Seq(TestTracer(Some(true)), TestTracer(Some(false)), TestTracer(None))
    ).sampleTrace(id) == Some(true), "If one Some(true) returns Some(true)")

    assert(BroadcastTracer(
      Seq(TestTracer(None), TestTracer(Some(false)), TestTracer(None))
    ).sampleTrace(id) == None, "If one Some(false) returns None")

    assert(BroadcastTracer(
      Seq(TestTracer(Some(false)), TestTracer(Some(false)), TestTracer(Some(false)))
    ).sampleTrace(id) == Some(false), "If all Some(false) returns Some(false)")
  }

  test("Combined tracers determine active tracing correctly") {
    val id = TraceId(None, None, SpanId(0L), None)
    assert(BroadcastTracer(
      Seq(TestTracer(Some(true)), TestTracer(Some(false)), TestTracer(Some(false)))
    ).isActivelyTracing(id) == true, "If any Some(true) returns true")

    assert(BroadcastTracer(
      Seq(TestTracer(Some(false)), TestTracer(Some(false)), TestTracer(Some(false)))
    ).isActivelyTracing(id) == false, "If all Some(false) returns false")
  }

  test("check equality of tracers") {
    val previous = DefaultTracer.self
    DefaultTracer.self = NullTracer

    val tracer = DefaultTracer
    assert(tracer == NullTracer, "Can't detect that tracer is NullTracer")

    DefaultTracer.self = ConsoleTracer
    assert(tracer != NullTracer, "Can't detect that tracer isn't NullTracer anymore")
    assert(tracer == ConsoleTracer, "Can't detect that tracer is ConsoleTracer")

    // Restore initial state
    DefaultTracer.self = previous
  }
}


text:
var fs = require("fs");
var path = require("path");
var utilities = require("../lib/utilities");
var xcode = require("xcode");
var plist = require('plist');

/**
 * This is used as the display text for the build phase block in XCode as well as the
 * inline comments inside of the .pbxproj file for the build script phase block.
 */
var comment = "\"Crashlytics\"";

module.exports = {

    /**
     * Used to get the path to the XCode project's .pbxproj file.
     */
    getXcodeProjectPath: function () {
        var appName = utilities.getAppName();
        return path.join("platforms", "ios", appName + ".xcodeproj", "project.pbxproj");
    },

    /**
     * This helper is used to add a build phase to the XCode project which runs a shell
     * script during the build process. The script executes Crashlytics run command line
     * tool with the API and Secret keys. This tool is used to upload the debug symbols
     * (dSYMs) so that Crashlytics can display stack trace information in it's web console.
     */
    addShellScriptBuildPhase: function (context, xcodeProjectPath) {

        // Read and parse the XCode project (.pxbproj) from disk.
        // File format information: http://www.monobjc.net/xcode-project-file-format.html
        var xcodeProject = xcode.project(xcodeProjectPath);
        xcodeProject.parseSync();

        // Build the body of the script to be executed during the build phase.
        var script = '"' + '\\"${PODS_ROOT}/Fabric/run\\"' + '"';

        // Generate a unique ID for our new build phase.
        var id = xcodeProject.generateUuid();
        // Create the build phase.
        xcodeProject.hash.project.objects.PBXShellScriptBuildPhase[id] = {
            isa: "PBXShellScriptBuildPhase",
            buildActionMask: 2147483647,
            files: [],
            inputPaths: ['"' + '$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)' + '"'],
            name: comment,
            outputPaths: [],
            runOnlyForDeploymentPostprocessing: 0,
            shellPath: "/bin/sh",
            shellScript: script,
            showEnvVarsInLog: 0
        };

        // Add a comment to the block (viewable in the source of the pbxproj file).
        xcodeProject.hash.project.objects.PBXShellScriptBuildPhase[id + "_comment"] = comment;

        // Add this new shell script build phase block to the targets.
        for (var nativeTargetId in xcodeProject.hash.project.objects.PBXNativeTarget) {

            // Skip over the comment blocks.
            if (nativeTargetId.indexOf("_comment") !== -1) {
                continue;
            }

            var nativeTarget = xcodeProject.hash.project.objects.PBXNativeTarget[nativeTargetId];

            nativeTarget.buildPhases.push({
                value: id,
                comment: comment
            });
        }

        // Finally, write the .pbxproj back out to disk.
        fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync());
    },

    /**
     * This helper is used to remove the build phase from the XCode project that was added
     * by the addShellScriptBuildPhase() helper method.
     */
    removeShellScriptBuildPhase: function (context, xcodeProjectPath) {

        // Read and parse the XCode project (.pxbproj) from disk.
        // File format information: http://www.monobjc.net/xcode-project-file-format.html
        var xcodeProject = xcode.project(xcodeProjectPath);
        xcodeProject.parseSync();

        // First, we want to delete the build phase block itself.

        var buildPhases = xcodeProject.hash.project.objects.PBXShellScriptBuildPhase;

        var commentTest = comment.replace(/"/g, '');
        for (var buildPhaseId in buildPhases) {

            var buildPhase = xcodeProject.hash.project.objects.PBXShellScriptBuildPhase[buildPhaseId];
            var shouldDelete = false;

            if (buildPhaseId.indexOf("_comment") === -1) {
                // Dealing with a build phase block.

                // If the name of this block matches ours, then we want to delete it.
                shouldDelete = buildPhase.name && buildPhase.name.indexOf(commentTest) !== -1;
            } else {
                // Dealing with a comment block.

                // If this is a comment block that matches ours, then we want to delete it.
                shouldDelete = buildPhase === commentTest;
            }

            if (shouldDelete) {
                delete buildPhases[buildPhaseId];
            }
        }

        // Second, we want to delete the native target reference to the block.

        var nativeTargets = xcodeProject.hash.project.objects.PBXNativeTarget;

        for (var nativeTargetId in nativeTargets) {

            // Skip over the comment blocks.
            if (nativeTargetId.indexOf("_comment") !== -1) {
                continue;
            }

            var nativeTarget = nativeTargets[nativeTargetId];

            // We remove the reference to the block by filtering out the the ones that match.
            nativeTarget.buildPhases = nativeTarget.buildPhases.filter(function (buildPhase) {
                return buildPhase.comment !== commentTest;
            });
        }

        // Finally, write the .pbxproj back out to disk.
        fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync());
    },

    ensureRunpathSearchPath: function(context, xcodeProjectPath){

        function addRunpathSearchBuildProperty(proj, build) {
            const LD_RUNPATH_SEARCH_PATHS = proj.getBuildProperty("LD_RUNPATH_SEARCH_PATHS", build);
            if (!LD_RUNPATH_SEARCH_PATHS) {
                proj.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", build);
            }
            if (LD_RUNPATH_SEARCH_PATHS.indexOf("@executable_path/Frameworks") == -1) {
                var newValue = LD_RUNPATH_SEARCH_PATHS.substr(0, LD_RUNPATH_SEARCH_PATHS.length - 1);
                newValue += ' @executable_path/Frameworks\"';
                proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build);
            }
            if (LD_RUNPATH_SEARCH_PATHS.indexOf("$(inherited)") == -1) {
                var newValue = LD_RUNPATH_SEARCH_PATHS.substr(0, LD_RUNPATH_SEARCH_PATHS.length - 1);
                newValue += ' $(inherited)\"';
                proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build);
            }
        }

        // Read and parse the XCode project (.pxbproj) from disk.
        // File format information: http://www.monobjc.net/xcode-project-file-format.html
        var xcodeProject = xcode.project(xcodeProjectPath);
        xcodeProject.parseSync();

        // Add search paths build property
        addRunpathSearchBuildProperty(xcodeProject, "Debug");
        addRunpathSearchBuildProperty(xcodeProject, "Release");

        // Finally, write the .pbxproj back out to disk.
        fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync());
    },
    stripDebugSymbols: function(){
        var podFilePath = 'platforms/ios/Podfile',
            podFile = fs.readFileSync(path.resolve(podFilePath)).toString();
        if(!podFile.match('DEBUG_INFORMATION_FORMAT')){
            podFile += "\npost_install do |installer|\n" +
                "    installer.pods_project.targets.each do |target|\n" +
                "        target.build_configurations.each do |config|\n" +
                "            config.build_settings['DEBUG_INFORMATION_FORMAT'] = 'dwarf'\n" +
                "        end\n" +
                "    end\n" +
                "end";
            fs.writeFileSync(path.resolve(podFilePath), podFile);
            console.log('cordova-plugin-firebasex: Applied IOS_STRIP_DEBUG to Podfile');
        }
    },
    applyPluginVarsToPlists: function(googlePlistPath, appPlistPath, pluginVariables){
        var googlePlist = plist.parse(fs.readFileSync(path.resolve(googlePlistPath), 'utf8')),
            appPlist = plist.parse(fs.readFileSync(path.resolve(appPlistPath), 'utf8')),
            googlePlistModified = false,
            appPlistModified = false;

        if(typeof pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== 'undefined'){
            googlePlist["FIREBASE_ANALYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ;
            appPlist["FirebaseScreenReportingEnabled"] = (pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== "false");
            appPlistModified = googlePlistModified = true;
        }
        if(typeof pluginVariables['FIREBASE_PERFORMANCE_COLLECTION_ENABLED'] !== 'undefined'){
            googlePlist["FIREBASE_PERFORMANCE_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_PERFORMANCE_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ;
            googlePlistModified = true;
        }
        if(typeof pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== 'undefined'){
            googlePlist["FIREBASE_CRASHLYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ;
            googlePlistModified = true;
        }
        if(pluginVariables['SETUP_RECAPTCHA_VERIFICATION'] === 'true'){
            var reversedClientId = googlePlist['REVERSED_CLIENT_ID'];

            if(!appPlist['CFBundleURLTypes']) appPlist['CFBundleURLTypes'] = [];
            var entry, i;
            for(i=0; i<appPlist['CFBundleURLTypes'].length; i++){
                if(typeof appPlist['CFBundleURLTypes'][i] === 'object' && appPlist['CFBundleURLTypes'][i]['CFBundleURLSchemes']){
                    entry = appPlist['CFBundleURLTypes'][i];
                    break;
                }
            }
            if(!entry) entry = {};
            if(!entry['CFBundleTypeRole']) entry['CFBundleTypeRole'] = 'Editor';
            if(!entry['CFBundleURLSchemes']) entry['CFBundleURLSchemes'] = [];
            if(entry['CFBundleURLSchemes'].indexOf(reversedClientId) === -1){
                entry['CFBundleURLSchemes'].push(reversedClientId)
            }
            appPlist['CFBundleURLTypes'][i] = entry;
            appPlistModified = true;
        }

        if(googlePlistModified) fs.writeFileSync(path.resolve(googlePlistPath), plist.build(googlePlist));
        if(appPlistModified) fs.writeFileSync(path.resolve(appPlistPath), plist.build(appPlist));
    }
};


text:
import os
from os_package_registry import PackageRegistry

class ModelRegistry(PackageRegistry):

    def __init__(self, es=None):
        if es is not None:
            super(ModelRegistry, self).__init__(es_instance=es)
        else:
            super(ModelRegistry, self).__init__(
                es_connection_string=os.environ.get('OS_ELASTICSEARCH_ADDRESS','localhost:9200'))


text:
<!doctype html>

<meta charset='utf-8' />

Type any Lojban text in the following textarea. The result will be parsed as you type:

<form id="form1" name="form1" method="post" action="" style="width:100%">
  <textarea id="input_textarea" style="width:100%" rows="8" autofocus></textarea>

  <input type='button' onClick="run_camxes();" value="Parse" />

</form>


text:
import unittest
from lastfm_stats import trackparser
from lastfm_stats import datastore

class TestTrackParser(unittest.TestCase):
    artist1 = datastore.Artist(id="Led Zeppelin")
    artist2 = datastore.Artist(id="Johann Sebastian Bach")
    track1 = datastore.Track(name="Misty mountain hop",
                             listening_uts=1234567,
                             artist_id=artist1.id,
                             artist=artist1)
    track2 = datastore.Track(name="Toccata and fugue in D minor BWV565",
                             listening_uts=2345678,
                             artist_id=artist2.id,
                             artist=artist2)

    track1_blob = {
        "artist": {
            "#text": "Led Zeppelin"
        },
        "name": "Misty mountain hop",
        "date": {
            "uts": "1234567"
        }
    }

    track2_blob = {
        "artist": {
            "#text": "Johann Sebastian Bach"
        },
        "name": "Toccata and fugue in D minor BWV565",
        "date": {
            "uts": "2345678"
        }
    }

    response_blob = {
        "recenttracks": {
            "track": [track1_blob, track2_blob]
        }
    }

    malformed_response_blob = {
        "test": "value"
    }

    def assertTracksEqual(self, base, compared):
        self.assertEqual(base.artist_id, compared.artist_id)
        self.assertEqual(base.name, compared.name)
        self.assertEqual(base.listening_uts, compared.listening_uts)

    def test_build_track_from_builds_a_track(self):
        expected = self.track1
        result = trackparser.build_track_from(self.track1_blob)
        self.assertTracksEqual(expected, result)

    def test_build_track_from_with_malformed_blob(self):
        result = trackparser.build_track_from(self.malformed_response_blob)
        self.assertIsNone(result)

    def test_parse_returns_list_of_tracks(self):
        result_list = trackparser.parse_track_collection(self.response_blob)
        self.assertEqual(2, len(result_list))
        self.assertTracksEqual(self.track1, result_list[0])
        self.assertTracksEqual(self.track2, result_list[1])

    def test_parse_with_malformed_blob(self):
        result = trackparser.parse_track_collection(self.malformed_response_blob)
        self.assertEqual(0, len(result))


text:
//
//  NSDate+AGXCore.h
//  AGXCore
//
//  Created by Char Aznable on 2016/2/4.
//  Copyright © 2016 github.com/CharLemAznable. All rights reserved.
//

#ifndef AGXCore_NSDate_AGXCore_h
#define AGXCore_NSDate_AGXCore_h

#import "AGXCategory.h"

typedef long long AGXTimeIntervalMills;

@category_interface(NSDate, AGXCore)
- (AGXTimeIntervalMills)timeIntervalMillsSinceDate:(NSDate *)anotherDate;
@property (readonly) AGXTimeIntervalMills timeIntervalMillsSinceNow;
@property (readonly) AGXTimeIntervalMills timeIntervalMillsSince1970;

@property (readonly) NSInteger era;
@property (readonly) NSInteger year;
@property (readonly) NSInteger month;
@property (readonly) NSInteger day;
@property (readonly) NSInteger hour;
@property (readonly) NSInteger minute;
@property (readonly) NSInteger second;
@property (readonly) NSInteger weekday;

@property (readonly) NSInteger monthCountInYear;
@property (readonly) NSInteger dayCountInMonth;
@property (readonly) NSInteger dayCountInYear;

- (NSString *)stringWithDateFormat:(NSString *)dateFormat;
- (NSString *)stringWithDateFormat:(NSString *)dateFormat timeZone:(NSTimeZone *)timeZone;

//  Created by Marcus Rohrmoser
//  http://blog.mro.name/2009/08/nsdateformatter-http-header/
//  http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
+ (AGX_INSTANCETYPE)dateFromRFC1123:(NSString *)rfc1123String;
- (NSString *)rfc1123String;

+ (AGX_INSTANCETYPE)dateFromRFC3339:(NSString *)rfc3339String;
- (NSString *)rfc3339String;
@end

@category_interface(NSNumber, AGXCoreNSDate)
+ (AGX_INSTANCETYPE)numberWithTimeInterval:(NSTimeInterval)value;
- (AGX_INSTANCETYPE)initWithTimeInterval:(NSTimeInterval)value;
- (NSTimeInterval)timeIntervalValue;

+ (AGX_INSTANCETYPE)numberWithMills:(AGXTimeIntervalMills)value;
- (AGX_INSTANCETYPE)initWithMills:(AGXTimeIntervalMills)value;
- (AGXTimeIntervalMills)millsValue;
@end

@category_interface(NSString, AGXCoreNSDate)
- (NSDate *)dateWithDateFormat:(NSString *)dateFormat;
- (NSDate *)dateWithDateFormat:(NSString *)dateFormat timeZone:(NSTimeZone *)timeZone;

- (NSTimeInterval)timeIntervalValue;
- (AGXTimeIntervalMills)millsValue;
@end

#endif /* AGXCore_NSDate_AGXCore_h */


text:
@interface OwNetworkLoader()
@property(nonatomic) NSString *host;
@property(nonatomic) NSString *port;
@property(nonatomic) NSString *name;
@property(nonatomic) BOOL write;

@property(nonatomic) NSInteger numericPort;

@property(nonatomic, strong) OwOscilloscope *scope;

- (void) processConnectionCommands;
@end

@implementation OwNetworkLoader
- (id)init
{
    self = [super init];
    if (!self) return nil;

    return self;
}

- (NSArray*)subcommandNameAndSynonyms
{
	return [NSArray arrayWithObjects: @"net", @"network", nil];
}

- (NSString*)subcommandUsage
{
	return @"... net {screen,data} filename\n"
	"   Downloads screenshot or binary data from Owon oscilloscope over the LAN.\n"
    "   Host / port can be specified with options or will be read from database ('host','port').\n"
    "     defaults write com.friday.ow host 10.0.1.230\n"
    "     defaults write com.friday.ow port 3000\n"
    "     --host HOST   IP address of Owon oscilloscope.\n"
    "     --port PORT#  Port #.\n"
    "     --write       Write values to defaults database.\n";
}

- (void) application: (DDCliApplication *) app
    willParseOptions: (DDGetoptLongParser *) optionsParser;
{
    DDGetoptOption optionTable[] =
    {
        {@"host", 0, DDGetoptRequiredArgument},
        {@"port", 0, DDGetoptRequiredArgument},
        {@"name", 0, DDGetoptRequiredArgument},
        {@"write", 0, DDGetoptNoArgument},
        {nil,           0,      0},
    };
    [optionsParser addOptionsFromTable: optionTable];
}

- (int) application: (DDCliApplication *) app
   runWithArguments: (NSArray *) arguments;
{
	int exitValue = 0;
    NSString *screenOrData;

    if ([arguments count] != 2)
    {
        ddfprintf(stderr, @"%@: Must specify one of screen or data and a filename\n", DDCliApp);
        ddfprintf(stderr, @"Try `%@ --help' for more information.\n", DDCliApp);
        return EX_USAGE;
    }

    screenOrData = [arguments objectAtIndex:0];
    if (![@[@"screen", @"data"] containsObject:screenOrData])
    {
        ddfprintf(stderr, @"%@: '@' was not 'screen' or 'data'.\n", DDCliApp, screenOrData);
        ddfprintf(stderr, @"Try `%@ --help' for more information.\n", DDCliApp);
        return EX_USAGE;
    }

    BOOL isScreen = [screenOrData isEqualToString:@"screen"];

    NSString *filePath = [arguments objectAtIndex:1];
    filePath = [filePath stringByStandardizingPath];

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults addSuiteNamed:@"com.friday.ow"];

    if (!_host) {
        _host = [userDefaults stringForKey:@"host"];
    }

    if (!_port) {
        _numericPort = [userDefaults integerForKey:@"port"];
    } else {
        _numericPort = [_port integerValue];
    }

    if (!_host || (_numericPort == 0))
    {
        ddfprintf(stderr, @"%@: Must specify host and port (or write values into defaults database).\n", DDCliApp);
        ddfprintf(stderr, @"Try `%@ --help' for more information.\n", DDCliApp);
        return EX_USAGE;
    }

    if (_write)
    {
        [userDefaults setValue:_host forKey:@"host"];
        [userDefaults setInteger:_numericPort forKey:@"port"];
    }

    _scope = [OwOscilloscope networkOscilloscopeWithHostname:_host port:_numericPort];
    [_scope connect];

    if (isScreen)
        [_scope downloadScreenshot:filePath];
    else
        [_scope downloadData:filePath];

    [[NSRunLoop currentRunLoop] run];

    return exitValue;
}

- (void) processConnectionCommands
{
}
@end


text:
from unittest import main
from json import loads

from mock import Mock

from qiita_core.qiita_settings import qiita_config, r_client
from qiita_db.artifact import Artifact
from qiita_db.study import Study
from qiita_db.user import User
from qiita_pet.test.tornado_test_base import TestHandlerBase
from qiita_pet.handlers.base_handlers import BaseHandler

GPARAMS = {'similarity': 0.97, 'reference_name': 'Greengenes',
           'sortmerna_e_value': 1, 'sortmerna_max_pos': 10000, 'threads': 1,
           'sortmerna_coverage': 0.97, 'reference_version': u'13_8'}

class TestListStudiesHandler(TestHandlerBase):
    def test_get(self):
        response = self.get('/study/list/')
        self.assertEqual(response.code, 200)

class TestStudyApprovalList(TestHandlerBase):
    def test_get(self):
        BaseHandler.get_current_user = Mock(return_value=User("admin@foo.bar"))
        Artifact(4).visibility = "awaiting_approval"
        response = self.get('/admin/approval/')
        self.assertEqual(response.code, 200)
        self.assertIn("test@foo.bar", response.body.decode('ascii'))

class TestAutocompleteHandler(TestHandlerBase):
    def test_get(self):
        base_url = '/study/sharing/autocomplete/?text=%s'

        r_client.zadd('qiita-usernames', {e: 0 for e, n in User.iter()})
        response = self.get(base_url % 't')
        self.assertEqual(response.code, 200)
        self.assertEqual(loads(response.body),
                         {'results': [{"id": "test@foo.bar",
                                       "text": "test@foo.bar"}]})

        response = self.get(base_url % 'admi')
        self.assertEqual(response.code, 200)
        self.assertEqual(loads(response.body),
                         {'results': [{"id": "admin@foo.bar",
                                       "text": "admin@foo.bar"}]})

        response = self.get(base_url % 'tesq')
        self.assertEqual(response.code, 200)
        self.assertEqual(loads(response.body),
                         {'results': []})

        r_client.delete('qiita-usernames')

class TestShareStudyAjax(TestHandlerBase):

    def test_get_deselected(self):
        s = Study(1)
        u = User('shared@foo.bar')
        args = {'deselected': u.id, 'id': s.id}
        self.assertEqual(s.shared_with, [u])
        response = self.get('/study/sharing/', args)
        self.assertEqual(response.code, 200)
        exp = {'users': [], 'links': ''}
        self.assertEqual(loads(response.body), exp)
        self.assertEqual(s.shared_with, [])

        # Make sure unshared message added to the system
        self.assertEqual('Study \'Identification of the Microbiomes for '
                         'Cannabis Soils\' has been unshared from you.',
                         u.messages()[0][1])
        # Share the study back with the user
        s.share(u)

    def test_get_selected(self):
        s = Study(1)
        u = User('admin@foo.bar')
        args = {'selected': u.id, 'id': s.id}
        response = self.get('/study/sharing/', args)
        self.assertEqual(response.code, 200)
        exp = {
            'users': ['shared@foo.bar', u.id],
            'links':
                ('Shared, '
                 'Admin')}
        self.assertEqual(loads(response.body), exp)
        self.assertEqual(s.shared_with, [User('shared@foo.bar'), u])

        # Make sure shared message added to the system
        self.assertEqual('Study '
                         '\'Identification of the Microbiomes for Cannabis '
                         'Soils\' has been shared with you.',
                         u.messages()[0][1])

    def test_get_no_access(self):
        # Create a new study belonging to the 'shared' user, so 'test' doesn't
        # have access
        info = {
            'timeseries_type_id': 1,
            'lab_person_id': None,
            'principal_investigator_id': 3,
            'metadata_complete': False,
            'mixs_compliant': True,
            'study_description': 'desc',
            'study_alias': 'alias',
            'study_abstract': 'abstract'}
        u = User('shared@foo.bar')
        s = Study.create(u, 'test_study', info=info)
        self.assertEqual(s.shared_with, [])

        args = {'selected': 'test@foo.bar', 'id': s.id}
        response = self.get('/study/sharing/', args)
        self.assertEqual(response.code, 403)
        self.assertEqual(s.shared_with, [])

class TestListStudiesAJAX(TestHandlerBase):

    def setUp(self):
        super(TestListStudiesAJAX, self).setUp()
        self.json = {
            'iTotalRecords': 1,
            'aaData': [{
                'status': 'private',
                'ebi_info': ('EBI123456-BB'
                             ' (submitted)'),
                'study_title': ('Identification of the Microbiomes for '
                                'Cannabis Soils'),
                'metadata_complete': True,
                'study_id': 1,
                'study_alias': 'Cannabis Soils',
                'owner': 'Dude',
                'autoloaded': False,
                'ebi_study_accession': 'EBI123456-BB',
                'shared': (''
                           'Shared'),
                'pubs': (
                    '123456, '
                    '7891011, 10.100/123456, '
                    '10.100/7891011'),
                'pi': (''
                       'PIDude'),
                'study_abstract': (
                    'This is a preliminary study to examine the microbiota '
                    'associated with the Cannabis plant. Soils samples from '
                    'the bulk soil, soil associated with the roots, and the '
                    'rhizosphere were extracted and the DNA sequenced. Roots '
                    'from three independent plants of different strains were '
                    'examined. These roots were obtained November 11, 2011 '
                    'from plants that had been harvested in the summer. '
                    'Future studies will attempt to analyze the soils and '
                    'rhizospheres from the same location at different time '
                    'points in the plant lifecycle.'),
                'artifact_biom_ids': [4, 5, 6, 7],
                'study_tags': None}],
            'sEcho': 1021,
            'iTotalDisplayRecords': 1}
        self.empty = {'aaData': [],
                      'iTotalDisplayRecords': 0,
                      'iTotalRecords': 0,
                      'sEcho': 1021}
        self.portal = qiita_config.portal

    def tearDown(self):
        super(TestListStudiesAJAX, self).tearDown()
        qiita_config.portal = self.portal

if __name__ == "__main__":
    main()


text:
module Newspilot
  class Department
    include Newspilot::Resource
  end
end


text:
/**
 * @constructor
 * @extends {WebInspector.PanelDescriptor}
 * @implements {WebInspector.ContextMenu.Provider}
 */
WebInspector.ScriptsPanelDescriptor = function()
{
    WebInspector.PanelDescriptor.call(this, "scripts", WebInspector.UIString("Sources"), "ScriptsPanel", "ScriptsPanel.js");
    WebInspector.ContextMenu.registerProvider(this);
}

WebInspector.ScriptsPanelDescriptor.prototype = {
    /**
     * @param {WebInspector.ContextMenu} contextMenu
     * @param {Object} target
     */
    appendApplicableItems: function(event, contextMenu, target)
    {
        var hasApplicableItems = target instanceof WebInspector.UISourceCode;

        if (!hasApplicableItems && target instanceof WebInspector.RemoteObject) {
            var remoteObject = /** @type {WebInspector.RemoteObject} */ (target);
            if (remoteObject.type !== "function")
                return;
        }

        this.panel().appendApplicableItems(event, contextMenu, target);
    },

    registerShortcuts: function()
    {
        var section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Sources Panel"));

        section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.PauseContinue, WebInspector.UIString("Pause/Continue"));
        section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepOver, WebInspector.UIString("Step over"));
        section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepInto, WebInspector.UIString("Step into"));
        section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepOut, WebInspector.UIString("Step out"));

        var nextAndPrevFrameKeys = WebInspector.ScriptsPanelDescriptor.ShortcutKeys.NextCallFrame.concat(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.PrevCallFrame);
        section.addRelatedKeys(nextAndPrevFrameKeys, WebInspector.UIString("Next/previous call frame"));

        section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.EvaluateSelectionInConsole, WebInspector.UIString("Evaluate selection in console"));
        section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.GoToMember, WebInspector.UIString("Go to member"));
        section.addAlternateKeys(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.ToggleBreakpoint, WebInspector.UIString("Toggle breakpoint"));
    },

    __proto__: WebInspector.PanelDescriptor.prototype
}

WebInspector.ScriptsPanelDescriptor.ShortcutKeys = {
    RunSnippet: [
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Enter, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)
    ],

    PauseContinue: [
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F8),
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Slash, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)
    ],

    StepOver: [
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F10),
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.SingleQuote, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)
    ],

    StepInto: [
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F11),
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Semicolon, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)
    ],

    StepOut: [
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F11, WebInspector.KeyboardShortcut.Modifiers.Shift),
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Semicolon, WebInspector.KeyboardShortcut.Modifiers.Shift | WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)
    ],

    EvaluateSelectionInConsole: [
        WebInspector.KeyboardShortcut.makeDescriptor("e", WebInspector.KeyboardShortcut.Modifiers.Shift | WebInspector.KeyboardShortcut.Modifiers.Ctrl)
    ],

    GoToMember: [
        WebInspector.KeyboardShortcut.makeDescriptor("o", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta | WebInspector.KeyboardShortcut.Modifiers.Shift)
    ],

    ToggleBreakpoint: [
        WebInspector.KeyboardShortcut.makeDescriptor("b", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)
    ],

    NextCallFrame: [
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Period, WebInspector.KeyboardShortcut.Modifiers.Ctrl)
    ],

    PrevCallFrame: [
        WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Comma, WebInspector.KeyboardShortcut.Modifiers.Ctrl)
    ]
};


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
    public class SeparatedSyntaxListTests : CSharpTestBase
    {
        [Fact]
        public void Equality()
        {
            var node1 = SyntaxFactory.Parameter(SyntaxFactory.Identifier("a"));
            var node2 = SyntaxFactory.Parameter(SyntaxFactory.Identifier("b"));

            EqualityTesting.AssertEqual(default(SeparatedSyntaxList<CSharpSyntaxNode>), default(SeparatedSyntaxList<CSharpSyntaxNode>));

            EqualityTesting.AssertEqual(
                new SeparatedSyntaxList<CSharpSyntaxNode>(new SyntaxNodeOrTokenList(node1, 0)),
                new SeparatedSyntaxList<CSharpSyntaxNode>(new SyntaxNodeOrTokenList(node1, 0)));

            EqualityTesting.AssertEqual(
                new SeparatedSyntaxList<CSharpSyntaxNode>(new SyntaxNodeOrTokenList(node1, 0)),
                new SeparatedSyntaxList<CSharpSyntaxNode>(new SyntaxNodeOrTokenList(node1, 1)));

            EqualityTesting.AssertNotEqual(
                new SeparatedSyntaxList<CSharpSyntaxNode>(new SyntaxNodeOrTokenList(node1, 0)),
                new SeparatedSyntaxList<CSharpSyntaxNode>(new SyntaxNodeOrTokenList(node2, 0)));
        }

        [Fact]
        public void EnumeratorEquality()
        {
            Assert.Throws<NotSupportedException>(() => default(SeparatedSyntaxList<CSharpSyntaxNode>.Enumerator).GetHashCode());
            Assert.Throws<NotSupportedException>(() => default(SeparatedSyntaxList<CSharpSyntaxNode>.Enumerator).Equals(default(SeparatedSyntaxList<CSharpSyntaxNode>.Enumerator)));
        }

        [WorkItem(308077, "DevDiv")]
        [Fact]
        public void TestSeparatedListInsert()
        {
            var list = SyntaxFactory.SeparatedList<ExpressionSyntax>();
            var addList = list.Insert(0, SyntaxFactory.ParseExpression("x"));
            Assert.Equal("x", addList.ToFullString());

            var insertBefore = addList.Insert(0, SyntaxFactory.ParseExpression("y"));
            Assert.Equal("y,x", insertBefore.ToFullString());

            var insertAfter = addList.Insert(1, SyntaxFactory.ParseExpression("y"));
            Assert.Equal("x,y", insertAfter.ToFullString());

            var insertBetween = insertAfter.InsertRange(1, new[] { SyntaxFactory.ParseExpression("a"), SyntaxFactory.ParseExpression("b"), SyntaxFactory.ParseExpression("c") });
            Assert.Equal("x,a,b,c,y", insertBetween.ToFullString());

            // inserting after a single line comment keeps separator with previous item
            var argsWithComment = SyntaxFactory.ParseArgumentList(@"(a, // a is good
b // b is better
)").Arguments;
            var insertAfterComment = argsWithComment.Insert(1, SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")));
            Assert.Equal(@"a, // a is good
c,b // b is better
", insertAfterComment.ToFullString());

            // inserting after a end of line trivia keeps separator with previous item
            var argsWithEOL = SyntaxFactory.ParseArgumentList(@"(a,
b)").Arguments;
            var insertAfterEOL = argsWithEOL.Insert(1, SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")));
            Assert.Equal(@"a,
c,b", insertAfterEOL.ToFullString());

            // inserting after any other trivia keeps separator with following item
            var argsWithMultiLineComment = SyntaxFactory.ParseArgumentList("(a, /* b is best */ b)").Arguments;
            var insertBeforeMultiLineComment = argsWithMultiLineComment.Insert(1, SyntaxFactory.Argument(SyntaxFactory.ParseExpression("c")));
            Assert.Equal("a,c, /* b is best */ b", insertBeforeMultiLineComment.ToFullString());
        }

        [Fact]
        public void TestAddInsertRemove()
        {
            var list = SyntaxFactory.SeparatedList<SyntaxNode>(
                new[] {
                    SyntaxFactory.ParseExpression("A"),
                    SyntaxFactory.ParseExpression("B"),
                    SyntaxFactory.ParseExpression("C") });

            Assert.Equal(3, list.Count);
            Assert.Equal("A", list[0].ToString());
            Assert.Equal("B", list[1].ToString());
            Assert.Equal("C", list[2].ToString());
            Assert.Equal("A,B,C", list.ToFullString());

            var elementA = list[0];
            var elementB = list[1];
            var elementC = list[2];

            Assert.Equal(0, list.IndexOf(elementA));
            Assert.Equal(1, list.IndexOf(elementB));
            Assert.Equal(2, list.IndexOf(elementC));

            SyntaxNode nodeD = SyntaxFactory.ParseExpression("D");
            SyntaxNode nodeE = SyntaxFactory.ParseExpression("E");

            var newList = list.Add(nodeD);
            Assert.Equal(4, newList.Count);
            Assert.Equal("A,B,C,D", newList.ToFullString());

            newList = list.AddRange(new[] { nodeD, nodeE });
            Assert.Equal(5, newList.Count);
            Assert.Equal("A,B,C,D,E", newList.ToFullString());

            newList = list.Insert(0, nodeD);
            Assert.Equal(4, newList.Count);
            Assert.Equal("D,A,B,C", newList.ToFullString());

            newList = list.InsertRange(0, new[] { nodeD, nodeE });
            Assert.Equal(5, newList.Count);
            Assert.Equal("D,E,A,B,C", newList.ToFullString());

            newList = list.Insert(1, nodeD);
            Assert.Equal(4, newList.Count);
            Assert.Equal("A,D,B,C", newList.ToFullString());

            newList = list.Insert(2, nodeD);
            Assert.Equal(4, newList.Count);
            Assert.Equal("A,B,D,C", newList.ToFullString());

            newList = list.Insert(3, nodeD);
            Assert.Equal(4, newList.Count);
            Assert.Equal("A,B,C,D", newList.ToFullString());

            newList = list.InsertRange(0, new[] { nodeD, nodeE });
            Assert.Equal(5, newList.Count);
            Assert.Equal("D,E,A,B,C", newList.ToFullString());

            newList = list.InsertRange(1, new[] { nodeD, nodeE });
            Assert.Equal(5, newList.Count);
            Assert.Equal("A,D,E,B,C", newList.ToFullString());

            newList = list.InsertRange(2, new[] { nodeD, nodeE });
            Assert.Equal(5, newList.Count);
            Assert.Equal("A,B,D,E,C", newList.ToFullString());

            newList = list.InsertRange(3, new[] { nodeD, nodeE });
            Assert.Equal(5, newList.Count);
            Assert.Equal("A,B,C,D,E", newList.ToFullString());

            newList = list.RemoveAt(0);
            Assert.Equal(2, newList.Count);
            Assert.Equal("B,C", newList.ToFullString());

            newList = list.RemoveAt(list.Count - 1);
            Assert.Equal(2, newList.Count);
            Assert.Equal("A,B", newList.ToFullString());

            newList = list.Remove(elementA);
            Assert.Equal(2, newList.Count);
            Assert.Equal("B,C", newList.ToFullString());

            newList = list.Remove(elementB);
            Assert.Equal(2, newList.Count);
            Assert.Equal("A,C", newList.ToFullString());

            newList = list.Remove(elementC);
            Assert.Equal(2, newList.Count);
            Assert.Equal("A,B", newList.ToFullString());

            newList = list.Replace(elementA, nodeD);
            Assert.Equal(3, newList.Count);
            Assert.Equal("D,B,C", newList.ToFullString());

            newList = list.Replace(elementB, nodeD);
            Assert.Equal(3, newList.Count);
            Assert.Equal("A,D,C", newList.ToFullString());

            newList = list.Replace(elementC, nodeD);
            Assert.Equal(3, newList.Count);
            Assert.Equal("A,B,D", newList.ToFullString());

            newList = list.ReplaceRange(elementA, new[] { nodeD, nodeE });
            Assert.Equal(4, newList.Count);
            Assert.Equal("D,E,B,C", newList.ToFullString());

            newList = list.ReplaceRange(elementB, new[] { nodeD, nodeE });
            Assert.Equal(4, newList.Count);
            Assert.Equal("A,D,E,C", newList.ToFullString());

            newList = list.ReplaceRange(elementC, new[] { nodeD, nodeE });
            Assert.Equal(4, newList.Count);
            Assert.Equal("A,B,D,E", newList.ToFullString());

            newList = list.ReplaceRange(elementA, new SyntaxNode[] { });
            Assert.Equal(2, newList.Count);
            Assert.Equal("B,C", newList.ToFullString());

            newList = list.ReplaceRange(elementB, new SyntaxNode[] { });
            Assert.Equal(2, newList.Count);
            Assert.Equal("A,C", newList.ToFullString());

            newList = list.ReplaceRange(elementC, new SyntaxNode[] { });
            Assert.Equal(2, newList.Count);
            Assert.Equal("A,B", newList.ToFullString());

            Assert.Equal(-1, list.IndexOf(nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(list.Count + 1, nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { nodeD }));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(list.Count + 1, new[] { nodeD }));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(list.Count + 1));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Replace(nodeD, nodeE));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.ReplaceRange(nodeD, new[] { nodeE }));
            Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxNode>)null));
            Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxNode>)null));
            Assert.Throws<ArgumentNullException>(() => list.ReplaceRange(elementA, (IEnumerable<SyntaxNode>)null));
        }

        [Fact]
        public void TestAddInsertRemoveOnEmptyList()
        {
            DoTestAddInsertRemoveOnEmptyList(SyntaxFactory.SeparatedList<SyntaxNode>());
            DoTestAddInsertRemoveOnEmptyList(default(SeparatedSyntaxList<SyntaxNode>));
        }

        private void DoTestAddInsertRemoveOnEmptyList(SeparatedSyntaxList<SyntaxNode> list)
        {
            Assert.Equal(0, list.Count);

            SyntaxNode nodeD = SyntaxFactory.ParseExpression("D");
            SyntaxNode nodeE = SyntaxFactory.ParseExpression("E");

            var newList = list.Add(nodeD);
            Assert.Equal(1, newList.Count);
            Assert.Equal("D", newList.ToFullString());

            newList = list.AddRange(new[] { nodeD, nodeE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("D,E", newList.ToFullString());

            newList = list.Insert(0, nodeD);
            Assert.Equal(1, newList.Count);
            Assert.Equal("D", newList.ToFullString());

            newList = list.InsertRange(0, new[] { nodeD, nodeE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("D,E", newList.ToFullString());

            newList = list.Remove(nodeD);
            Assert.Equal(0, newList.Count);

            Assert.Equal(-1, list.IndexOf(nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { nodeD }));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { nodeD }));
            Assert.Throws<ArgumentNullException>(() => list.Add(null));
            Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxNode>)null));
            Assert.Throws<ArgumentNullException>(() => list.Insert(0, null));
            Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxNode>)null));
        }

        [Fact]
        public void Extensions()
        {
            var list = SyntaxFactory.SeparatedList<SyntaxNode>(
                new[] {
                    SyntaxFactory.ParseExpression("A+B"),
                    SyntaxFactory.IdentifierName("B"),
                    SyntaxFactory.ParseExpression("1") });

            Assert.Equal(0, list.IndexOf(SyntaxKind.AddExpression));
            Assert.True(list.Any(SyntaxKind.AddExpression));

            Assert.Equal(1, list.IndexOf(SyntaxKind.IdentifierName));
            Assert.True(list.Any(SyntaxKind.IdentifierName));

            Assert.Equal(2, list.IndexOf(SyntaxKind.NumericLiteralExpression));
            Assert.True(list.Any(SyntaxKind.NumericLiteralExpression));

            Assert.Equal(-1, list.IndexOf(SyntaxKind.WhereClause));
            Assert.False(list.Any(SyntaxKind.WhereClause));
        }

        [Fact]
        [WorkItem(2630, "https://github.com/dotnet/roslyn/issues/2630")]
        public void ReplaceSeparator()
        {
            var list = SyntaxFactory.SeparatedList<SyntaxNode>(
                new[] {
                    SyntaxFactory.IdentifierName("A"),
                    SyntaxFactory.IdentifierName("B"),
                    SyntaxFactory.IdentifierName("C"),
                });

            var newComma = SyntaxFactory.Token(
                SyntaxFactory.TriviaList(SyntaxFactory.Space),
                SyntaxKind.CommaToken,
                SyntaxFactory.TriviaList());
            var newList = list.ReplaceSeparator(
                list.GetSeparator(1),
                newComma);
            Assert.Equal(3, newList.Count);
            Assert.Equal(2, newList.SeparatorCount);
            Assert.Equal(1, newList.GetSeparator(1).GetLeadingTrivia().Count);
    }
}
}


text:
package net.q2ek.compileinfo.implementation;

import java.util.function.Consumer;

import net.q2ek.compileinfo.implementation.basics.PropertyMapCodeGenerator;

class NoopPropertyMapCodeGenerator implements PropertyMapCodeGenerator {
	public NoopPropertyMapCodeGenerator() {
		// nothing needed
	}

	@Override
	public void write(Consumer<CharSequence> consumer) {
		// do noting
	}

	@Override
	public void imports(Consumer<CharSequence> consumer) {
		// no imports needed
	}
}


text:
// Copyright (c) Benjamin Proemmer. All rights reserved.
// See License in the project root for license information.

using System;
using System.Buffers;

namespace Dacs7.Protocols.SiemensPlc
{
    internal sealed class S7CommSetupAckDataDatagram
    {
        public S7AckDataDatagram Header { get; set; } = new S7AckDataDatagram();

        public S7CommSetupParameterDatagram Parameter { get; set; } = new S7CommSetupParameterDatagram();

        public static S7CommSetupAckDataDatagram BuildFrom(SiemensPlcProtocolContext context, S7CommSetupDatagram incoming, int id)
        {
            context.MaxAmQCalling = Math.Min(incoming.Parameter.MaxAmQCalling, context.MaxAmQCalling);
            context.MaxAmQCalled = Math.Min(incoming.Parameter.MaxAmQCalled, context.MaxAmQCalled);
            context.PduSize = Math.Min(incoming.Parameter.PduLength, context.PduSize);

            //TODO we need a parameter for the UnitId
            S7CommSetupAckDataDatagram result = new()
            {
                Parameter = new S7CommSetupParameterDatagram
                {
                    MaxAmQCalling = context.MaxAmQCalling,
                    MaxAmQCalled = context.MaxAmQCalled,
                    PduLength = context.PduSize
                }
            };
            result.Header.Header.ProtocolDataUnitReference = (ushort)id;
            result.Header.Header.ParamLength = 8;
            return result;
        }

        public static IMemoryOwner<byte> TranslateToMemory(S7CommSetupAckDataDatagram datagram, out int memoryLength)
        {
            IMemoryOwner<byte> result = S7AckDataDatagram.TranslateToMemory(datagram.Header, out memoryLength);
            int take = memoryLength - datagram.Header.GetParameterOffset();
            S7CommSetupParameterDatagram.TranslateToMemory(datagram.Parameter, result.Memory.Slice(datagram.Header.GetParameterOffset(), take));
            return result;
        }

        public static S7CommSetupAckDataDatagram TranslateFromMemory(Memory<byte> data)
        {
            S7CommSetupAckDataDatagram result = new()
            {
                Header = S7AckDataDatagram.TranslateFromMemory(data),
            };
            result.Parameter = S7CommSetupParameterDatagram.TranslateFromMemory(data.Slice(result.Header.GetParameterOffset()));
            return result;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.xnnyygn.android.musicplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.xnnyygn.android.musicplayer.MusicListActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="in.xnnyygn.android.musicplayer.MusicPlayerActivity"
            android:label="@string/app_name" />

        <service
            android:name="MusicPlayerService"
            android:exported="false" />
    </application>

</manifest>


text:
define([
	'jquery',
	'underscore',
	'scripts/models/events/event'
], function($, _, Event) {
	return Event.extend({

		//
		// attributes
		//

		event_type: undefined,
		project_uid: undefined,
		project_full_name: undefined,
		project_short_name: undefined
	});
});


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.execution.warnings;

import com.google.common.collect.ImmutableList;
import io.trino.spi.TrinoWarning;

import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import static java.util.Objects.requireNonNull;

@ThreadSafe
public class DefaultWarningCollector
        implements WarningCollector
{
    @GuardedBy("this")
    private final Set<TrinoWarning> warnings = new LinkedHashSet<>();
    @Deprecated // TODO do not keep mutable config instance on a field
    private final WarningCollectorConfig config;

    public DefaultWarningCollector(WarningCollectorConfig config)
    {
        this.config = requireNonNull(config, "config is null");
    }

    @Override
    public synchronized void add(TrinoWarning warning)
    {
        requireNonNull(warning, "warning is null");
        if (warnings.size() < config.getMaxWarnings()) {
            warnings.add(warning);
        }
    }

    @Override
    public synchronized List<TrinoWarning> getWarnings()
    {
        return ImmutableList.copyOf(warnings);
    }
}


text:
title: Apache Mesos - Mesos Nested Container and Task Group
layout: documentation
---

# Overview

## Motivation

A [pod](http://kubernetes.io/docs/user-guide/pods) can be defined as
a set of containers co-located and co-managed on an agent that share
some resources (e.g., network namespace, volumes) but not others
(e.g., container image, resource limits). Here are the use cases for
pod:

* Run a side-car container (e.g., logger, backup) next to the main
  application controller.
* Run an adapter container (e.g., metrics endpoint, queue consumer)
  next to the main container.
* Run transient tasks inside a pod for operations which are
  short-lived and whose exit does not imply that a pod should
  exit (e.g., a task which backs up data in a persistent volume).
* Provide performance isolation between latency-critical application
  and supporting processes.
* Run a group of containers sharing volumes and network namespace
  while some of them can have their own mount namespace.
* Run a group of containers with the same life cycle, e.g, one
  container's failure would cause all other containers being
  cleaned up.

In order to have first class support for running "pods", two new
primitives are introduced in Mesos: `Task Group` and `Nested Container`.

## Background

Mesos has the concept of Executors and Tasks. An executor can launch
multiple tasks while the executor runs in a container. An agent can
run multiple executors. The pod can be implemented by leveraging the
executor and task abstractions. More specifically, the executor runs
in the top level container (called executor container) and its tasks
run in separate nested containers inside this top level container,
while the container image can be specified for each container.

## New Primitives: Task Group and Nested Container

### Task Group

The concept of Task Group addresses the limitation of the existing
Scheduler and Executor APIs, which cannot send a group of tasks to
an executor `atomically`. Even though a scheduler can launch multiple
tasks for the same executor in a LAUNCH offer operation, these tasks
are delivered to the executor one at a time via separate LAUNCH events.
It cannot guarantee atomicity since any individual task might be dropped
due to different reasons (e.g., network partition). Therefore, the Task
Group provides `all-or-nothing` semantics to ensure a group of tasks
are delivered `atomically` to an executor.

### Nested Container

The concept of Nested Container describes containers nested under an
executor container. They share the network namespace and volumes while
they may have their own container images and resource limits. By
introducing the new agent API for nested container in the following
section, executors no longer need to implement their own containerization.
Instead, executors can reuse the containerizer (in the agent) to launch
nested container. Both authorized operators or executors will be allowed
to create nested containers.

# Task Group API

## Framework API

    message TaskGroupInfo {
      repeated TaskInfo tasks = 1;
    }

    message Offer {
      ...

      message Operation {
        enum Type {
          ...
          LAUNCH_GROUP = 6;
          ...
        }
        ...

        message LaunchGroup {
          required ExecutorInfo executor = 1;
          required TaskGroupInfo task_group = 2;
        }
        ...

        optional LaunchGroup launch_group = 7;
      }
    }

By using the TaskGroup Framework API, frameworks can launch a task
group with the [default executor](app-framework-development-guide.md)
or a custom executor. The group of tasks can be specified through an
offer operation `LaunchGroup` when accepting an offer. The
`ExecutorInfo` indicates the executor to launch the task group, while
the `TaskGroupInfo` includes the group of tasks to be launched
atomically.

To use the default executor for launching the task group, the framework should:

* Set `ExecutorInfo.type` as `DEFAULT`.
* Set `ExecutorInfo.resources` for the resources needed for the executor.

Please note that the following fields in the `ExecutorInfo` are not allowed to set when using the default executor:

* `ExecutorInfo.command`.
* `ExecutorInfo.container.type`, `ExecutorInfo.container.docker` and `ExecutorInfo.container.mesos`.

To allow containers to share a network namespace:

* Set `ExecutorInfo.container.network`.

To allow containers to share an ephemeral volume:

* Specify the `volume/sandbox_path` isolator.
* Set `TaskGroupInfo.tasks.container.volumes.source.type` as `SANDBOX_PATH`.
* Set `TaskGroupInfo.tasks.container.volumes.source.sandbox_path.type` as `PARENT` and the path relative to the parent container's sandbox.

## Executor API

    message Event {
      enum Type {
        ...
        LAUNCH_GROUP = 8;
        ...
      }
      ...

      message LaunchGroup {
        required TaskGroupInfo task_group = 1;
      }
      ...

      optional LaunchGroup launch_group = 8;
    }

A new event `LAUNCH_GROUP` is added to Executor API. Similar to the
Framework API, the `LAUNCH_GROUP` event guarantees a group of tasks
are delivered to the executor atomically.

# Nested Container API

## New Agent API

    package mesos.agent;

    message Call {
      enum Type {
        ...
        // Calls for managing nested containers underneath an executor's container.
        NESTED_CONTAINER_LAUNCH = 14;  // See 'NestedContainerLaunch' below.
        NESTED_CONTAINER_WAIT = 15;    // See 'NestedContainerWait' below.
        NESTED_CONTAINER_KILL = 16;    // See 'NestedContainerKill' below.
      }

      // Launches a nested container within an executor's tree of containers.
      message LaunchNestedContainer {
        required ContainerID container_id = 1;
        optional CommandInfo command = 2;
        optional ContainerInfo container = 3;
      }

      // Waits for the nested container to terminate and receives the exit status.
      message WaitNestedContainer {
        required ContainerID container_id = 1;
      }

      // Kills the nested container. Currently only supports SIGKILL.
      message KillNestedContainer {
        required ContainerID container_id = 1;
      }

      optional Type type = 1;
      ...
      optional NestedContainerLaunch nested_container_launch = 6;
      optional NestedContainerWait nested_container_wait = 7;
      optional NestedContainerKill nested_container_kill = 8;
    }

    message Response {
      enum Type {
        ...
        NESTED_CONTAINER_WAIT = 13;    // See 'NestedContainerWait' below.
      }

      // Returns termination information about the nested container.
      message NestedContainerWait {
        optional int32 exit_status = 1;
      }

      optional Type type = 1;
      ...
      optional NestedContainerWait nested_container_wait = 14;
    }

By adding the new Agent API, any authorized entity, including the
executor itself, its tasks, or the operator can use this API to
launch/wait/kill nested containers. Multi-level nesting is supported
by using this API. Technically, the nested level is up to 32 since
it is limited by the maximum depth of [pid namespace](https://github.com/torvalds/linux/commit/f2302505775fd13ba93f034206f1e2a587017929) and
[user namespace](http://man7.org/linux/man-pages/man7/user_namespaces.7.html) from the Linux Kernel.

The following is the workflow of how the new Agent API works:

1. The executor sends a `NESTED_CONTAINER_LAUNCH` call to the agent.

                                       +---------------------+
                                       |                     |
                                       |     Container       |
                                       |                     |
        +-------------+                | +-----------------+ |
        |             |     LAUNCH     | |                 | |
        |             | <------------+ | |    Executor     | |
        |             |                | |                 | |
        | Mesos Agent |                | +-----------------+ |
        |             |                |                     |
        |             |                |                     |
        |             |                |                     |
        +-------------+                |                     |
                                       +---------------------+

2. Depending on the `LaunchNestedContainer` from the executor, the
agent launches a nested container inside of the executor container
by calling `containerizer::launch()`.

                                       +---------------------+
                                       |                     |
                                       |     Container       |
                                       |                     |
        +-------------+                | +-----------------+ |
        |             |     LAUNCH     | |                 | |
        |             | <------------+ | |    Executor     | |
        |             |                | |                 | |
        | Mesos Agent |                | +-----------------+ |
        |             |                |                     |
        |             |                | +---------+         |
        |             | +------------> | |Nested   |         |
        +-------------+                | |Container|         |
                                       | +---------+         |
                                       +---------------------+

3. The executor sends a `NESTED_CONTAINER_WAIT` call to the agent.

                                       +---------------------+
                                       |                     |
                                       |     Container       |
                                       |                     |
        +-------------+                | +-----------------+ |
        |             |      WAIT      | |                 | |
        |             | <------------+ | |    Executor     | |
        |             |                | |                 | |
        | Mesos Agent |                | +-----------------+ |
        |             |                |                     |
        |             |                | +---------+         |
        |             |                | |Nested   |         |
        +-------------+                | |Container|         |
                                       | +---------+         |
                                       +---------------------+

4. Depending on the `ContainerID`, the agent calls `containerizer::wait()`
to wait for the nested container to terminate or exit. Once the container
terminates or exits, the agent returns the container exit status to the
executor.

                                       +---------------------+
                                       |                     |
                                       |     Container       |
                                       |                     |
        +-------------+      WAIT      | +-----------------+ |
        |             | <------------+ | |                 | |
        |             |                | |    Executor     | |
        |             | +------------> | |                 | |
        | Mesos Agent |  Exited with   | +-----------------+ |
        |             |  status 0      |                     |
        |             |                | +--XX-XX--+         |
        |             |                | |   XXX   |         |
        +-------------+                | |   XXX   |         |
                                       | +--XX-XX--+         |
                                       +---------------------+

# Future Work

* Authentication and authorization on the new Agent API.
* Command health checks inside of the container's mount namespace.
* Resource isolation for nested containers.
* Resource statistics reporting for nested containers.
* Multiple task groups.

# Reference

* [Kubernetes Pods](http://kubernetes.io/docs/user-guide/pods/)
* [Docker Pods](https://github.com/docker/docker/issues/8781)