text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace RCCM.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RCCM.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap arrow_down {
            get {
                object obj = ResourceManager.GetObject("arrow-down", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap arrow_left {
            get {
                object obj = ResourceManager.GetObject("arrow-left", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap arrow_right {
            get {
                object obj = ResourceManager.GetObject("arrow-right", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap arrow_up {
            get {
                object obj = ResourceManager.GetObject("arrow-up", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap drexel_logo {
            get {
                object obj = ResourceManager.GetObject("drexel_logo", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap estop {
            get {
                object obj = ResourceManager.GetObject("estop", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap faa_logo {
            get {
                object obj = ResourceManager.GetObject("faa_logo", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap pause {
            get {
                object obj = ResourceManager.GetObject("pause", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap play {
            get {
                object obj = ResourceManager.GetObject("play", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap RCCM_splashscreen_draft3 {
            get {
                object obj = ResourceManager.GetObject("RCCM splashscreen draft3", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap record {
            get {
                object obj = ResourceManager.GetObject("record", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap save {
            get {
                object obj = ResourceManager.GetObject("save", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap snap {
            get {
                object obj = ResourceManager.GetObject("snap", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap stop {
            get {
                object obj = ResourceManager.GetObject("stop", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap wjhtc {
            get {
                object obj = ResourceManager.GetObject("wjhtc", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
    }
}


text:
import java.io.IOException;

class InheritedDocInThrows extends A{
  /**
   * @throws IOException {@inheritDoc}
   */
  void foo() throws IOException {
    super.foo();
  }
}

class A {
  /**
   * @throws IOException la-la-la
   */
  void foo() throws IOException {
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.df.restypass.command;

import com.github.df.restypass.base.RestyPassFactory;
import com.github.df.restypass.command.update.UpdateCommandConfig;
import com.github.df.restypass.command.update.Updater;
import com.github.df.restypass.lb.LoadBalancer;
import com.github.df.restypass.lb.rule.VersionRule;

import java.util.List;

/**
 * Resty请求的配置
 * Created by darrenfu on 17-6-21.
 */
@SuppressWarnings("unused")
public interface RestyCommandConfig extends Updater<UpdateCommandConfig> {

    /**
     * 获取服务名称
     *
     * @return the service name
     */
    String getServiceName();

    /**
     * 获取服务URL
     *
     * @return service URL
     */
    String[] getUrl();

    /**
     * 设置服务名称
     *
     * @param serviceName the service name
     */
    void setServiceName(String serviceName);

    /**
     * 设置服务URL
     *
     * @param url the service url
     */
    void setUrl(String[] url);

    /**
     * 断路器是否启用
     * 启用时在达到一定条件时,断路器会自动熔断服务接口
     *
     * @return the boolean
     */
    boolean isCircuitBreakEnabled();

    /**
     * 是否强制熔断
     * <p>
     * true:强制熔断服务,直到设置为false
     *
     * @return the boolean
     */
    boolean isForceBreakEnabled();

    /**
     * 是否启用降级服务
     * true:启用降级服务,熔断后自动调用降级服务并返回结果
     *
     * @return the boolean
     */
    boolean isFallbackEnabled();

    /**
     * 降级服务Class
     *
     * @return the fallback class
     */
    Class getFallbackClass();

    /**
     * 降级服务Bean
     *
     * @return the fallback
     */
    String getFallbackBean();

    /**
     * 重试次数
     *
     * @return the retry
     */
    int getRetry();

    /**
     * 配置使用的负载均衡器
     *
     * @return the load balancer
     */
    Class<? extends LoadBalancer> getLoadBalancer();

    /**
     * 限流
     *
     * @return the limit
     */
    int getLimit();

    /**
     * 基础工厂类
     *
     * @return the factory
     */
    Class<? extends RestyPassFactory> getFactory();

    /**
     * 版本控制
     *
     * @return the version
     */
    List<VersionRule> getVersion();

    /**
     * Sets circuit break enabled.
     *
     * @param enableCircuitBreak the enable circuit break
     */
    void setCircuitBreakEnabled(boolean enableCircuitBreak);

    /**
     * Sets force break enabled.
     *
     * @param forceBreakEnabled the force break enabled
     */
    void setForceBreakEnabled(boolean forceBreakEnabled);

    /**
     * Sets fallback enabled.
     *
     * @param enableFallback the enable fallback
     */
    void setFallbackEnabled(boolean enableFallback);

    /**
     * Sets fallback class.
     *
     * @param fallbackClass the fallback class
     */
    void setFallbackClass(Class fallbackClass);

    /**
     * Sets fallback bean.
     *
     * @param fallbackBean the fallback bean
     */
    void setFallbackBean(String fallbackBean);

    /**
     * Sets retry.
     *
     * @param retry the retry
     */
    void setRetry(int retry);

    /**
     * Sets load balancer.
     *
     * @param loadBalancer the load balancer
     */
    void setLoadBalancer(Class<? extends LoadBalancer> loadBalancer);

    /**
     * Sets limit.
     *
     * @param limit the limit
     */
    void setLimit(int limit);

    /**
     * Sets factory.
     *
     * @param factoryClz the factory clz
     */
    void setFactory(Class<? extends RestyPassFactory> factoryClz);

    /**
     * Sets version.
     *
     * @param version the version
     */
    void setVersion(List<VersionRule> version);

    /**
     * The type Default resty command config.
     */
    class DefaultRestyCommandConfig implements RestyCommandConfig {

        private String serviceName;

        private String[] url;

        private boolean circuitBreakEnabled = true;

        private boolean forceBreakEnabled = false;

        private boolean fallbackEnabled = true;

        private Class fallbackClass;

        private String fallbackBean;

        private int retry = 1;

        private Class<? extends LoadBalancer> loadBalancer;

        private int limit = -1;

        private List<VersionRule> version;

        private Class<? extends RestyPassFactory> factory;

        @Override
        public String getServiceName() {
            return serviceName;
        }

        @Override
        public String[] getUrl() {
            return url;
        }

        @Override
        public void setServiceName(String serviceName) {
            this.serviceName = serviceName;
        }

        @Override
        public void setUrl(String[] url) {
            this.url = url;
        }

        @Override
        public boolean isCircuitBreakEnabled() {
            return circuitBreakEnabled;
        }

        @Override
        public boolean isFallbackEnabled() {
            return fallbackEnabled;
        }

        @Override
        public Class getFallbackClass() {
            return fallbackClass;
        }

        @Override
        public String getFallbackBean() {
            return fallbackBean;
        }

        @Override
        public int getRetry() {
            return retry;
        }

        @Override
        public List<VersionRule> getVersion() {
            return version;
        }

        @Override
        public void setCircuitBreakEnabled(boolean enableCircuitBreak) {
            this.circuitBreakEnabled = enableCircuitBreak;
        }

        @Override
        public void setFallbackEnabled(boolean enableFallback) {
            this.fallbackEnabled = enableFallback;
        }

        @Override
        public void setFallbackClass(Class fallbackClass) {
            this.fallbackClass = fallbackClass;
        }

        @Override
        public void setFallbackBean(String fallbackBean) {
            this.fallbackBean = fallbackBean;
        }

        @Override
        public void setRetry(int retry) {
            this.retry = retry;
        }

        @Override
        public boolean isForceBreakEnabled() {
            return forceBreakEnabled;
        }

        @Override
        public void setForceBreakEnabled(boolean forceBreakEnabled) {
            this.forceBreakEnabled = forceBreakEnabled;
        }

        @Override
        public Class<? extends LoadBalancer> getLoadBalancer() {
            return loadBalancer;
        }

        @Override
        public void setLoadBalancer(Class<? extends LoadBalancer> loadBalancer) {
            this.loadBalancer = loadBalancer;
        }

        @Override
        public int getLimit() {
            return limit;
        }

        @Override
        public void setLimit(int limit) {
            this.limit = limit;
        }

        @Override
        public Class<? extends RestyPassFactory> getFactory() {
            return factory;
        }

        @Override
        public void setFactory(Class<? extends RestyPassFactory> factory) {
            this.factory = factory;
        }

        @Override
        public void setVersion(List<VersionRule> version) {
            this.version = version;
        }

        @Override
        public boolean refresh(UpdateCommandConfig updateCommandConfig) {

            if (updateCommandConfig.getCircuitBreakEnabled() != null) {
                this.setCircuitBreakEnabled(updateCommandConfig.getCircuitBreakEnabled());
            }
            if (updateCommandConfig.getFallbackEnabled() != null) {
                this.setFallbackEnabled(updateCommandConfig.getFallbackEnabled());
            }
            return true;
        }
    }
}


text:
var _ = require('lodash');

module.exports = function hasArgument(args, argument) {
  return _.some(args, function (arg) {
    return _.startsWith(arg, argument);
  });
};


text:
using System;
using Xunit;
using LanguageExt;
using LanguageExt.Common;
using static LanguageExt.Prelude;

namespace LanguageExt.Tests.Transformer.Traverse.OptionAsyncT.Sync
{
    public class TryOptionOptionAsync
    {
        [Fact]
        public async void FailIsSomeFail()
        {
            var ma = TryOption<OptionAsync<int>>(new Exception("fail"));
            var mb = ma.Sequence();
            var mc = SomeAsync(TryOption<int>(new Exception("fail")));

            var mr = await (mb == mc);

            Assert.True(mr);
        }

        [Fact]
        public async void SuccNoneIsNone()
        {
            var ma = TryOption<OptionAsync<int>>(None);
            var mb = ma.Sequence();
            var mc = OptionAsync<TryOption<int>>.None;

            var mr = await (mb == mc);

            Assert.True(mr);
        }

        [Fact]
        public async void SuccSomeIsSomeSucc()
        {
            var ma = TryOption<OptionAsync<int>>(SomeAsync(1234));
            var mb = ma.Sequence();
            var mc = SomeAsync(TryOption(1234));

            var mr = await (mb == mc);

            Assert.True(mr);
        }
    }
}


text:
namespace lldb_private {

class CPlusPlusLanguage : public Language {
public:
  class MethodName {
  public:
    MethodName()
        : m_full(), m_basename(), m_context(), m_arguments(), m_qualifiers(),
          m_parsed(false), m_parse_error(false) {}

    MethodName(const ConstString &s)
        : m_full(s), m_basename(), m_context(), m_arguments(), m_qualifiers(),
          m_parsed(false), m_parse_error(false) {}

    void Clear();

    bool IsValid() {
      if (!m_parsed)
        Parse();
      if (m_parse_error)
        return false;
      return (bool)m_full;
    }

    const ConstString &GetFullName() const { return m_full; }

    std::string GetScopeQualifiedName();

    llvm::StringRef GetBasename();

    llvm::StringRef GetContext();

    llvm::StringRef GetArguments();

    llvm::StringRef GetQualifiers();

  protected:
    void Parse();
    bool TrySimplifiedParse();

    ConstString m_full; // Full name:
                        // "lldb::SBTarget::GetBreakpointAtIndex(unsigned int)
                        // const"
    llvm::StringRef m_basename;   // Basename:     "GetBreakpointAtIndex"
    llvm::StringRef m_context;    // Decl context: "lldb::SBTarget"
    llvm::StringRef m_arguments;  // Arguments:    "(unsigned int)"
    llvm::StringRef m_qualifiers; // Qualifiers:   "const"
    bool m_parsed;
    bool m_parse_error;
  };

  CPlusPlusLanguage() = default;

  ~CPlusPlusLanguage() override = default;

  lldb::LanguageType GetLanguageType() const override {
    return lldb::eLanguageTypeC_plus_plus;
  }

  std::unique_ptr<TypeScavenger> GetTypeScavenger() override;
  lldb::TypeCategoryImplSP GetFormatters() override;

  HardcodedFormatters::HardcodedSummaryFinder GetHardcodedSummaries() override;

  HardcodedFormatters::HardcodedSyntheticFinder
  GetHardcodedSynthetics() override;

  //------------------------------------------------------------------
  // Static Functions
  //------------------------------------------------------------------
  static void Initialize();

  static void Terminate();

  static lldb_private::Language *CreateInstance(lldb::LanguageType language);

  static lldb_private::ConstString GetPluginNameStatic();

  static bool IsCPPMangledName(const char *name);

  // Extract C++ context and identifier from a string using heuristic matching
  // (as opposed to
  // CPlusPlusLanguage::MethodName which has to have a fully qualified C++ name
  // with parens and arguments.
  // If the name is a lone C identifier (e.g. C) or a qualified C identifier
  // (e.g. A::B::C) it will return true,
  // and identifier will be the identifier (C and C respectively) and the
  // context will be "" and "A::B" respectively.
  // If the name fails the heuristic matching for a qualified or unqualified
  // C/C++ identifier, then it will return false
  // and identifier and context will be unchanged.

  static bool ExtractContextAndIdentifier(const char *name,
                                          llvm::StringRef &context,
                                          llvm::StringRef &identifier);

  // Given a mangled function name, calculates some alternative manglings since
  // the compiler mangling may not line up with the symbol we are expecting
  static uint32_t
  FindAlternateFunctionManglings(const ConstString mangled,
                                 std::set<ConstString> &candidates);

  //------------------------------------------------------------------
  // PluginInterface protocol
  //------------------------------------------------------------------
  ConstString GetPluginName() override;

  uint32_t GetPluginVersion() override;
};

} // namespace lldb_private

#endif // liblldb_CPlusPlusLanguage_h_


text:
The repository of my presentation on The Developers Conference - POA - 2016

https://rust-from-ruby.herokuapp.com

# Simple Rust Web App
How it work?

It was made using Iron that is a high level web framework
built in and for Rust, built on hyper.

## Backend
- [iron](https://github.com/iron/iron)
- [staticfile](https://github.com/iron/staticfile)
- [monting](https://github.com/iron/mount)

## Frontend
The presentation was made using reveal.js

## Running
```bash
cargo run
```
And the server will be running at: `http://localhost:3000`

## Deploying to Heroku

```
$ heroku create
$ git push heroku master
$ heroku open
```
or

[![Deploy to Heroku](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)

# LICENSE
MIT


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.manjunathshetty</groupId>
	<artifactId>java-samples</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>
	<modules>
		<module>java-threadpool-executor-sample</module>
		<module>java-async-rest-sample</module>
		<module>java-httpclient-starter</module>
	</modules>
</project>


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Octokit.Reflection;

namespace Octokit.Internal
{
    public class SimpleJsonSerializer : IJsonSerializer
    {
        readonly GitHubSerializerStrategy _serializationStrategy = new GitHubSerializerStrategy();

        public string Serialize(object item)
        {
            return SimpleJson.SerializeObject(item, _serializationStrategy);
        }

        public T Deserialize<T>(string json)
        {
            return SimpleJson.DeserializeObject<T>(json, _serializationStrategy);
        }

        class GitHubSerializerStrategy : PocoJsonSerializerStrategy
        {
            readonly List<string> _membersWhichShouldPublishNull = new List<string>();

            protected override string MapClrMemberToJsonFieldName(MemberInfo member)
            {
                return member.GetJsonFieldName();
            }

            internal override IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
            {
                var propertiesAndFields = type.GetPropertiesAndFields().Where(p => p.CanSerialize).ToList();

                foreach (var property in propertiesAndFields.Where(p => p.SerializeNull))
                {
                    var key = type.FullName + "-" + property.JsonFieldName;

                    _membersWhichShouldPublishNull.Add(key);
                }

                return propertiesAndFields
                    .ToDictionary(
                        p => p.JsonFieldName,
                        p => p.GetDelegate);
            }

            // This is overridden so that null values are omitted from serialized objects.
            [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")]
            protected override bool TrySerializeUnknownTypes(object input, out object output)
            {
                Ensure.ArgumentNotNull(input, "input");

                var type = input.GetType();
                var jsonObject = new JsonObject();
                var getters = GetCache[type];
                foreach (var getter in getters)
                {
                    if (getter.Value != null)
                    {
                        var value = getter.Value(input);
                        if (value == null)
                        {
                            var key = type.FullName + "-" + getter.Key;
                            if (!_membersWhichShouldPublishNull.Contains(key))
                                continue;
                        }
                        jsonObject.Add(getter.Key, value);
                    }
                }
                output = jsonObject;
                return true;
            }

            [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase",
                Justification = "The API expects lowercase values")]
            protected override object SerializeEnum(Enum p)
            {
                return p.ToString().ToLowerInvariant();
            }

            private string _type;

            // Overridden to handle enums.
            public override object DeserializeObject(object value, Type type)
            {
                var stringValue = value as string;
                var jsonValue = value as JsonObject;
                if (stringValue != null)
                {
                    stringValue = stringValue.Replace("-", "");
                    if (ReflectionUtils.GetTypeInfo(type).IsEnum)
                    {
                        // remove '-' from values coming in to be able to enum utf-8
                        stringValue = RemoveHyphenAndUnderscore(stringValue);
                        return Enum.Parse(type, stringValue, ignoreCase: true);
                    }

                    if (ReflectionUtils.IsNullableType(type))
                    {
                        var underlyingType = Nullable.GetUnderlyingType(type);
                        if (ReflectionUtils.GetTypeInfo(underlyingType).IsEnum)
                        {
                            stringValue = RemoveHyphenAndUnderscore(stringValue);
                            return Enum.Parse(underlyingType, stringValue, ignoreCase: true);
                        }
                    }

                    if (ReflectionUtils.IsTypeGenericeCollectionInterface(type))
                    {
                        // OAuth tokens might be a string of comma-separated values
                        // we should only try this if the return array is a collection of strings
                        var innerType = ReflectionUtils.GetGenericListElementType(type);
                        if (innerType.IsAssignableFrom(typeof(string)))
                        {
                            return stringValue.Split(',');
                        }
                    }
                }
                else if (jsonValue != null)
                {
                    if (type == typeof(Activity))
                    {
                        _type = jsonValue["type"].ToString();
                    }
                }

                if (type == typeof(ActivityPayload))
                {
                    var payloadType = GetPayloadType(_type);
                    return base.DeserializeObject(value, payloadType);
                }

                return base.DeserializeObject(value, type);
            }

            static string RemoveHyphenAndUnderscore(string stringValue)
            {
                // remove '-' from values coming in to be able to enum utf-8
                stringValue = stringValue.Replace("-", "");
                // remove '-' from values coming in to be able to enum EventInfoState names with underscores in them. Like "head_ref_deleted"
                stringValue = stringValue.Replace("_", "");
                return stringValue;
            }

            internal override IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)
            {
                return type.GetPropertiesAndFields()
                    .Where(p => p.CanDeserialize)
                    .ToDictionary(
                        p => p.JsonFieldName,
                        p => new KeyValuePair<Type, ReflectionUtils.SetDelegate>(p.Type, p.SetDelegate));
            }

            private static Type GetPayloadType(string activityType)
            {
                switch (activityType)
                {
                    case "CommitCommentEvent":
                        return typeof(CommitCommentPayload);
                    case "ForkEvent":
                        return typeof(ForkEventPayload);
                    case "IssueCommentEvent":
                        return typeof(IssueCommentPayload);
                    case "IssuesEvent":
                        return typeof(IssueEventPayload);
                    case "PullRequestEvent":
                        return typeof(PullRequestEventPayload);
                    case "PullRequestReviewCommentEvent":
                        return typeof(PullRequestCommentPayload);
                    case "PushEvent":
                        return typeof(PushEventPayload);
                    case "WatchEvent":
                        return typeof(StarredEventPayload);
                }
                return typeof(ActivityPayload);
            }
        }
    }
}


text:
EXTENDS_TYPE_OF —  Query dynamic type for extension

Description

Query dynamic type for extension.

Syntax

RESULT = EXTENDS_TYPE_OF(A, MOLD)

Arguments

<var>A</var> 	Shall be an object of extensible declared type or
unlimited polymorphic.

<var>MOLD</var> 	Shall be an object of extensible declared type or
unlimited polymorphic.

Return value

The return value is a scalar of type default logical. It is true if and only if
the dynamic type of A is an extension type of the dynamic type of MOLD.

Standard

Fortran 2003 and later

Class

Inquiry function

See also

SAME_TYPE_AS


text:
<?php

namespace Nocio\FormStore\NotifyRules;

use Nocio\FormStore\Classes\SubmissionEventBase;

class SubmissionSubmittedEvent extends SubmissionEventBase
{

    /**
     * Returns information about this event, including name and description.
     */
    public function eventDetails()
    {
        return [
            'name'        => 'Submission submitted',
            'description' => 'A submission is submitted',
            'group'       => 'formstore'
        ];
    }

}


text:
package com.jfilowk.teamfactory.datasource.cache.helper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.jfilowk.teamfactory.datasource.entities.Event;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.inject.Inject;

/**
 * Created by Javi on 22/09/14.
 */
public class EventDBImpl extends DatabaseHelper implements EventDB {

  @Inject
  public EventDBImpl(Context context) {
    super(context);
  }

  @Override public long createEvent(Event event) {
    SQLiteDatabase db = this.getWritableDatabase();
    long lEvent = db.insert(DBConstants.TABLE_EVENT, null, bindEvent(event));
    return lEvent;
  }

  @Override public long createEventUser(long idEvent, long idUser) {
    SQLiteDatabase db = this.getWritableDatabase();
    long lEventUser =
        db.insert(DBConstants.TABLE_RANDOM_EVENT, null, bindEventUser(idEvent, idUser));
    return lEventUser;
  }

  @Override public long createEventTeam(long idEvent, long idTeam) {
    SQLiteDatabase db = this.getWritableDatabase();
    long lEventTeam = db.insert(DBConstants.TABLE_EVENT_TEAM, null, bindEventTeam(idEvent, idTeam));
    return lEventTeam;
  }

  @Override public Cursor getIdUserEvent(long idEvent) {
    SQLiteDatabase db = this.getReadableDatabase();
    String selectQuery =
        "SELECT id_user FROM " + DBConstants.TABLE_RANDOM_EVENT + " WHERE id_event = " + idEvent;
    Cursor cursorIdUsers = db.rawQuery(selectQuery, null);

    return cursorIdUsers;
  }

  @Override public Cursor getIdTeamsEvent(long idEvent) {
    SQLiteDatabase db = this.getReadableDatabase();
    String selectQuery =
        "SELECT id_team FROM " + DBConstants.TABLE_EVENT_TEAM + " WHERE id_event = " + idEvent;
    Cursor cursorIdTeams = db.rawQuery(selectQuery, null);

    return cursorIdTeams;
  }

  @Override public Cursor getEvent(long id) {
    String selectQuery =
        "SELECT  * FROM " + DBConstants.TABLE_EVENT + " WHERE " + DBConstants.KEY_ID + " = " + id;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursorUsers = db.rawQuery(selectQuery, null);

    return cursorUsers;
  }

  @Override public Cursor getAllEvents() {
    String selectQuery = "SELECT  * FROM " + DBConstants.TABLE_EVENT;

    return this.getReadableDatabase().rawQuery(selectQuery, null);
  }

  @Override public int deleteEvent(long id) {
    SQLiteDatabase db = this.getWritableDatabase();
    int numRows = db.delete(DBConstants.TABLE_EVENT, "id = " + String.valueOf(id), null);
    return numRows;
  }

  @Override public void closeDb() {
    this.close();
  }

  private ContentValues bindEvent(Event event) {

    ContentValues values = new ContentValues();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();

    values.put("type", event.getType());
    values.put("num_users", event.getNumUser());
    values.put("num_teams", event.getNumTeams());
    values.put("created_at", dateFormat.format(date));

    return values;
  }

  private ContentValues bindEventUser(long idEvent, long idUser) {
    ContentValues values = new ContentValues();
    values.put("id_user", idUser);
    values.put("id_event", idEvent);
    return values;
  }

  private ContentValues bindEventTeam(long idEvent, long idTeam) {
    ContentValues values = new ContentValues();
    values.put("id_event", idEvent);
    values.put("id_team", idTeam);
    return values;
  }
}


text:
<?php //-->

namespace Cradle\Framework\Queue\Service;

/**
 * Comment Noop Service
 *
 * @vendor   Salaaap
 * @package  Utility
 * @author   Christian Blanquera <cblanquera@openovate.com>
 * @standard PSR-2
 */
class NoopService
{
    /**
     * @var *string $type
     */
    private $type = null;

    /**
     * Always return false
     *
     * @param string $type
     *
     * @return false
     */
    public function __construct($type = null)
    {
        $this->type = $type;
    }

    /**
     * Always return false
     *
     * @param *string $name
     * @param *array  $args
     *
     * @return false
     */
    public function __call($name, array $args)
    {
        if($this->type === 'redis') {
            return false;
        }

        return $this;
    }

    /**
     * Consumes Message
     *
     * @return bool
     */
    public function consume()
    {
        return false;
    }

    /**
     * Sends Message
     *
     * @return bool
     */
    public function send()
    {
        return false;
    }
}


text:
GLuint load_shader(GLenum shaderType, const char *src) {
  GLint status = 0, len = 0;
  GLuint shader;

  if (!(shader = glCreateShader(shaderType)))
    return 0;

  glShaderSource(shader, 1, &src, NULL);
  glCompileShader(shader);
  glGetShaderiv(shader, GL_COMPILE_STATUS, &status);

  if (status)
    return shader;

  glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
  if (len) {
    char *msg = (char*)malloc(len);
    if (msg) {
      glGetShaderInfoLog(shader, len, NULL, msg);
      msg[len-1] = 0;
      fprintf(stderr, "error compiling shader:\n%s\n", msg);
      free(msg);
    }
  }
  glDeleteShader(shader);
  return 0;
}

GLuint load_program(const char *vert_src, const char *frag_src) {
  GLuint vert, frag, prog;
  GLint status = 0, len = 0;

  if (!(vert = load_shader(GL_VERTEX_SHADER, vert_src)))
    return 0;
  if (!(frag = load_shader(GL_FRAGMENT_SHADER, frag_src)))
    goto fail_frag;
  if (!(prog = glCreateProgram()))
    goto fail_prog;

  glAttachShader(prog, vert);
  glAttachShader(prog, frag);
  glLinkProgram(prog);

  glGetProgramiv(prog, GL_LINK_STATUS, &status);
  if (status)
    return prog;

  glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &len);
  if (len) {
    char *buf = (char*) malloc(len);
    if (buf) {
      glGetProgramInfoLog(prog, len, NULL, buf);
      buf[len-1] = 0;
      fprintf(stderr, "error linking program:\n%s\n", buf);
      free(buf);
    }
  }
  glDeleteProgram(prog);
fail_prog:
  glDeleteShader(frag);
fail_frag:
  glDeleteShader(vert);
  return 0;
}


text:
#ifndef __DEBUG_H__
#define __DEBUG_H__

// #define DEBUG_CARBON_ALLOTROPE_CONSTRUCTION 1
// #define DEBUG_FULLERENE_CONSTRUCTION 1
// #define DEBUG_CONSTRUCTION_ALGORITHM 1
// #define DEBUG_ERRORS 1
// #define DEBUG_BOUNDARY_REPRESENTATIONS 1
// #define DEBUG_STOP_SIMULATION 1
// #define DEBUG_STOP_DRAWING 1
// #define DEBUG_CONTROL_SLICE 1

#endif /* __DEBUG_H__ */

/* Local Variables:	*/
/* mode: c++		*/
/* End:			*/


text:
layout: blog-post
title: Set up Raspberry Pi as a Network Server
type: blog
tag: [Raspberry Pi, Raspbian, Samba, video, streaming, storage]
description: Learn how to set up a Samba on the Raspberry Pi to share files acrosss your home network.
date: 2016-01-10T00:00:00-00:00
draft: false
---
The Raspberry Pi has an infinite amount of uses and one of them is using it as a [network server](http://computer.howstuffworks.com/what-is-network-server.htm). This is handy because people in your home network can connect to this network server and access shared files, such as movies and music, which can be streamed to your TV. I will be going over how to set this up on a fresh RPi.

## Install Raspbian

[Raspbian](https://www.raspberrypi.org/) is a light-weight Debian based Linux distro tailored for the RPi. Head over to the [downloads](https://www.raspberrypi.org/downloads/raspbian/) page and download the *img* file.

Once it's downloaded and extracted from the zip, plug in the SD card to your computer which will be used as the boot drive.

First list out the mounted media devices by using `df` (disk free) command:

```bash
$ df -h
Filesystem                  Size   Used  Avail Capacity  iused      ifree %iused  Mounted on
/dev/disk1                 167Gi  143Gi   24Gi    86% 37452708    6246366   86%   /
devfs                      344Ki  344Ki    0Bi   100%     1192          0  100%   /dev
map -hosts                   0Bi    0Bi    0Bi   100%        0          0  100%   /net
map auto_home                0Bi    0Bi    0Bi   100%        0          0  100%   /home
/dev/disk2s1               7.4Gi  3.0Mi  7.4Gi     1%        0          0  100%   /Volumes/NO NAME
```

In my case, `/dev/disk2s1` is the SD card. It will probably be different for you.

Next unmount the SD card using `umount` to be able to write the img on to it. It is important that you make sure you are unmounting the correct device.

```bash
$ sudo umount /dev/disk2s1
```

If you're on OS X and get the following error message:

```
umount(/Volumes/NO NAME): Resource busy -- try 'diskutil unmount'
```

Then use `diskutil`:

```
$ sudo diskutil umount /dev/disk2s1
Volume NO NAME on disk2s1 unmounted
```

Next write the Raspbian img to the SD card by using `dd` (dump data) command. This command simply takes the img as the input file and the SD card location as the output file.

VERY IMPORTANT that the output path is pointing to your own SD card. If not set correctly it can possibly corrupt your hard drive.

```
$ sudo dd bs=4m if=~/Downloads/2015-11-21-raspbian-jessie-lite.img of=/dev/disk2
347+1 records in
347+1 records out
1458569216 bytes transferred in 654.878776 secs (2227235 bytes/sec)
```

Be patient. It might take a minute or two to burn the Raspbian image.

After it is complete plug it in to your RPi with ethernet connected and boot.

The default credentials for Raspbian are:

```text
username: pi
password: raspberry
```

## Install Samba

[Samba](https://www.samba.org/) is a popular piece of software that enable directory and file sharing across a network. It is a Linux implementation of the [Server Message Block](https://en.wikipedia.org/wiki/Server_Message_Block) (SMB) protocol.

First update Raspbian packages to the latest:

```bash
$ sudo apt-get update
```

Now install `samba` and `smbclient` on the RPi. Samba also supports the Windows Naming System (WINS) and support for joining Windows workgroups. A workgroup is a group of computers on a Local Area Network (LAN) that can access each other's shared directories. Samba-common-bin contains a tool for registering users with Samba. Smbclient will be used for testing the SMB connection.

```bash
$ sudo apt-get install samba samba-common-bin smbclient
```

After the packages are installed we, we will add user `pi` to the local `smbpasswd` file.

```bash
$ sudo smbpasswd -a pi
New SMB password:
Retype new SMB password:
Added user pi.
```

You can use `smbpasswd` to change password if you need to:

```bash
$ smbpasswd
Old SMB password:
New SMB password:
Retype new SMB password:
Password changed for user pi
```

So now samba is installed, let's mount a hard drive to be used as the shared storage device.

## Mount Hard Drive

A convenient little tool is `blkid` which lists connected drives and their filesystem type.

```bash
$ sudo blkid
/dev/mmcblk0p1: SEC_TYPE="msdos" LABEL="boot" UUID="C0E6-1BEB" TYPE="vfat"
/dev/mmcblk0p2: UUID="9c7e2035-df9b-490b-977b-d60f2170889d" TYPE="ext4"
/dev/sda1: LABEL="My Passport" UUID="4E1AEA7B1AEA6007" TYPE="ntfs"
/dev/sdb1: LABEL="Ubuntu 15.10 amd64" TYPE="iso9660"
/dev/sdb2: SEC_TYPE="msdos" UUID="99B5-7FC8" TYPE="vfat"
```

If my case I will be mounting the Western Digital "My Passport" external hard drive located at `/dev/sda1` which has an *ntfs* file system. In your case it might be different so take note of the drive path.

It's standard to mount drives in `/mnt` so we need to create a new directory there.

```bash
$ sudo mkdir /mnt/hd
```

Now we just mount the drive to that location.

```bash
$ mount /dev/sda1 /mnt/hd
```

If you get the following error:

```bash
mount: only root can do that
```

then do not run sudo because we want normal users to access the drive instead of always being root. So what we need to do is append a line to `/etc/fstab` that allows normal users to mount the drive to a specified mounting location.

```bash
$ sudo vim /etc/fstab
```

Append this line but note that you might need to edit the paths and filesystem to your own requirements.

```text
/dev/sda1       /mnt/hd         ntfs    rw,user,exec,umask=000 0 0
```

The complete `/etc/fstab` file should look something like this:

```text
proc            /proc           proc    defaults          0       0
/dev/mmcblk0p1  /boot           vfat    defaults          0       2
/dev/mmcblk0p2  /               ext4    defaults,noatime  0       1
# a swapfile is not a swap partition, no line here
#   use  dphys-swapfile swap[on|off]  for that

# Allow normal users to mount `/dev/sda` drive to `/mnt/hd`.
/dev/sda1       /mnt/hd         ntfs    rw,user,exec,umask=000 0 0
```

Make sure to save the file.

If you ever need to unmount the drive, simply run:

```
umount /mnt/hd
```

We have the drive now in place so let's configure Samba and start it up.

## Configure Samba

The Samba configuration file is located in `/etc/samba/smb.conf`:

```bash
$ sudo vim /etc/samba/smb.conf
```

In this example we will be adding a `Movies` directory which points to the path `/mnt/hd/Movies` where my movies are located. Simply append it to the bottom of the configuration file.

```text
[Movies]
    comment=Movies
    path = /mnt/hd/Movies
    available = yes
    valid users = @users
    read only = no
    browsable = yes
    read only = no
    writeable = yes
    only guest = no
    public = no
    create mask = 0700
    directory mask = 0777
```

Save it and restart the restart the Samba server for changes to take effect.

```bash
$ sudo /etc/init.d/samba restart
Restarting nmbd (via systemctl): nmbd.service.
Restarting smbd (via systemctl): smbd.service.
Restarting samba-ad-dc (via systemctl): samba-ad-dc.service.
```
Alternatively you can do:

```bash
service samba restart
```

Now test with the SMB client to make sure the folder is recognized.

```bash
$ smbclient -L localhost
Enter pi's password:
Enter pi's password:
Domain=[WORKGROUP] OS=[Unix] Server=[Samba 4.1.17-Debian]

        Sharename       Type      Comment
        ---------       ----      -------
        print$          Disk      Printer Drivers
        Movies          Disk      Movies
        IPC$            IPC       IPC Service (Samba 4.1.17-Debian)
        pi              Disk      Home Directories
Domain=[WORKGROUP] OS=[Unix] Server=[Samba 4.1.17-Debian]

        Server               Comment
        ---------            -------
        RASPBERRYPI          Samba 4.1.17-Debian

        Workgroup            Master
        ---------            -------
        WORKGROUP            RASPBERRYPI
```

The entire Samba configuration file might look something like this:

```text
#
# Sample configuration file for the Samba suite for Debian GNU/Linux.
#
#
# This is the main Samba configuration file. You should read the
# smb.conf(5) manual page in order to understand the options listed
# here. Samba has a huge number of configurable options most of which
# are not shown in this example
#
# Some options that are often worth tuning have been included as
# commented-out examples in this file.
#  - When such options are commented with ";", the proposed setting
#    differs from the default Samba behaviour
#  - When commented with "#", the proposed setting is the default
#    behaviour of Samba but the option is considered important
#    enough to be mentioned here
#
# NOTE: Whenever you modify this file you should run the command
# "testparm" to check that you have not made any basic syntactic
# errors.

#======================= Global Settings =======================

[global]

## Browsing/Identification ###

# Change this to the workgroup/NT-domain name your Samba server will part of
   workgroup = WORKGROUP

# Windows Internet Name Serving Support Section:
# WINS Support - Tells the NMBD component of Samba to enable its WINS Server
#   wins support = no

# WINS Server - Tells the NMBD components of Samba to be a WINS Client
# Note: Samba can be either a WINS Server, or a WINS Client, but NOT both
;   wins server = w.x.y.z

# This will prevent nmbd to search for NetBIOS names through DNS.
   dns proxy = no

#### Networking ####

# The specific set of interfaces / networks to bind to
# This can be either the interface name or an IP address/netmask;
# interface names are normally preferred
;   interfaces = 127.0.0.0/8 eth0

# Only bind to the named interfaces and/or networks; you must use the
# 'interfaces' option above to use this.
# It is recommended that you enable this feature if your Samba machine is
# not protected by a firewall or is a firewall itself.  However, this
# option cannot handle dynamic or non-broadcast interfaces correctly.
;   bind interfaces only = yes

#### Debugging/Accounting ####

# This tells Samba to use a separate log file for each machine
# that connects
   log file = /var/log/samba/log.%m
# Cap the size of the individual log files (in KiB).
   max log size = 1000

# If you want Samba to only log through syslog then set the following
# parameter to 'yes'.
#   syslog only = no

# We want Samba to log a minimum amount of information to syslog. Everything
# should go to /var/log/samba/log.{smbd,nmbd} instead. If you want to log
# through syslog you should set the following parameter to something higher.
   syslog = 0

# Do something sensible when Samba crashes: mail the admin a backtrace
   panic action = /usr/share/samba/panic-action %d

####### Authentication #######

# Server role. Defines in which mode Samba will operate. Possible
# values are "standalone server", "member server", "classic primary
# domain controller", "classic backup domain controller", "active
# directory domain controller".
#
# Most people will want "standalone sever" or "member server".
# Running as "active directory domain controller" will require first
# running "samba-tool domain provision" to wipe databases and create a
# new domain.
   server role = standalone server

# If you are using encrypted passwords, Samba will need to know what
# password database type you are using.
   passdb backend = tdbsam

   obey pam restrictions = yes

# This boolean parameter controls whether Samba attempts to sync the Unix
# password with the SMB password when the encrypted SMB password in the
# passdb is changed.
   unix password sync = yes

# For Unix password sync to work on a Debian GNU/Linux system, the following
# parameters must be set (thanks to Ian Kahan <<kahan@informatik.tu-muenchen.de> for
# sending the correct chat script for the passwd program in Debian Sarge).
   passwd program = /usr/bin/passwd %u
   passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .

# This boolean controls whether PAM will be used for password changes
# when requested by an SMB client instead of the program listed in
# 'passwd program'. The default is 'no'.
   pam password change = yes

# This option controls how unsuccessful authentication attempts are mapped
# to anonymous connections
   map to guest = bad user

########## Domains ###########

#
# The following settings only takes effect if 'server role = primary
# classic domain controller', 'server role = backup domain controller'
# or 'domain logons' is set
#

# It specifies the location of the user's
# profile directory from the client point of view) The following
# required a [profiles] share to be setup on the samba server (see
# below)
;   logon path = \\%N\profiles\%U
# Another common choice is storing the profile in the user's home directory
# (this is Samba's default)
#   logon path = \\%N\%U\profile

# The following setting only takes effect if 'domain logons' is set
# It specifies the location of a user's home directory (from the client
# point of view)
;   logon drive = H:
#   logon home = \\%N\%U

# The following setting only takes effect if 'domain logons' is set
# It specifies the script to run during logon. The script must be stored
# in the [netlogon] share
# NOTE: Must be store in 'DOS' file format convention
;   logon script = logon.cmd

# This allows Unix users to be created on the domain controller via the SAMR
# RPC pipe.  The example command creates a user account with a disabled Unix
# password; please adapt to your needs
; add user script = /usr/sbin/adduser --quiet --disabled-password --gecos "" %u

# This allows machine accounts to be created on the domain controller via the
# SAMR RPC pipe.
# The following assumes a "machines" group exists on the system
; add machine script  = /usr/sbin/useradd -g machines -c "%u machine account" -d /var/lib/samba -s /bin/false %u
# This allows Unix groups to be created on the domain controller via the SAMR
# RPC pipe.
; add group script = /usr/sbin/addgroup --force-badname %g

############ Misc ############

# Using the following line enables you to customise your configuration
# on a per machine basis. The %m gets replaced with the netbios name
# of the machine that is connecting
;   include = /home/samba/etc/smb.conf.%m

# Some defaults for winbind (make sure you're not using the ranges
# for something else.)
;   idmap uid = 10000-20000
;   idmap gid = 10000-20000
;   template shell = /bin/bash

# Setup usershare options to enable non-root users to share folders
# with the net usershare command.

# Maximum number of usershare. 0 (default) means that usershare is disabled.
;   usershare max shares = 100

# Allow users who've been granted usershare privileges to create
# public shares, not just authenticated ones
   usershare allow guests = yes

#======================= Share Definitions =======================

[homes]
   comment = Home Directories
   browseable = no

# By default, the home directories are exported read-only. Change the
# next parameter to 'no' if you want to be able to write to them.
   read only = yes

# File creation mask is set to 0700 for security reasons. If you want to
# create files with group=rw permissions, set next parameter to 0775.
   create mask = 0700

# Directory creation mask is set to 0700 for security reasons. If you want to
# create dirs. with group=rw permissions, set next parameter to 0775.
   directory mask = 0700

# By default, \\server\username shares can be connected to by anyone
# with access to the samba server.
# The following parameter makes sure that only "username" can connect
# to \\server\username
# This might need tweaking when using external authentication schemes
   valid users = %S

# Un-comment the following and create the netlogon directory for Domain Logons
# (you need to configure Samba to act as a domain controller too.)
;[netlogon]
;   comment = Network Logon Service
;   path = /home/samba/netlogon
;   guest ok = yes
;   read only = yes

# Un-comment the following and create the profiles directory to store
# users profiles (see the "logon path" option above)
# (you need to configure Samba to act as a domain controller too.)
# The path below should be writable by all users so that their
# profile directory may be created the first time they log on
;[profiles]
;   comment = Users profiles
;   path = /home/samba/profiles
;   guest ok = no
;   browseable = no
;   create mask = 0600
;   directory mask = 0700

[printers]
   comment = All Printers
   browseable = no
   path = /var/spool/samba
   printable = yes
   guest ok = no
   read only = yes
   create mask = 0700

# Windows clients look for this share name as a source of downloadable
# printer drivers
[print$]
   comment = Printer Drivers
   path = /var/lib/samba/printers
   browseable = yes
   read only = yes
   guest ok = no
# Uncomment to allow remote administration of Windows print drivers.
# You may need to replace 'lpadmin' with the name of the group your
# admin users are members of.
# Please note that you also need to set appropriate Unix permissions
# to the drivers directory for these users to have write rights in it
;   write list = root, @lpadmin

# My shared directories
[Movies]
    comment=Movies
    path = /mnt/hd/Movies
    available = yes
    valid users = @users
    read only = no
    browsable = yes
    read only = no
    writeable = yes
    only guest = no
    public = no
    create mask = 0700
    directory mask = 0777
```

## Connect to SMB in OS X

To connect to the Raspberry Pi network server follow these steps:

Go to

*Finder* -> *Go* -> *Connect To Server*

Enter the RPi hostname prefixed by the protocol.

```
smb://raspberrypi
```

[![](finder-connect-to-server.jpg)](finder-connect-to-server.jpg)

To get the hostname you can use the `hostname` command on the RPi:

```bash
$ hostname
raspberrypi
```

Next enter the credential for SMB you have set up earlier.

[![](finder-enter-server-credentials.jpg)](finder-enter-server-credentials.jpg)

Select the Volumes (directories) you wish to mount.

[![](finder-select-volumes-to-mount.jpg)](finder-select-volumes-to-mount.jpg)

Now you're connected to the shared network.

[![](finder-connected-shared-drive.jpg)](finder-connected-shared-drive.jpg)

## Streaming videos

The [Google Chromecast](https://www.google.com/chromecast) is a must for easily streaming content to your TV.

[Videostream for Google Chromecast](https://chrome.google.com/webstore/detail/videostream-for-google-ch/cnciopoikihiagdjbjpnocolokfelagl?hl=en) is a great Chrome app for streaming a large number video formats from your computer.

[FileBrowser](https://itunes.apple.com/us/app/filebrowser-access-files-on/id364738545?mt=8) for iOS is a fantastic app for connecting to SMB and opening different file types in your phone.

[VLC for Mobile](https://itunes.apple.com/us/app/vlc-for-mobile/id650377962?mt=8) is the best video player for iOS I've come across.

## Conclusion

A Raspberry Pi running Samba makes a great network server on a budget. Easy to set up and cheap.


text:
from corehq.apps.reports.fields import ReportSelectField, SelectCaseOwnerField
from django.utils.translation import ugettext_noop
from corehq.apps.groups.models import Group
from dimagi.utils.couch.database import get_db
from django.utils.translation import ugettext as _

class SelectPNCStatusField(ReportSelectField):
    slug = "PNC_status"
    name = ugettext_noop("Status")
    cssId = "opened_closed"
    cssClasses = "span3"
    default_option = "Select PNC Status"
    options = [dict(val="On Time", text=ugettext_noop("On time")),
               dict(val="Late", text=ugettext_noop("Late"))]

class SelectBlockField(ReportSelectField):
    slug = "block"
    name = ugettext_noop("Block")
    cssId = "opened_closed"
    cssClasses = "span3"

    def update_params(self):
        blocks = set(self.get_blocks(self.domain))
        block = self.request.GET.get(self.slug, '')

        self.selected = block
        self.options = [dict(val=block_item, text="%s" % block_item) for block_item in blocks]
        self.default_option = _("Select Block")

    @classmethod
    def get_blocks(cls, domain):
        key = [domain]
        for r in get_db().view('crs_reports/field_block',
                      startkey=key,
                      endkey=key + [{}],
                      group_level=3).all():
            _, _, block_name = r['key']
            if block_name:
                yield block_name

class SelectSubCenterField(ReportSelectField):
    slug = "sub_center"
    name = ugettext_noop("Sub Center")
    cssId = "opened_closed"
    cssClasses = "span3"
    default_option = "Select Sub Center"
    options = []

class SelectASHAField(SelectCaseOwnerField):
    name = ugettext_noop("ASHA")
    default_option = ugettext_noop("Type ASHA name")

    def update_params(self):
        case_sharing_groups = Group.get_case_sharing_groups(self.domain)
        self.context["groups"] = [dict(group_id=group._id, name=group.name) for group in case_sharing_groups]


text:
package hu.akarnokd.reactive4java.base;

/**
 * An observable which provides a key as its group identity.
 * @author akarnokd, 2011.01.29.
 * @param <Key> the key type
 * @param <Value> the value type
 */
public interface GroupedObservable<Key, Value> extends Observable<Value> {
    /** @return the key of this group. */
    Key key();
}


text:
package com.vaadin.tests.componentlocator;

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

import com.vaadin.testbench.elements.LabelElement;
import com.vaadin.testbench.elementsbase.ServerClass;
import com.vaadin.tests.tb3.SingleBrowserTest;

public class ComponentLocatorInheritedClassesTest extends SingleBrowserTest {

    @ServerClass("com.vaadin.tests.componentlocator.ComponentLocatorInheritedClasses.DefaultLabel")
    public static class DefaultLabelElement extends LabelElement {
    }

    @ServerClass("com.vaadin.tests.componentlocator.ComponentLocatorInheritedClasses.MyCustomLabel")
    public static class MyCustomLabelElement extends DefaultLabelElement {
    }

    @Test
    public void label_finds_all_three() {
        openTestURL();
        Assert.assertEquals(3, $(LabelElement.class).all().size());
    }

    @Test
    public void defaultlabel_finds_two() {
        openTestURL();
        Assert.assertEquals(2, $(DefaultLabelElement.class).all().size());
    }

    @Test
    public void mycustomlabel_finds_one() {
        openTestURL();
        Assert.assertEquals(1, $(MyCustomLabelElement.class).all().size());
    }
}


text:
Sequel.migration do
  change do
    # TODO delete webhook headers table
    add_column(:webhooks, :headers, String)
  end
end


text:
/**
 * @file
 * @author Ivan Ristic <ivanr@webkreator.com>
 */

#ifndef HTP_CONNECTION_PARSER_H
#define	HTP_CONNECTION_PARSER_H

#ifdef	__cplusplus
extern "C" {
#endif

/**
 * Clears the most recent error, if any.
 *
 * @param[in] connp
 */
void htp_connp_clear_error(htp_connp_t *connp);

/**
 * Closes the connection associated with the supplied parser.
 *
 * @param[in] connp
 * @param[in] timestamp Optional.
 */
void htp_connp_close(htp_connp_t *connp, const htp_time_t *timestamp);

/**
 * Creates a new connection parser using the provided configuration. Because
 * the configuration structure is used directly, in a multithreaded environment
 * you are not allowed to change the structure, ever. If you have a need to
 * change configuration on per-connection basis, make a copy of the configuration
 * structure to go along with every connection parser.
 *
 * @param[in] cfg
 * @return New connection parser instance, or NULL on error.
 */
htp_connp_t *htp_connp_create(htp_cfg_t *cfg);

/**
 * Destroys the connection parser and its data structures, leaving
 * all the data (connection, transactions, etc) intact.
 *
 * @param[in] connp
 */
void htp_connp_destroy(htp_connp_t *connp);

/**
 * Destroys the connection parser, its data structures, as well
 * as the connection and its transactions.
 *
 * @param[in] connp
 */
void htp_connp_destroy_all(htp_connp_t *connp);

/**
 * Returns the connection associated with the connection parser.
 *
 * @param[in] connp
 * @return htp_conn_t instance, or NULL if one is not available.
 */
htp_conn_t *htp_connp_get_connection(const htp_connp_t *connp);

/**
 * Retrieves the pointer to the active inbound transaction. In connection
 * parsing mode there can be many open transactions, and up to 2 active
 * transactions at any one time. This is due to HTTP pipelining. Can be NULL.
 *
 * @param[in] connp
 * @return Active inbound transaction, or NULL if there isn't one.
 */
htp_tx_t *htp_connp_get_in_tx(const htp_connp_t *connp);

/**
 * Returns the last error that occurred with this connection parser. Do note, however,
 * that the value in this field will only be valid immediately after an error condition,
 * but it is not guaranteed to remain valid if the parser is invoked again.
 *
 * @param[in] connp
 * @return A pointer to an htp_log_t instance if there is an error, or NULL
 *         if there isn't.
 */
htp_log_t *htp_connp_get_last_error(const htp_connp_t *connp);

/**
 * Retrieves the pointer to the active outbound transaction. In connection
 * parsing mode there can be many open transactions, and up to 2 active
 * transactions at any one time. This is due to HTTP pipelining. Can be NULL.
 *
 * @param[in] connp
 * @return Active outbound transaction, or NULL if there isn't one.
 */
htp_tx_t *htp_connp_get_out_tx(const htp_connp_t *connp);

/**
 * Retrieve the user data associated with this connection parser.
 *
 * @param[in] connp
 * @return User data, or NULL if there isn't any.
 */
void *htp_connp_get_user_data(const htp_connp_t *connp);

/**
 * Opens connection.
 *
 * @param[in] connp
 * @param[in] client_addr Client address
 * @param[in] client_port Client port
 * @param[in] server_addr Server address
 * @param[in] server_port Server port
 * @param[in] timestamp Optional.
 */
void htp_connp_open(htp_connp_t *connp, const char *client_addr, int client_port, const char *server_addr,
    int server_port, htp_time_t *timestamp);

/**
 * Associate user data with the supplied parser.
 *
 * @param[in] connp
 * @param[in] user_data
 */
void htp_connp_set_user_data(htp_connp_t *connp, const void *user_data);

/**
 *
 * @param[in] connp
 * @param[in] timestamp
 * @param[in] data
 * @param[in] len
 * @return HTP_STREAM_DATA, HTP_STREAM_ERROR or STEAM_STATE_DATA_OTHER (see QUICK_START).
 *         HTP_STREAM_CLOSED and HTP_STREAM_TUNNEL are also possible.
 */
int htp_connp_req_data(htp_connp_t *connp, const htp_time_t *timestamp, const void *data, size_t len);

/**
 * Returns the number of bytes consumed from the most recent inbound data chunk. Normally, an invocation
 * of htp_connp_req_data() will consume all data from the supplied buffer, but there are circumstances
 * where only partial consumption is possible. In such cases HTP_STREAM_DATA_OTHER will be returned.
 * Consumed bytes are no longer necessary, but the remainder of the buffer will be need to be saved
 * for later.
 *
 * @param[in] connp
 * @return The number of bytes consumed from the last data chunk sent for inbound processing.
 */
size_t htp_connp_req_data_consumed(htp_connp_t *connp);

/**
 * Process a chunk of outbound (server or response) data.
 *
 * @param[in] connp
 * @param[in] timestamp Optional.
 * @param[in] data
 * @param[in] len
 * @return HTP_OK on state change, HTP_ERROR on error, or HTP_DATA when more data is needed
 */
int htp_connp_res_data(htp_connp_t *connp, const htp_time_t *timestamp, const void *data, size_t len);

/**
 * Returns the number of bytes consumed from the most recent outbound data chunk. Normally, an invocation
 * of htp_connp_res_data() will consume all data from the supplied buffer, but there are circumstances
 * where only partial consumption is possible. In such cases HTP_STREAM_DATA_OTHER will be returned.
 * Consumed bytes are no longer necessary, but the remainder of the buffer will be need to be saved
 * for later.
 *
 * @param[in] connp
 * @return The number of bytes consumed from the last data chunk sent for outbound processing.
 */
size_t htp_connp_res_data_consumed(htp_connp_t *connp);

/**
 * Create a new transaction using the connection parser provided.
 *
 * @param[in] connp
 * @return Transaction instance on success, NULL on failure.
 */
htp_tx_t *htp_connp_tx_create(htp_connp_t *connp);

#ifdef	__cplusplus
}
#endif

#endif	/* HTP_CONNECTION_PARSER_H */


text:
package com.dynamicguy.solrpress.config.metrics;

import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.inject.Inject;

@Configuration
public class JHipsterHealthIndicatorConfiguration {

    @Inject
    private JavaMailSenderImpl javaMailSender;

    @Bean
    public HealthIndicator mailHealthIndicator() {
        return new JavaMailHealthIndicator(javaMailSender);
    }
}


text:
package commands

import (
	"fmt"
	"io"
	"path"

	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/cheggaaa/pb"

	cmds "github.com/ipfs/go-ipfs/commands"
	files "github.com/ipfs/go-ipfs/commands/files"
	core "github.com/ipfs/go-ipfs/core"
	importer "github.com/ipfs/go-ipfs/importer"
	"github.com/ipfs/go-ipfs/importer/chunk"
	dag "github.com/ipfs/go-ipfs/merkledag"
	pin "github.com/ipfs/go-ipfs/pin"
	ft "github.com/ipfs/go-ipfs/unixfs"
	u "github.com/ipfs/go-ipfs/util"
)

// Error indicating the max depth has been exceded.
var ErrDepthLimitExceeded = fmt.Errorf("depth limit exceeded")

// how many bytes of progress to wait before sending a progress update message
const progressReaderIncrement = 1024 * 256

const (
	quietOptionName    = "quiet"
	progressOptionName = "progress"
	trickleOptionName  = "trickle"
	wrapOptionName     = "wrap-with-directory"
	hiddenOptionName   = "hidden"
	onlyHashOptionName = "only-hash"
	chunkerOptionName  = "chunker"
)

type AddedObject struct {
	Name  string
	Hash  string `json:",omitempty"`
	Bytes int64  `json:",omitempty"`
}

var AddCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Add an object to ipfs.",
		ShortDescription: `
Adds contents of <path> to ipfs. Use -r to add directories.
Note that directories are added recursively, to form the ipfs
MerkleDAG. A smarter partial add with a staging area (like git)
remains to be implemented.
`,
	},

	Arguments: []cmds.Argument{
		cmds.FileArg("path", true, true, "The path to a file to be added to IPFS").EnableRecursive().EnableStdin(),
	},
	Options: []cmds.Option{
		cmds.OptionRecursivePath, // a builtin option that allows recursive paths (-r, --recursive)
		cmds.BoolOption(quietOptionName, "q", "Write minimal output"),
		cmds.BoolOption(progressOptionName, "p", "Stream progress data"),
		cmds.BoolOption(trickleOptionName, "t", "Use trickle-dag format for dag generation"),
		cmds.BoolOption(onlyHashOptionName, "n", "Only chunk and hash - do not write to disk"),
		cmds.BoolOption(wrapOptionName, "w", "Wrap files with a directory object"),
		cmds.BoolOption(hiddenOptionName, "Include files that are hidden"),
		cmds.StringOption(chunkerOptionName, "s", "chunking algorithm to use"),
	},
	PreRun: func(req cmds.Request) error {
		if quiet, _, _ := req.Option(quietOptionName).Bool(); quiet {
			return nil
		}

		req.SetOption(progressOptionName, true)

		sizeFile, ok := req.Files().(files.SizeFile)
		if !ok {
			// we don't need to error, the progress bar just won't know how big the files are
			return nil
		}

		size, err := sizeFile.Size()
		if err != nil {
			// see comment above
			return nil
		}
		log.Debugf("Total size of file being added: %v\n", size)
		req.Values()["size"] = size

		return nil
	},
	Run: func(req cmds.Request, res cmds.Response) {
		n, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		progress, _, _ := req.Option(progressOptionName).Bool()
		trickle, _, _ := req.Option(trickleOptionName).Bool()
		wrap, _, _ := req.Option(wrapOptionName).Bool()
		hash, _, _ := req.Option(onlyHashOptionName).Bool()
		hidden, _, _ := req.Option(hiddenOptionName).Bool()
		chunker, _, _ := req.Option(chunkerOptionName).String()

		if hash {
			nilnode, err := core.NewNodeBuilder().NilRepo().Build(n.Context())
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
			n = nilnode
		}

		outChan := make(chan interface{}, 8)
		res.SetOutput((<-chan interface{})(outChan))

		// addSingleFile is a function that adds a file given as a param.
		addSingleFile := func(file files.File) error {
			addParams := adder{
				node:     n,
				out:      outChan,
				progress: progress,
				hidden:   hidden,
				trickle:  trickle,
				chunker:  chunker,
			}

			rootnd, err := addParams.addFile(file)
			if err != nil {
				return err
			}

			rnk, err := rootnd.Key()
			if err != nil {
				return err
			}

			mp := n.Pinning.GetManual()
			mp.RemovePinWithMode(rnk, pin.Indirect)
			mp.PinWithMode(rnk, pin.Recursive)
			return n.Pinning.Flush()
		}

		// addFilesSeparately loops over a convenience slice file to
		// add each file individually. e.g. 'ipfs add a b c'
		addFilesSeparately := func(sliceFile files.File) error {
			for {
				file, err := sliceFile.NextFile()
				if err != nil && err != io.EOF {
					return err
				}
				if file == nil {
					return nil // done
				}

				if err := addSingleFile(file); err != nil {
					return err
				}
			}
		}

		go func() {
			defer close(outChan)

			// really, we're unrapping, if !wrap, because
			// req.Files() is already a SliceFile() with all of them,
			// so can just use that slice as the wrapper.
			var err error
			if wrap {
				err = addSingleFile(req.Files())
			} else {
				err = addFilesSeparately(req.Files())
			}
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
		}()
	},
	PostRun: func(req cmds.Request, res cmds.Response) {
		if res.Error() != nil {
			return
		}
		outChan, ok := res.Output().(<-chan interface{})
		if !ok {
			res.SetError(u.ErrCast(), cmds.ErrNormal)
			return
		}
		res.SetOutput(nil)

		quiet, _, err := req.Option("quiet").Bool()
		if err != nil {
			res.SetError(u.ErrCast(), cmds.ErrNormal)
			return
		}

		size := int64(0)
		s, found := req.Values()["size"]
		if found {
			size = s.(int64)
		}
		showProgressBar := !quiet && size >= progressBarMinSize

		var bar *pb.ProgressBar
		var terminalWidth int
		if showProgressBar {
			bar = pb.New64(size).SetUnits(pb.U_BYTES)
			bar.ManualUpdate = true
			bar.Start()

			// the progress bar lib doesn't give us a way to get the width of the output,
			// so as a hack we just use a callback to measure the output, then git rid of it
			terminalWidth = 0
			bar.Callback = func(line string) {
				terminalWidth = len(line)
				bar.Callback = nil
				bar.Output = res.Stderr()
				log.Infof("terminal width: %v\n", terminalWidth)
			}
			bar.Update()
		}

		lastFile := ""
		var totalProgress, prevFiles, lastBytes int64

		for out := range outChan {
			output := out.(*AddedObject)
			if len(output.Hash) > 0 {
				if showProgressBar {
					// clear progress bar line before we print "added x" output
					fmt.Fprintf(res.Stderr(), "\033[2K\r")
				}
				if quiet {
					fmt.Fprintf(res.Stdout(), "%s\n", output.Hash)
				} else {
					fmt.Fprintf(res.Stdout(), "added %s %s\n", output.Hash, output.Name)
				}

			} else {
				log.Debugf("add progress: %v %v\n", output.Name, output.Bytes)

				if !showProgressBar {
					continue
				}

				if len(lastFile) == 0 {
					lastFile = output.Name
				}
				if output.Name != lastFile || output.Bytes < lastBytes {
					prevFiles += lastBytes
					lastFile = output.Name
				}
				lastBytes = output.Bytes
				delta := prevFiles + lastBytes - totalProgress
				totalProgress = bar.Add64(delta)
			}

			if showProgressBar {
				bar.Update()
			}
		}
	},
	Type: AddedObject{},
}

// Internal structure for holding the switches passed to the `add` call
type adder struct {
	node     *core.IpfsNode
	out      chan interface{}
	progress bool
	hidden   bool
	trickle  bool
	chunker  string
}

// Perform the actual add & pin locally, outputting results to reader
func add(n *core.IpfsNode, reader io.Reader, useTrickle bool, chunker string) (*dag.Node, error) {
	chnk, err := chunk.FromString(reader, chunker)
	if err != nil {
		return nil, err
	}

	var node *dag.Node
	if useTrickle {
		node, err = importer.BuildTrickleDagFromReader(
			n.DAG,
			chnk,
			importer.PinIndirectCB(n.Pinning.GetManual()),
		)
	} else {
		node, err = importer.BuildDagFromReader(
			n.DAG,
			chnk,
			importer.PinIndirectCB(n.Pinning.GetManual()),
		)
	}

	if err != nil {
		return nil, err
	}

	return node, nil
}

// Add the given file while respecting the params.
func (params *adder) addFile(file files.File) (*dag.Node, error) {
	// Check if file is hidden
	if fileIsHidden := files.IsHidden(file); fileIsHidden && !params.hidden {
		log.Debugf("%s is hidden, skipping", file.FileName())
		return nil, &hiddenFileError{file.FileName()}
	}

	// Check if "file" is actually a directory
	if file.IsDirectory() {
		return params.addDir(file)
	}

	// if the progress flag was specified, wrap the file so that we can send
	// progress updates to the client (over the output channel)
	var reader io.Reader = file
	if params.progress {
		reader = &progressReader{file: file, out: params.out}
	}

	dagnode, err := add(params.node, reader, params.trickle, params.chunker)
	if err != nil {
		return nil, err
	}

	log.Infof("adding file: %s", file.FileName())
	if err := outputDagnode(params.out, file.FileName(), dagnode); err != nil {
		return nil, err
	}
	return dagnode, nil
}

func (params *adder) addDir(file files.File) (*dag.Node, error) {
	tree := &dag.Node{Data: ft.FolderPBData()}
	log.Infof("adding directory: %s", file.FileName())

	for {
		file, err := file.NextFile()
		if err != nil && err != io.EOF {
			return nil, err
		}
		if file == nil {
			break
		}

		node, err := params.addFile(file)
		if _, ok := err.(*hiddenFileError); ok {
			// hidden file error, set the node to nil for below
			node = nil
		} else if err != nil {
			return nil, err
		}

		if node != nil {
			_, name := path.Split(file.FileName())

			err = tree.AddNodeLink(name, node)
			if err != nil {
				return nil, err
			}
		}
	}

	err := outputDagnode(params.out, file.FileName(), tree)
	if err != nil {
		return nil, err
	}

	k, err := params.node.DAG.Add(tree)
	if err != nil {
		return nil, err
	}

	params.node.Pinning.GetManual().PinWithMode(k, pin.Indirect)

	return tree, nil
}

// outputDagnode sends dagnode info over the output channel
func outputDagnode(out chan interface{}, name string, dn *dag.Node) error {
	o, err := getOutput(dn)
	if err != nil {
		return err
	}

	out <- &AddedObject{
		Hash: o.Hash,
		Name: name,
	}

	return nil
}

type hiddenFileError struct {
	fileName string
}

func (e *hiddenFileError) Error() string {
	return fmt.Sprintf("%s is a hidden file", e.fileName)
}

type ignoreFileError struct {
	fileName string
}

func (e *ignoreFileError) Error() string {
	return fmt.Sprintf("%s is an ignored file", e.fileName)
}

type progressReader struct {
	file         files.File
	out          chan interface{}
	bytes        int64
	lastProgress int64
}

func (i *progressReader) Read(p []byte) (int, error) {
	n, err := i.file.Read(p)

	i.bytes += int64(n)
	if i.bytes-i.lastProgress >= progressReaderIncrement || err == io.EOF {
		i.lastProgress = i.bytes
		i.out <- &AddedObject{
			Name:  i.file.FileName(),
			Bytes: i.bytes,
		}
	}

	return n, err
}


text:
<?xml version="1.0"?>

<!--
   Copyright 2008 University of Rochester

   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.
-->

<!DOCTYPE hibernate-mapping SYSTEM
			"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
	Mapping for an Affiliation.

	@author Sharmila Ranganathan
-->
<hibernate-mapping package="edu.ur.ir.user">
	<class name="Affiliation" table="ir_user.affiliation"
		lazy="true">

		<!-- Common id property. -->
		<id name="id" type="long" column="affiliation_id"
			unsaved-value="0" access="field">
			<generator class="sequence">
				<param name="sequence">ir_user.affiliation_seq</param>
			</generator>
		</id>

		<!-- A versioned entity. -->
		<version name="version" column="version"
			access="org.hibernate.property.DirectPropertyAccessor" />

		<property name="name" column="name" type="string"
			not-null="true" access="field" />

		<property name="description" column="description" type="string"
			not-null="false" />

		<property name="author" column="is_author"
		     type="boolean" not-null="true"
			 access="field" />

		<property name="researcher" column="is_researcher"
		     type="boolean" not-null="true"
			 access="field" />

		<property name="needsApproval" column="needs_approval"
		     type="boolean" not-null="true"
			 access="field" />

	 </class>

	<!--  Get a count of affiliations in the system -->
	<query name="affiliationCount">
	    select count(*) from Affiliation
	</query>

	<!-- named query for getting all affiliations ordered by name -->
    <query name="getAllAffiliationNameAsc">from Affiliation order by name</query>

    <!-- named query for getting a affiliation-->
	<query name="getAffiliationByName">
		from Affiliation as Affiliation where
		Affiliation.name = ?
	</query>

	<!-- named query for getting a affiliation order by name desc -->
	<query name="getAffiliationsOrderByNameAsc">
		from Affiliation order by name asc
	</query>

	<!-- named query for getting a affiliation order by name desc-->
	<query name="getAffiliationsOrderByNameDesc">
		from Affiliation order by name desc
	</query>
</hibernate-mapping>


text:
package iotdataplane_test

import (
	"github.com/stretchr/testify/assert"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/iotdataplane"
)

func TestRequireEndpointIfRegionProvided(t *testing.T) {
	svc := iotdataplane.New(&aws.Config{
		Region:                 aws.String("mock-region"),
		DisableParamValidation: aws.Bool(true),
	})
	req, _ := svc.GetThingShadowRequest(nil)
	err := req.Build()

	assert.Equal(t, "", svc.Endpoint)
	assert.Error(t, err)
	assert.Equal(t, aws.ErrMissingEndpoint, err)
}

func TestRequireEndpointIfNoRegionProvided(t *testing.T) {
	svc := iotdataplane.New(&aws.Config{
		Region:                 aws.String(""),
		DisableParamValidation: aws.Bool(true),
	})
	req, _ := svc.GetThingShadowRequest(nil)
	err := req.Build()

	assert.Equal(t, "", svc.Endpoint)
	assert.Error(t, err)
	assert.Equal(t, aws.ErrMissingEndpoint, err)
}

func TestRequireEndpointUsed(t *testing.T) {
	svc := iotdataplane.New(&aws.Config{
		Region:                 aws.String("mock-region"),
		DisableParamValidation: aws.Bool(true),
		Endpoint:               aws.String("https://endpoint"),
	})
	req, _ := svc.GetThingShadowRequest(nil)
	err := req.Build()

	assert.Equal(t, "https://endpoint", svc.Endpoint)
	assert.NoError(t, err)
}


text:
'use strict';

const middleware = require('../../../src/utils/middleware.js');

const expect = require('chai').expect;
const sinon = require('sinon');

let sandbox;
describe('middleware utils', () => {

  beforeEach(() => {
    // sandbox = sinon.createSandbox();
    sandbox = sinon.sandbox.create();
  });
  afterEach(() => {
    sandbox.restore();
  });

  describe('redirectOnTrailingSlash', () => {

    let req, res, next;
    beforeEach(() => {
      req = {};
      res = {};
      res.redirect = sandbox.spy();
      next = sandbox.spy();
    });

    const restoreFuncs = [];
    before(() => {
      restoreFuncs.push((function(value) {
        if (value) {
          process.env.UI_SERVER = value;
        } else {
          delete process.env.UI_SERVER;
        }
      }).bind(null, process.env.UI_SERVER));
      process.env.UI_SERVER = process.env.UI_SERVER || null;
    });
    after(() => {
      restoreFuncs.forEach(f => f());
    });

    it('single slash, skip', () => {
      req.url = '/';

      middleware.redirectOnTrailingSlash(req, res, next);
      expect(next.callCount).to.equal(1);
    });

    it('no ending slash, skip', () => {
      req.url = '/athenz';

      middleware.redirectOnTrailingSlash(req, res, next);
      expect(next.callCount).to.equal(1);
    });

    it('with ending slash, env. not set, remove and redirect', () => {
      // sandbox.stub(process.env, 'UI_SERVER').value('');
      sandbox.stub(process.env, 'UI_SERVER', '');
      req.url = '/athenz/';

      middleware.redirectOnTrailingSlash(req, res, next);
      expect(res.redirect.callCount).to.equal(1);
      const args = res.redirect.firstCall.args;
      expect(args[0]).to.equal(301);
      expect(args[1]).to.equal('//localhost/athenz');
    });

    it('with ending slash, env. set, remove and redirect', () => {
      // sandbox.stub(process.env, 'UI_SERVER').value('athenz.server.domain');
      sandbox.stub(process.env, 'UI_SERVER', 'athenz.server.domain');
      req.url = '/athenz/';

      middleware.redirectOnTrailingSlash(req, res, next);
      expect(res.redirect.callCount).to.equal(1);
      const args = res.redirect.firstCall.args;
      expect(args[0]).to.equal(301);
      expect(args[1]).to.equal('//athenz.server.domain/athenz');
    });

    it('check open redirect vulnerability', () => {
      req.url = '//example.com/';

      middleware.redirectOnTrailingSlash(req, res, next);
      expect(res.redirect.callCount).to.equal(1);
      const args = res.redirect.firstCall.args;
      expect(args[0]).to.equal(301);
      expect(args[1].startsWith('//example.com'), 'redirect location should not start with another domain').to.false;
    });

  });

});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

  <meta name="generator" content=
  "HTML Tidy for Linux (vers 25 March 2009), see www.w3.org">

  <title>NCURSES – Manual Pages</title>
  <link rev="MADE" href="mailto:dickey@invisible-island.net">
  <meta http-equiv="Content-Type" content=
  "text/html; charset=us-ascii">

Programs:

captoinfo – convert a
        termcap description into a terminfo description

clear – clear the terminal
        screen

infocmp – compare or
        print out terminfo descriptions

infotocap – convert a
        terminfo description into a termcap description

tabs – set tabs on a
        terminal

tic – the terminfo
        entry-description compiler

toe – table of (terminfo)
        entries

tput – initialize a
        terminal or query terminfo database

tset – terminal
        initialization

Libraries:

ncurses – CRT screen
        handling and optimization package

panel- panel stack extension
        for curses

form – curses extension
        for programming forms

menu – curses extension
        for programming menus

File formats:

terminfo – terminal
        capability data base

term – format of compiled
        term file.

term – conventions for
        naming terminal types


text:
import * as helpers from '../../utils/helpers'

export function getPinnedContacts (state) {
	return state.contacts.pinnedContacts
}

export function getContact (state) {
	let contact = getCurrentContact(state)

	return (helpers.isNullOrUndefined(contact))
		? {}
		: state.contacts.pinnedContacts[contact]
}

export function getCurrentContact (state) {
	return state.contacts.currentContact
}

export function getSearchContacts (state) {
	return state.contacts.searchContacts
}

export function getSearching (state) {
	return state.contacts.searching
}